@hyperfixi/core 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -11
- package/dist/api/dom-processor.d.ts +8 -4
- package/dist/api/hyperscript-api.d.ts +5 -1
- package/dist/ast-utils/index.js +25320 -94
- package/dist/ast-utils/index.mjs +25320 -94
- package/dist/ast-utils/interchange/types.d.ts +7 -1
- package/dist/behaviors/index.js +54 -100
- package/dist/behaviors/index.mjs +54 -100
- package/dist/bundle-generator/index.js +44 -6
- package/dist/bundle-generator/index.mjs +44 -6
- package/dist/bundle-generator/parser-templates.d.ts +1 -1
- package/dist/bundle-generator/template-capabilities.d.ts +1 -1
- package/dist/chunks/bridge-C4d3blZX.js +2 -0
- package/dist/chunks/browser-modular-BwIRlrTM.js +2 -0
- package/dist/chunks/feature-eventsource-BpZvPy_K.js +2 -0
- package/dist/chunks/{feature-sockets-ClOH7vk7.js → feature-sockets-CrYvjZ4j.js} +2 -2
- package/dist/chunks/feature-webworker-BSYguEIW.js +2 -0
- package/dist/chunks/index-Beno_SBy.js +2 -0
- package/dist/commands/advanced/async.d.ts +6 -2
- package/dist/commands/advanced/js.d.ts +1 -1
- package/dist/commands/animation/start-view-transition.d.ts +24 -0
- package/dist/commands/async/fetch.d.ts +6 -1
- package/dist/commands/control-flow/repeat.d.ts +2 -0
- package/dist/commands/data/clear.d.ts +23 -0
- package/dist/commands/data/set.d.ts +6 -0
- package/dist/commands/dom/close.d.ts +19 -0
- package/dist/commands/dom/empty.d.ts +19 -0
- package/dist/commands/dom/open.d.ts +21 -0
- package/dist/commands/dom/reset.d.ts +19 -0
- package/dist/commands/dom/select.d.ts +19 -0
- package/dist/commands/dom/swap.d.ts +7 -4
- package/dist/commands/events/trigger.d.ts +1 -1
- package/dist/commands/execution/blur.d.ts +19 -0
- package/dist/commands/execution/call.d.ts +1 -2
- package/dist/commands/execution/focus.d.ts +19 -0
- package/dist/commands/helpers/element-resolution.d.ts +2 -2
- package/dist/commands/helpers/event-waiting.d.ts +1 -1
- package/dist/commands/helpers/numeric-target-parser.d.ts +7 -0
- package/dist/commands/index.d.ts +34 -2
- package/dist/commands/index.js +19374 -4848
- package/dist/commands/index.mjs +19342 -4849
- package/dist/commands/navigation/go.d.ts +3 -0
- package/dist/commands/navigation/scroll-to.d.ts +26 -0
- package/dist/commands/utility/beep.d.ts +2 -2
- package/dist/commands/utility/breakpoint.d.ts +19 -0
- package/dist/commands/utility/pick.d.ts +11 -2
- package/dist/compatibility/browser-bundle-modular.d.ts +2 -2
- package/dist/compatibility/browser-bundle-multilingual.d.ts +1 -1
- package/dist/compatibility/browser-bundle-semantic-complete.d.ts +3 -3
- package/dist/compatibility/browser-bundle.d.ts +13 -6
- package/dist/compatibility/browser-modular.d.ts +1 -3
- package/dist/core/expression-evaluator.d.ts +4 -4
- package/dist/core/expression-registry.d.ts +8 -0
- package/dist/expressions/bundles/common-expressions.d.ts +2 -2
- package/dist/expressions/bundles/core-expressions.d.ts +2 -2
- package/dist/expressions/bundles/full-expressions.d.ts +2 -2
- package/dist/expressions/bundles/index.d.ts +3 -3
- package/dist/expressions/collection/index.d.ts +35 -0
- package/dist/expressions/conversion/impl/index.d.ts +1 -1
- package/dist/expressions/index.d.ts +4 -3
- package/dist/expressions/index.js +1117 -1590
- package/dist/expressions/index.mjs +1113 -1586
- package/dist/expressions/logical/index.d.ts +2 -0
- package/dist/expressions/mathematical/index.d.ts +11 -0
- package/dist/expressions/shared/index.d.ts +1 -1
- package/dist/expressions/shared/number-utils.d.ts +1 -0
- package/dist/htmx/htmx-attribute-processor.d.ts +37 -1
- package/dist/htmx/htmx-translator.d.ts +2 -0
- package/dist/htmx/i18n-hooks.d.ts +15 -0
- package/dist/htmx/i18n-orchestrator.d.ts +15 -0
- package/dist/htmx/lang-resolver.d.ts +3 -0
- package/dist/htmx/sse.d.ts +60 -0
- package/dist/htmx/ws.d.ts +59 -0
- package/dist/hyperfixi-browser-classic-i18n.js +2 -0
- package/dist/hyperfixi-browser-minimal.js +1 -0
- package/dist/hyperfixi-browser-standard.js +2 -0
- package/dist/hyperfixi-browser.js +2 -0
- package/dist/hyperfixi-classic-i18n.js +1 -1
- package/dist/hyperfixi-hx-v4.js +1 -0
- package/dist/hyperfixi-hx.js +1 -1
- package/dist/hyperfixi-hybrid-complete.js +1 -1
- package/dist/hyperfixi-hybrid-hx.js +1 -0
- package/dist/hyperfixi-minimal.js +1 -1
- package/dist/hyperfixi-multilingual.js +1 -1
- package/dist/hyperfixi-standard.js +1 -1
- package/dist/hyperfixi.js +1 -1
- package/dist/hyperfixi.mjs +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +43613 -45063
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +43610 -45064
- package/dist/lib/index.d.ts +2 -2
- package/dist/lib/morph-adapter.d.ts +0 -13
- package/dist/lib/swap-executor.d.ts +0 -10
- package/dist/lib/view-transitions.d.ts +1 -30
- package/dist/lokascript-browser-classic-i18n.js +1 -1
- package/dist/lokascript-browser-minimal.js +1 -1
- package/dist/lokascript-browser-standard.js +1 -1
- package/dist/lokascript-browser.js +1 -1
- package/dist/lokascript-hybrid-complete.js +1 -1
- package/dist/lokascript-hybrid-hx.js +1 -1
- package/dist/lokascript-multilingual.js +1 -1
- package/dist/lsp-metadata.d.ts +9 -4
- package/dist/lsp-metadata.js +187 -3
- package/dist/lsp-metadata.mjs +185 -4
- package/dist/metadata.d.ts +1 -1
- package/dist/metadata.js +3 -3
- package/dist/metadata.mjs +3 -3
- package/dist/multilingual/bridge.d.ts +1 -1
- package/dist/multilingual/index.js +79 -22
- package/dist/multilingual/index.mjs +79 -22
- package/dist/parser/command-parsers/animation-commands.d.ts +1 -0
- package/dist/parser/command-parsers/utility-commands.d.ts +1 -0
- package/dist/parser/extensions.d.ts +51 -0
- package/dist/parser/full-parser.js +1224 -899
- package/dist/parser/full-parser.mjs +1224 -899
- package/dist/parser/helpers/ast-helpers.d.ts +1 -0
- package/dist/parser/helpers/parsing-helpers.d.ts +4 -0
- package/dist/parser/hybrid/index.js +7 -0
- package/dist/parser/hybrid/index.mjs +7 -0
- package/dist/parser/hybrid/parser-core.js +7 -0
- package/dist/parser/hybrid/parser-core.mjs +7 -0
- package/dist/parser/hybrid/tokenizer.js +7 -0
- package/dist/parser/hybrid/tokenizer.mjs +7 -0
- package/dist/parser/hybrid-parser.js +7 -0
- package/dist/parser/hybrid-parser.mjs +7 -0
- package/dist/parser/parser-types.d.ts +8 -28
- package/dist/parser/parser.d.ts +3 -7
- package/dist/parser/pratt-parser.d.ts +0 -3
- package/dist/parser/runtime.d.ts +4 -0
- package/dist/parser/semantic-integration.d.ts +17 -0
- package/dist/parser/types.d.ts +7 -1
- package/dist/reference/index.js +91 -0
- package/dist/reference/index.mjs +91 -0
- package/dist/registry/index.js +12866 -5876
- package/dist/registry/index.mjs +12866 -5876
- package/dist/registry/universal-types.d.ts +2 -1
- package/dist/runtime/command-adapter.d.ts +23 -16
- package/dist/runtime/plugin.d.ts +14 -0
- package/dist/runtime/runtime-base.d.ts +32 -7
- package/dist/runtime/runtime-factory.d.ts +3 -3
- package/dist/runtime/runtime.d.ts +2 -2
- package/dist/test-setup.d.ts +1 -0
- package/dist/types/base-types.d.ts +3 -0
- package/dist/types/feature-types.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/package.json +26 -20
- package/vocab/htmx/ar.js +60 -0
- package/vocab/htmx/bn.js +49 -0
- package/vocab/htmx/de.js +60 -0
- package/vocab/htmx/en.js +21 -0
- package/vocab/htmx/es.js +60 -0
- package/vocab/htmx/fr.js +59 -0
- package/vocab/htmx/he.js +40 -0
- package/vocab/htmx/hi.js +60 -0
- package/vocab/htmx/id.js +57 -0
- package/vocab/htmx/it.js +58 -0
- package/vocab/htmx/ja.js +60 -0
- package/vocab/htmx/ko.js +60 -0
- package/vocab/htmx/ms.js +35 -0
- package/vocab/htmx/pl.js +60 -0
- package/vocab/htmx/pt.js +60 -0
- package/vocab/htmx/qu.js +60 -0
- package/vocab/htmx/ru.js +60 -0
- package/vocab/htmx/sw.js +59 -0
- package/vocab/htmx/th.js +49 -0
- package/vocab/htmx/tl.js +33 -0
- package/vocab/htmx/tr.js +60 -0
- package/vocab/htmx/uk.js +60 -0
- package/vocab/htmx/vi.js +51 -0
- package/vocab/htmx/zh.js +60 -0
- package/dist/bundles/test-minimal.d.ts +0 -3
- package/dist/bundles/test-standard.d.ts +0 -3
- package/dist/chunks/bridge-BlRqsZT4.js +0 -2
- package/dist/chunks/browser-modular-AbV0Ql4i.js +0 -2
- package/dist/chunks/feature-eventsource-B5F2-H1r.js +0 -2
- package/dist/chunks/feature-webworker-3bAp0ac9.js +0 -2
- package/dist/chunks/index-BDYQHwCF.js +0 -2
- package/dist/compatibility/browser-bundle-minimal.d.ts +0 -8
- package/dist/compatibility/browser-bundle-standard.d.ts +0 -8
- package/dist/compatibility/hyperscript-tests/test-adapter.d.ts +0 -13
- package/dist/core/base-expression-evaluator.d.ts +0 -74
- package/dist/core/binary-expression-evaluator.d.ts +0 -7
- package/dist/core/call-expression-evaluator.d.ts +0 -7
- package/dist/core/configurable-expression-evaluator.d.ts +0 -5
- package/dist/core/lazy-expression-evaluator.d.ts +0 -22
- package/dist/core/parser.d.ts +0 -21
- package/dist/core/selector-evaluator.d.ts +0 -15
- package/dist/core/template-literal-evaluator.d.ts +0 -5
- package/dist/expressions/comparison/index.d.ts +0 -80
- package/dist/expressions/comparison/utils.d.ts +0 -2
- package/dist/expressions/conversion/impl/bridge.d.ts +0 -117
- package/dist/expressions/logical/impl/pattern-matching.d.ts +0 -58
- package/dist/expressions/positional/impl/bridge.d.ts +0 -95
- package/dist/expressions/property/index.d.ts +0 -55
- package/dist/expressions/references/impl/bridge.d.ts +0 -54
- package/dist/extensions/index.d.ts +0 -3
- package/dist/extensions/tailwind.d.ts +0 -22
- package/dist/mod.d.ts +0 -63
- package/dist/parser/expression-parser.d.ts +0 -6
- package/dist/runtime/runtime-experimental.d.ts +0 -18
- package/dist/scripts/code-generator.d.ts +0 -64
- package/dist/scripts/generate-missing-commands.d.ts +0 -4
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var hyperfixi=function(){"use strict";const e="then",t="else",n="end",r="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",f="to",h="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],N=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),C=e=>E.has(e.toLowerCase()),T=e=>x.has(e.toLowerCase()),O=e=>N.has(e.toLowerCase()),R=e=>$.has(e.toLowerCase()),$=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),L=new Set(["me","it","you","result","my","its","your"]),I=new Set(["and","or","not","no"]),j=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","ignoring case","sorted by","mapped to","split by","joined by"]),M=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),D=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var P;!function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(P||(P={}));const B=new Set(["+","-","*","/","mod"]),F=new Set(["ms","s","seconds","minutes","hours","days"]);function V(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function _(e){const t=e.input[e.position];return e.position++,"\n"===t?(e.line++,e.column=1):"\r"===t?("\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1):e.column++,t}function q(e){const t=e.input,n=t.length;for(;n>e.position;){const n=t[e.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;_(e)}}function H(e,t,n,r,s){const i=r??e.position-n.length,o=e.position;let a=e.column-n.length;if(void 0!==r){a=1;let t=-1;for(let n=0;r>n;n++)"\n"!==e.input[n]&&"\r"!==e.input[n]||(t=n);a=r-t}const c={kind:t,value:n,start:i,end:o,line:U(e,i),column:a};e.tokens.push(c)}function U(e,t){let n=1;for(let r=0;t>r&&e.input.length>r;r++){const t=e.input[r];"\n"===t?n++:"\r"===t&&(n++,e.input.length>r+1&&"\n"===e.input[r+1]&&r++)}return n}function W(e){const t=e.position;let n="";for(_(e),_(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=_(e);H(e,P.COMMENT,"--"+n,t)}function z(e){const t=e.position,n=_(e);let r=n;for(;e.input.length>e.position;){const t=_(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=_(e))}H(e,P.STRING,r,t)}function J(e){const t=e.position;_(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){_(e);break}if("\\"===t){if(_(e),e.input.length>e.position){const t=_(e);switch(t){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=t}}}else n+=_(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);H(e,P.TEMPLATE,n,t)}function Z(e){const t=e.position;let n=_(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=_(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=_(e),"}"===t)break}H(e,P.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if(!ne(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=_(e)}H(e,P.SELECTOR,n,t)}}function G(e){const t=e.position;let n="";for(n+=_(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=_(e),"/"===t&&">"===r){n+=_(e);break}}H(e,P.SELECTOR,n,t)}function K(e){const t=e.position;let n=_(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!ne(t)&&"_"!==t&&"-"!==t)break;n+=_(e)}H(e,P.SYMBOL,n,t)}function X(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===V(e,1))return n="'s",_(e),_(e),void H(e,P.OPERATOR,n,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(n=i,_(e),_(e),_(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(n=s,_(e),_(e)):n=_(e),H(e,P.OPERATOR,n,t)}function Y(e){const t=e.position,n=e.input,r=n.length;let s="";for(;r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=_(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(s+=_(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=_(e)}if(r>e.position){const t=n[e.position];if("e"===t||"E"===t){const t=r>e.position+1?n[e.position+1]:"",i=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=_(e),"+"!==n[e.position]&&"-"!==n[e.position]||(s+=_(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;s+=_(e)}}}const i=e.position;let o="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;o+=_(e)}F.has(o)?H(e,P.TIME,s+o,t):(e.position=i,H(e,P.NUMBER,s,t))}function Q(e){const t=e.position,n=e.input,r=n.length;let s="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=_(e)}const i=function(e,t,n){const r=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;const i=e.tokens[e.tokens.length-1];if(i&&(i.kind===P.IDENTIFIER||i.kind===P.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}q(e);let o="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;o+=_(e)}if(o){const t=o.toLowerCase(),s=`${r} ${t}`,i=function(e,t,n,r){const s=t.toLowerCase(),i=n.toLowerCase();if("at"===s){const t=e.position;if("the"===i){q(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;n+=_(e)}const s=n.toLowerCase();if("start"===s||"end"===s){q(e);let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;t+=_(e)}if("of"===t.toLowerCase())return H(e,P.IDENTIFIER,`at the ${s} of`,r),!0}return e.position=t,!1}if("start"===i||"end"===i){q(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;n+=_(e)}return"of"===n.toLowerCase()?(H(e,P.IDENTIFIER,`at ${i} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(i)return!0;const a=function(e,t,n){const r=e.position;let s=`${t} ${n}`,i=e.position;const o=[t,n];for(;8>o.length&&(q(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;t+=_(e)}if(!t)break;o.push(t.toLowerCase());const n=o.join(" ");j.has(n)&&(s=n,i=e.position)}return j.has(s)&&s!==`${t} ${n}`?(e.position=i,s):(e.position=r,null)}(e,r,t);if(a)return H(e,P.OPERATOR,a,n),!0;if(j.has(s))return H(e,P.OPERATOR,s,n),!0}return j.has(r)?(e.position=s,H(e,P.OPERATOR,t,n),!0):(e.position=s,!1)}(e,s,t);if(i)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||I.has(t)||B.has(e)||B.has(t)||j.has(t)?P.OPERATOR:P.IDENTIFIER}(s);H(e,o,s,t)}function ee(e){const t=e.position,n=e.input,r=n.length;_(e);let s="$";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=_(e)}H(e,P.IDENTIFIER,s,t)}function te(e){return/[a-zA-Z]/.test(e)}function ne(e){return/[a-zA-Z0-9]/.test(e)}function re(e){let t=e.position+1,n=!1;for(;e.input.length>t;){const r=e.input[t];if("/"===r&&e.input.length>t+1&&">"===e.input[t+1])return n;if(ne(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r)n=!0,t++;else{if(" "!==r&&"\t"!==r)return!1;t++}if(t-e.position>50)return!1}return!1}function se(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const ie=function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),oe=ie,ae=ie,ce=ie,le=ie,ue=(...e)=>{oe&&console.log("🔧",...e)},fe=(...e)=>{ae&&console.log("🎯",...e)},he=(...e)=>{ce&&console.log("📝",...e)},de=(...e)=>{le&&console.log("🚀",...e)};let pe=!1,me=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(pe=!0,me=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let ye={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class ge{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(ge.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const n=e.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(e)}trySemanticParse(e){const t=performance.now();if(this.shouldSkipSemantic(e))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(e,this.language),s=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const i=r.confidence>=this.confidenceThreshold&&!!r.command,o=!i&&r.confidence>0;if(pe){const t={};if(r.command?.roles)for(const[e,n]of r.command.roles)t[e]=n.value;const a={input:e.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:r.errors,timestamp:Date.now(),duration:s};!function(e){if(!pe)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",n=Math.round(100*e.confidence),r=Math.round(100*e.threshold),s=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),e.command&&console.log("Command: "+e.command),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),me){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});me.dispatchEvent(t)}}(a),n=a,ye.totalParses++,n.semanticSuccess?ye.semanticSuccesses++:n.fallbackTriggered?ye.semanticFallbacks++:ye.traditionalParses++,ye.confidenceHistory.push(n.confidence),ye.confidenceHistory.length>100&&ye.confidenceHistory.shift(),ye.averageConfidence=ye.confidenceHistory.reduce((e,t)=>e+t,0)/ye.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var n}buildCommandNode(e){const{command:t}=e;if(!t)throw Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const n=[],r={};for(const[e,s]of t.roles){const i=this.semanticValueToExpression(s);switch(e){case"patient":case"event":n.push(i);break;case"destination":"put"===t.name?r.into=i:"add"===t.name||"append"===t.name||"prepend"===t.name?r.to=i:r.on=i;break;case"source":"fetch"===t.name?n.push(i):r.from=i;break;case"quantity":r.by=i;break;case"duration":r.over=i;break;case"responseType":r.as=i;break;case"method":r.method=i;break;case"style":r.with=i;break;case"condition":r.when=i;break;default:r[e]=i}}return{type:"command",name:t.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],n={},r=e.roles.get("loopType");r&&t.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("patient");"for"==(r?r.value+"":"")&&s&&t.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=e.roles.get("event");i&&t.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=e.roles.get("source");o&&t.push(this.semanticValueToExpression(o));const a=e.roles.get("quantity");a&&t.push(this.semanticValueToExpression(a));const c=e.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],n=e.roles.get("destination");if(n)if("property-path"===n.type){const e=n;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(n));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=e.roles.get("patient");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],n=e.roles.get("condition");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:e.name,args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(e.raw||"")}}parseExpressionString(e){let t=0;const n=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},r=()=>{n();const r=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(r,t)},s=()=>{const r=[];if(t++,n(),")"!==e[t])for(r.push(i()),n();","===e[t];)t++,n(),r.push(i()),n();return")"===e[t]&&t++,r},i=()=>{n();const i=r();if(!i)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;e.length>t;){n();const i=e[t];if("."===i){t++;const e=r();e&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:e,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}ge.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const ve=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),be=new Set([")","]","}",","]);function we(e,t){return{infix:{bp:[e,e+1],handler:t??((t,n,r)=>{const s=r.parseExpr(e+1);return{type:"binaryExpression",operator:n.value,left:t,right:s,start:t.start,end:s.end??n.end,line:t.line??n.line,column:t.column??n.column}})}}}function Ee(e,t){return{infix:{bp:[e+1,e],handler:(t,n,r)=>{const s=r.parseExpr(e);return{type:"binaryExpression",operator:n.value,left:t,right:s,start:t.start,end:s.end??n.end,line:t.line??n.line,column:t.column??n.column}}}}}function xe(e,t){return{prefix:{bp:e,handler:t??((t,n)=>{const r=n.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:r,argument:r,prefix:!0,start:t.start,end:r.end??t.end,line:t.line,column:t.column}})}}}function ke(e){return(t,n,r)=>{const s=r.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${e?"not ":""}a/an', got: <end>`);let i=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),i=!1),{type:"typeCheckExpression",value:t,typeName:s.value,nullOk:i,negated:e,start:t.start,end:s.end}}}const Se=function(...e){const t=new Map;for(const n of e)for(const[e,r]of n){const n=t.get(e);t.set(e,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return t}(new Map([["or",we(10)],["||",we(10)],["and",we(20)],["&&",we(20)],["==",we(30)],["!=",we(30)],["<",we(30)],[">",we(30)],["<=",we(30)],[">=",we(30)],["is",we(30)],["matches",we(30)],["contains",we(30)],["starts with",we(30)],["ends with",we(30)],["does not start with",we(30)],["does not end with",we(30)],["is between",we(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!1,start:e.start,end:i.end}})],["is not between",we(30,(e,t,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:i,negated:!0,start:e.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",we(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:r,start:e.start,end:r.end}})],["sorted by",we(28,(e,t,n)=>{const r=n.parseExpr(29);let s="asc";const i=n.peek();if(i&&"string"==typeof i.value){const e=i.value.toLowerCase();"asc"===e||"ascending"===e?(n.advance(),s="asc"):"desc"!==e&&"descending"!==e||(n.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:r,order:s,start:e.start,end:r.end}})],["mapped to",we(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:r,start:e.start,end:r.end}})],["split by",we(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:r,start:e.start,end:r.end}})],["joined by",we(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:r,start:e.start,end:r.end}})],["+",{...we(40),...xe(80)}],["-",{...we(40),...xe(80)}],["*",we(50)],["/",we(50)],["%",we(50)],["mod",we(50)],["^",Ee(60)],["**",Ee(60)],["as",we(70,(e,t,n)=>{const r=n.parseExpr(71),s=n.peek();if(s&&":"===s.value&&r&&"identifier"===r.type){n.advance();const e=n.advance();e&&void 0!==e.value&&(r.name=`${r.name}:${e.value}`,r.end=e.end)}return{type:"asExpression",expression:e,targetType:r,start:e.start,end:r.end??t.end,line:e.line??t.line,column:e.column??t.column}})],["not",xe(80)],["!",xe(80)],["no",xe(80)]]),new Map([["===",we(30)],["!==",we(30)],["is not",we(30)],["am",we(30)],["is in",we(30)],["is not in",we(30)],["precedes",we(30)],["does not precede",we(30)],["follows",we(30)],["does not follow",we(30)],["is a",we(30,ke(!1))],["is an",we(30,ke(!1))],["is not a",we(30,ke(!0))],["is not an",we(30,ke(!0))],["has",we(30)],["have",we(30)],["match",we(30)],["include",we(30)],["includes",we(30)],["equals",we(30)],["does not contain",we(30)],["does not include",we(30)],["is equal to",we(30)],["is not equal to",we(30)],["is really equal to",we(30)],["is not really equal to",we(30)],["really equals",we(30)],["is greater than",we(30)],["is less than",we(30)],["is greater than or equal to",we(30)],["is less than or equal to",we(30)],["in",we(30)],["of",we(30)],["really",we(30)],["exists",{prefix:{bp:80,handler:(e,t)=>({type:"unaryExpression",operator:e.value,operand:t.parseExpr(80),start:e.start})},infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["does not exist",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is not empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["some",xe(80)]]),new Map([["=",Ee(5)]])),Ae=new Map,Ne=new Map,Ce=new Map,Te=new Set,Oe=new Set,Re=new Set,$e=new Set;function Le(e){return Ae.get(e.toLowerCase())}function Ie(e){return Ce.get(e)}function je(e,t){if(0!==Oe.size)for(const n of Oe)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",e)}}function Me(e,t,n){if(0!==Re.size)for(const r of Re)try{r(e,t,n)}catch(e){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",e)}}function De(e,t){if(0!==$e.size)for(const n of $e)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",e)}}function Pe(e,t,n){if(e.globals.set(t,n),0!==Te.size)for(const r of Te)try{r(t,n,e)}catch(e){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",e)}}function Be(e){return e.kind===P.IDENTIFIER&&E.has(e.value.toLowerCase())}function Fe(e){return e.kind===P.IDENTIFIER&&D.has(e.value.toLowerCase())}function Ve(e){return e.kind===P.IDENTIFIER&&M.has(e.value.toLowerCase())}function _e(e){return e.kind===P.IDENTIFIER&&L.has(e.value.toLowerCase())}function qe(e){return j.has(e.value.toLowerCase())}function He(e){return e.kind===P.IDENTIFIER}function Ue(e){return e.kind===P.SELECTOR}function We(e){return e.kind===P.SELECTOR&&!e.value.startsWith("<")}function ze(e){return e.kind===P.STRING||e.kind===P.NUMBER||e.kind===P.TEMPLATE}function Je(e){return e.kind===P.IDENTIFIER}function Ze(e){return e.kind===P.TIME}function Ge(e){return e.kind===P.SYMBOL}function Ke(e){return e.kind===P.COMMENT}function Xe(e){if(e.kind!==P.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(E.has(t)||D.has(t)||M.has(t)||L.has(t))}function Ye(e){return e.kind===P.STRING}function Qe(e){return e.kind===P.NUMBER}function et(e){if(e.kind===P.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function tt(e){return e.kind===P.TEMPLATE}function nt(e){return e.kind===P.SELECTOR&&e.value.startsWith("<")}function rt(e){return e.kind===P.SELECTOR&&e.value.startsWith("#")}function st(e){return e.kind===P.SELECTOR&&e.value.startsWith(".")}function it(e){return e.kind===P.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function ot(e){if(e.kind!==P.OPERATOR)return!1;const t=e.value.toLowerCase();return!I.has(t)&&!j.has(t)}function at(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function ct(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function lt(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ut(e,t,n,r){return{type:"binaryExpression",operator:e,left:t,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function ft(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ht(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function dt(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function pt(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function mt(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function yt(e,t,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...n&&{source:n}}],start:e.start,end:e.end,line:e.line,column:e.column}}const gt=[{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 vt(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const bt=[e,r,t,n];function wt(e,t=[]){if(e.isAtEnd())return!0;for(const t of bt)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function Et(e,t=[]){if(!wt(e,t))return e.parseExpression()}function xt(e,t,n){return!!e.check(t)&&(e.advance(),n.push(e.createIdentifier(t)),!0)}function kt(e,t,n){for(const r of t)if(e.check(r))return e.advance(),n.push(e.createIdentifier(r)),r;return null}function St(e,t){return!!e.check(t)&&(e.advance(),!0)}function At(e){const t=e.savePosition();let n;if(e.checkIdentifierLike()){const r=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=r):e.restorePosition(t)}const r=e.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class Nt{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Nt(e.value);return t.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},t}static fromIdentifier(e){const t=new Nt(e.name);return void 0!==e.start&&(t.startPos={start:e.start,end:e.end??0,line:e.line??1,column:e.column??1}),t}static named(e){return new Nt(e)}withArgs(...e){return this.args.push(...e),this}withBody(e){return this.body=e,this}withImplicitTarget(e){return this.implicitTarget=e,this}withModifier(e,t){return this.modifiers||(this.modifiers={}),this.modifiers[e]=t,this}withModifiers(e){return this.modifiers={...this.modifiers,...e},this}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=e,this}blocking(e=!0){return this.isBlocking=e,this}startingAt(e){return this.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},this}endingAt(e){return this.endPos={start:e.start??this.startPos?.start??0,end:e.end,line:e.line??this.startPos?.line??1,column:e.column??this.startPos?.column??1},this}build(){const e={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(e.body=this.body),this.implicitTarget&&(e.implicitTarget=this.implicitTarget),this.modifiers&&(e.modifiers=this.modifiers),this.originalCmd&&(e.originalCommand=this.originalCmd),e}clone(){const e=new Nt(this.name);return e.args=[...this.args],e.body=this.body?[...this.body]:void 0,e.implicitTarget=this.implicitTarget,e.isBlocking=this.isBlocking,e.modifiers=this.modifiers?{...this.modifiers}:void 0,e.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function Ct(e,t){const n=[];let r="";const s=e.peek().start||0,i=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(r=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),r+=":",e.checkIdentifierLike()&&(r+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=At(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),n.push({type:"functionCall",name:r,args:t,start:s,end:e.getPosition().end,line:i,column:o})}else n.push({type:"string",value:r,start:s,end:e.getPosition().end,line:i,column:o})}const a=[...n];for(;!wt(e);){if(e.check("on")||e.check("to")){const t=e.advance().value;a.push(e.createIdentifier(t));continue}a.push(e.parsePrimary())}return Nt.fromIdentifier(t).withArgs(...a).endingAt(e.getPosition()).build()}function Tt(e,t){const n=[];if(e.check(b)){const t=e.advance();if(n.push({type:"identifier",name:b,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(y)){const t=e.advance();n.push({type:"identifier",name:y,start:t.start,end:t.end,line:t.line,column:t.column})}}return Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Ot(r,s){const i=[];let o=!1;const a=r.savePosition();for(let t=0;500>t&&!r.isAtEnd();t++){const t=r.peek();if(t.value===e){o=!0;break}if(t.value===n||t.value===g||"def"===t.value||t.value===m)break;r.advance()}r.restorePosition(a);let c=!1;if(!o){const e=r.savePosition(),i=s.line,o=100;for(;!r.isAtEnd()&&o>r.current-e;){const e=r.peek(),s=e.value?.toLowerCase();if(s===g||"def"===s||s===m)break;if(s===t||s===n){e.line===i&&(c=!0);break}if((r.checkIsCommand()||r.isCommand(s))&&void 0!==e.line&&e.line!==i){c=!0;break}r.advance()}r.restorePosition(e)}const l=o||c;let u;if(l)u=r.parseExpression();else{const t=[],n=20;let i=0;for(;!r.isAtEnd()&&!r.checkIsCommand()&&!r.isCommand(r.peek().value)&&!r.check(e)&&n>i;){const e=r.savePosition();t.push(r.parseLogicalAnd()),r.savePosition()===e&&r.advance(),i++}if(0===t.length)throw Error("Expected condition after if/unless");u=1===t.length?t[0]:{type:"expression",tokens:t,start:t[0].start,end:t[t.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&r.advance();const e=[];for(;!r.isAtEnd()&&!r.check(t)&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const t=r.parseCommand();t&&e.push(t)}if(0===e.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(ft(e,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}));let a=!1;if(r.check(t))if(r.advance(),r.check("if")){const e=r.peek();r.advance();const t=Ot(r,e);i.push(ft([t],{start:e.start,end:r.getPosition().end,line:e.line,column:e.column})),a=!0}else{const e=[];for(;!r.isAtEnd()&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const t=r.parseCommand();t&&e.push(t)}i.push(ft(e,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const e=r.parseCommand();i.push(ft([e],{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}}return Nt.from(s).withArgs(...i).endingAt(r.getPosition()).build()}function Rt(e,t){const n=[],r={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(n.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();n.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();r.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}function $t(e,t){const n=[],r=Et(e,[h]);r&&n.push(r),xt(e,h,n);const s=Et(e);return s&&n.push(s),Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Lt(e,t){const n=[];if(e.check("between")){e.advance(),n.push(e.createIdentifier("between"));const i=Et(e,[r]);i&&n.push(i),xt(e,r,n);const o=Et(e,[h,m,s]);if(o&&n.push(o),kt(e,[h,m],n)){const t=Et(e);t&&n.push(t)}return Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}const i=Et(e,[h,m]);if(i&&n.push(i),kt(e,[h,m],n)){const t=Et(e);t&&n.push(t)}return Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function It(e,t){const r=e.parseExpression();if(!r)return e.addError("Put command requires content expression"),null;const s=e.peek();if(!s||!A.includes(s.value))return e.addError(`Expected operation keyword (${A.join(", ")}) after put expression, got: ${s?.value}`),null;let i=e.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=S:"at"===i&&(e.check(w)||e.check(b)?(St(e,b),e.check(w)&&(e.advance(),e.check(p)&&(e.advance(),i=k))):e.check(n)&&(e.advance(),e.check(p)&&(e.advance(),i=S)));const a=e.parseExpression();return a?Nt.fromIdentifier(t).withArgs(r,e.createIdentifier(i),a).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const jt=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Mt(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end}}(s)??function(e){if(!e.check(v)&&!e.check("local"))return null;const t=e.advance(),n=e.advance();return{type:"identifier",name:n.value,scope:t.value,start:t.start,end:n.end}}(s)??function(e){if(!e.check(b))return null;const t=e.savePosition();e.advance();const n=e.parseExpression();if(!n)return e.restorePosition(t),null;if("binaryExpression"===n.type&&n.operator===p){const e=n.left,t=n.right;return mt(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(f)?n:(e.restorePosition(t),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const e=s.advance();return{expression:{type:"identifier",name:e.value,scope:"local",start:e.start,end:e.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(f)||s.check(e)||s.check(r)||s.check(t)||s.check(n));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const e=(e,t)=>e[t];if(e(i[0],"value")===b&&e(i[2],"value")===p){const t=i[1],n=i[3];return{expression:mt(lt(e(t,"value")||e(t,"name")||"",{start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:e(n,"value")||e(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:i[0].start??0,end:n.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(f)){const e=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+e)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(f)),l&&u.push(l),Nt.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function Dt(e,t){const n=[];for(;!wt(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)n.push(e.parsePrimary());return Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Pt(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||wt(e)}function Bt(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function Ft(e){const t=[],n=e.getPosition();do{if(!e.checkIdentifierLike())break;const n=e.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};e.consume(":","Expected ':' after property name in fetch named arguments");const s=e.parsePrimary();s&&t.push({key:r,value:s})}while(e.match(",")&&!e.isAtEnd());const r=e.getPosition();return{type:"objectLiteral",properties:t,start:n.start,end:r.end,line:n.line,column:n.column}}class Vt{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new ge({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors]),e}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}const e=this.peek(),t=e&&Le(e.value)?e.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==t){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def")){const t=this.peek(),n=t?Le(t.value):void 0;if(n){const t=this.advance(),r=n(this.getContext(),t);r&&e.push(r);continue}break}{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){he("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];he(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){he(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(he("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,he(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),he(`✅ 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 he("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error};he("✅ PARSER: No more event handlers, at end of input");break}}return he(`✅ PARSER: Finished parsing, creating Program node with ${t.length} statements`),this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return n&&["number","string","identifier"].includes(e.kind)?this.addError(`Unexpected token: ${e.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+e.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,warnings:this.warnings}}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,n=this.prattCache.get(t);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),s=Vt.PRATT_TABLE.get(r.value);let i;if(s?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();i=s.prefix.handler(e,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const t=this.peek(),n=Vt.PRATT_TABLE.get(t.value);if(!n?.infix){if(ve.has(t.value)||be.has(t.value))break;break}const[r]=n.infix.bp;if(e>r)break;if("="===t.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(e){he("arrow body discarded after error:",e instanceof Error?e.message:e+"")}return this.createErrorNode()}if("+"===t.value||"-"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("+"===e.value||"-"===e.value))return this.addError(`Invalid operator combination: ${t.value}${e.value}`),i}if("*"===t.value||"/"===t.value||"%"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("*"===e.value||"/"===e.value||"%"===e.value||"+"===e.value||"-"===e.value))return this.addError("*"===t.value&&"*"===e.value?"Unexpected token: "+e.value:`Invalid operator combination: ${t.value}${e.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Vt.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=n.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(t,{node:i,endPos:this.current}),i}makePrattContext(){const e=this;return{peek:()=>e.tokens.length>e.current?e.tokens[e.current]:void 0,advance:()=>{const t=e.tokens[e.current];return e.current++,t},parseExpr:t=>e.parseExpressionPratt(t),isStopToken:()=>{const t=e.tokens[e.current];return!t||ve.has(t.value)||be.has(t.value)},atEnd:()=>e.current>=e.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else if("wait"===e.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):C(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):O(e)}createCommandFromIdentifier(e){const t=[],n=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:!1,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return T(e)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return It(s,i);case"trigger":case"send":return Ct(s,i);case"remove":return $t(s,i);case"toggle":return Lt(s,i);case"set":return Mt(s,i);case"halt":return Tt(s,i);case"measure":return Rt(s,i);case"js":return function(e,t){const r=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&r.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const s=e.peek().start,i=function(e,t){const n=e.getInputSlice(t);if(!n)return t;let r=0;for(;n.length>r;){const e=n[r];if("'"!==e&&"’"!==e&&"‘"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===e&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==e&&"E"!==e||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return t+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==e;)"\\"===n[r]&&r++,r++;r++}}return t+n.length}(e,s);for(;!e.isAtEnd()&&!e.check(n)&&e.peek().start<i;)e.advance();e.consume(n,"Expected end after js code body");const o={type:"literal",value:e.getInputSlice(s,i).trim(),start:t.start,end:e.getPosition().end},a={type:"arrayLiteral",elements:r.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Nt.fromIdentifier(t).withArgs(o,a).endingAt(e.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const e=s.parseCommand();if(!e)break;a.push(e)}catch{break}if(s.match(r))continue;if(s.check(e)||s.check(t)||s.check(n))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return Nt.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(e,t){const n=Nt.fromIdentifier(t);St(e,b);const r=e.peek().value,s=e=>({type:"literal",value:e,start:t.start,end:t.end}),i=()=>{if(!e.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return e.parseExpression()};if("first"===r){e.advance();const t=e.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===r){e.advance();const t=e.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===r){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const r=i(),o=n.withArgs(r).withModifier("variant",s("random"));return t&&o.withModifier("count",t),o.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?s("start"):e.parsePrimary();let o=!1;(e.match("to")||e.match(".."))&&(e.match("end")?o=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=i(),l=n.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",t).withModifier("rangeMode",s(a));return o?l.withModifier("rangeEnd",s("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(e.getPosition()).build()}if("match"===r||"matches"===r){e.advance(),e.match("of");const t=e.parsePrimary();let o;e.matchOperator("|")&&(o=e.advance().value);const a=i(),c=n.withArgs(a).withModifier("variant",s("match"===r?"match":"matches")).withModifier("regex",t);return o&&c.withModifier("flags",s(o)),c.endingAt(e.getPosition()).build()}return Dt(e,t)}(s,i);case"start":return function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd();return Nt.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(s,i);case"swap":case"morph":return function(e,t){const n=[];let r=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const s=t.value.toLowerCase();jt.includes(s)&&(r=s,e.advance(),n.push(e.createIdentifier(r)))}}if("delete"===r){const r=e.parseExpression();return r&&n.push(r),Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(p)&&(e.advance(),n.push(e.createIdentifier("of")));const s=e.parseExpression();if(s&&n.push(s),!e.isAtEnd()&&e.check(d)){e.advance(),n.push(e.createIdentifier("with"));const t=e.parseExpression();t&&n.push(t)}return Nt.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(s,i);default:return Dt(s,i)}}(this.getContext(),s)}parsePutCommand(e){return It(this.getContext(),e)}parseSetCommand(e){return Mt(this.getContext(),e)}parseHaltCommand(e){return Tt(this.getContext(),e)}parseMeasureCommand(e){return Rt(this.getContext(),e)}parseTriggerCommand(e){return Ct(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(he("🔄 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){he("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),s=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||s){he(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&&(he("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(he("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(e){he("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n}}else this.checkIdentifier()&&he("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){he("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(he("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)he("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))he("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){he("📍 No separator and no command, breaking. Current token:",this.peek().value);break}he("✅ Next token is a command, continuing without separator")}}let r="end";for(const t of e)if(this.check(t)){r=t;break}return this.check("end")||e.some(e=>this.check(e))||(r=""),he("✅ parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(){const{commands:e}=this.parseCommandListUntilTerminator([]);if(he('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw he('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return he('✅ Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",f=null,p=null,m=null,g=null,v=null,w=null;if(e.check(s)){e.advance(),r=s;const t=e.peek();He(t)&&(v=t.value,e.advance()),e.check(u)&&(e.advance(),g=e.parseExpression())}else if(e.check(u))e.advance(),r=s,v="it",g=e.parseExpression();else if(e.check(i))e.advance(),r=i,m=e.parseExpression();else if(e.check(o))if(e.advance(),r=o,e.check(y)){e.advance(),r="until-event";const t=e.peek();if(he("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!He(t)&&!Ve(t))throw Error('Expected event name after "event"');if(f=t.value,e.advance(),he("✅ Got event name:",f,"Next token:",e.peek().value),he('🔍 Checking for "from", current token:',e.peek().value),e.check(h)){he('✅ Found "from", advancing...'),e.advance(),he('📍 After consuming "from", current token:',e.peek().value),St(e,b)&&he('✅ Found "the", advancing...');const t=e.peek();he("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),p=e.parsePrimary(),he("✅ After parsePrimary, eventTarget:",p)}else he('❌ No "from" found, skipping target parsing')}else m=e.parseExpression();else e.check(a)?(e.advance(),r=a):(w=e.parseExpression(),e.check(c)&&(e.advance(),r=c));let E,x=null;if(e.check(d)){const t=e.peekAt(1);t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),x=l)}else if(e.check(l)){e.advance();const t=e.peek();He(t)?(x=t.value,e.advance()):x=l}let k=null,S=!1;if(r===a){const t=e.parseRepeatBody();if(E=t.commands,"else"===t.terminator)e.advance(),k=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(S=!0,r=t.terminator,e.advance(),m=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();E=t.commands,t.hasElse&&(e.advance(),k=e.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column});const A={start:t.start,end:t.end,line:t.line,column:t.column};v&&n.push(ht(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(ht(f,A)),p&&n.push(p),x&&n.push(ht(x,A)),n.push(ft(E,{...A,end:A.end||0})),null!==k&&n.push(ft(k,{...A,end:A.end||0}));const N=Nt.from(t).withArgs(...n);return S&&N.withModifier("bottomTested",{type:"literal",value:!0,...A}),N.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const n=[];let r=null,s=null;e.check("each")&&e.advance();const i=e.peek();if(!He(i))throw Error('Expected variable name after "for"');if(r=i.value,e.advance(),!e.check(u))throw Error('Expected "in" after variable name in for loop');if(e.advance(),s=e.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(e.check(d)){const t=e.peekAt(1);t&&t.value.toLowerCase()===l&&(e.advance(),e.advance(),o=l)}else if(e.check(l)){e.advance();const t=e.peek();He(t)?(o=t.value,e.advance()):o=l}const a=e.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(ht(r,c)),n.push(s),o&&n.push(ht(o,c)),n.push(ft(a,{...c,end:c.end||0})),Nt.from({...t,value:"repeat"}).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const n=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!wt(e)){const r=e.parseExpression();return n.push(r),Nt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{const t=e.peek();if(!He(t))throw Error('Expected event name after "for"');const n=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!He(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(r.push({name:n,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(h)&&(e.advance(),St(e,b),s=e.parsePrimary());const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(pt(r.map(e=>dt([{key:lt("name",i),value:ct(e.name,`"${e.name}"`,i)},{key:lt("args",i),value:pt(e.params.map(e=>ct(e,`"${e}"`,i)),i)}],i)),i)),s&&n.push(s)}return Nt.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const n=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=e.advance().value,s=e.previous();if(n.push(lt(r,{start:s.start,end:s.end,line:s.line,column:s.column})),e.check("(")){e.advance();const r=[];for(;!e.isAtEnd()&&!e.check(")");)if(r.push(At(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),r.length>0){const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(dt(r.map(e=>({key:e.name?lt(e.name,s):ct("_positional","_positional",s),value:e.value})),s))}}return Nt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let s=null;const i=e.peek();if(He(i)||"*"===i.value){let t="";e.check("*")&&(t="*",e.advance());const n=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);n&&(t+=n,s={type:"string",value:t,start:i.start||0,end:e.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(n.push(s),!e.check(f))throw Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(r.to=o,e.check("over")){e.advance();const t=e.parsePrimary();r.over=t}if(e.check(d)){e.advance();const t=e.parsePrimary();r.with=t}return Nt.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=Et(e,[f]);t&&n.push(t)}if(e.check(f)){e.advance();const t=Et(e);t&&n.push(t)}return Nt.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return Ot(this.getContext(),e)}parseRemoveCommand(e){return $t(this.getContext(),e)}parseToggleCommand(e){return Lt(this.getContext(),e)}parseRegularCommand(e){return Dt(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("?.")){const t=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(e,this.createIdentifier(t.value),!1);n.optional=!0,e=n}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}else{if(!this.check("'s"))break;{let t;this.advance(),this.check("*")?(this.advance(),t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):t=Ge(this.peek())&&this.peek().value.startsWith("@")?this.advance().value:this.consumeIdentifier("Expected property name after possessive").value,e=this.createPossessiveExpression(e,this.createIdentifier(t))}}return e}parsePrimary(){if(this.check("*")){const e=this.current;if(this.advance(),!this.isAtEnd()&&He(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),n=this.processEscapeSequences(t);return this.createLiteral(n,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value.slice(1,-2).trim(),t=this.createSelector(e);return t.fromQuery=!0,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 e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end,line:e.line,column:e.column}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if((!e||"end"!==e.value&&"else"!==e.value&&"then"!==e.value)&&(this.matchPredicate(Xe)||this.matchPredicate(Fe)||this.matchPredicate(_e)||this.matchPredicate(Be)||this.matchPredicate(Ve))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(e.value):this.parseNavigationFunction(e.value)}const t=this.check(".")||this.check("?.");return"my"!==e.value||t?"its"!==e.value||t?"your"!==e.value||t?"the"===e.value?this.parseTheXofY():"values"===e.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:e.line,column:e.column}):this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if(Ge(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const e=this.advance().value;return this.createLiteral(e,"$"+e)}if(this.checkIdentifier()){const e=this.advance();let t=this.createIdentifier(e.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const e=this.advance();t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}}return{type:"dollarExpression",expression:t,raw:`$${e.value}${this.previous().value||""}`,line:e.line,column:e.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.matchPredicate(Xe))t=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const e=this.previous().value,n=e.slice(1,-1);t=this.createLiteral(n,e)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(e.push({key:t,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Xe))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);n=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let s=!1,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),"$"===e.value&&this.check("{")&&(s=!0),"{"===e.value&&i++,"}"===e.value&&i--}const o=r.join(""),a=s?{type:"templateLiteral",value:o,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(o,o);if(t.push({key:n,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),n=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column},arguments:r,isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(e,t){const n=e.callee.name,r=this.peek();if(!(Vt.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Xe(r)&&!this.isCommand(r.value)||_e(r)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),Vt.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,s,i,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(he("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return he("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseEventHandler(){he("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[];let t=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const e=this.tokens[this.current+1],n=e?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),t=!0,he("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),he("🔧 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),he("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),he("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(he("🔧 parseEventHandler: Total events parsed: "+e.join(", ")),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);r=e?.name,he(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const s=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();s.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),he("🔧 parseEventHandler: Parsed event parameters: "+s.join(", "))}const i={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)i.once=!0,he("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)i.prevent=!0,he("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)i.stop=!0,he("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),n=parseInt(t.value,10);if(isNaN(n))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(i.debounce=n,he(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,he(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else he(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}if(this.check("debounced")||this.check("throttled")){const e=this.advance().value.toLowerCase(),t="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const n=this.advance(),r=(o=n.value).endsWith("ms")?parseInt(o,10):o.endsWith("seconds")||o.endsWith("s")?1e3*parseFloat(o):o.endsWith("minutes")?6e4*parseFloat(o):o.endsWith("hours")?36e5*parseFloat(o):o.endsWith("days")?864e5*parseFloat(o):parseInt(o,10);i[t]=r,he(`🔧 parseEventHandler: Parsed '${e} at ${n.value}' (${r}ms)`)}else if(this.matchNumber()){const n=parseInt(this.previous().value,10);i[t]=n,he(`🔧 parseEventHandler: Parsed '${e} at ${n}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`)}var o;let a,c,l,u;if(t&&(i.once=!0),Object.keys(i).length>0&&he("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(a=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();c=e.value,he(`🔧 parseEventHandler: Parsed 'from' target: ${c} (kind: ${e.kind})`)}if(this.match("of")){const e=this.advance();l=e.value.startsWith("@")?e.value.substring(1):e.value,he("🔧 parseEventHandler: Parsed attribute name: "+l)}this.match("in")&&(he("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),he("🔧 parseEventHandler: Parsed watch target expression"));const f=[];for(he(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(he(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){he("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())he("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){he("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const n=this.parseCommand();f.push(n);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(f.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.parseCommandWithErrorRecovery();e&&(f.push(e),he("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&f.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){he("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(f.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator)break;{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name))break;{const n={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};f.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),d={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:f,...s.length>0&&{params:s},...a&&{condition:a},...c&&{target:c},...l&&{attributeName:l},...u&&{watchTarget:u},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:h.start,end:h.end,line:h.line,column:h.column};return he(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${l||"none"}, watchTarget: ${u?"yes":"none"}`),d}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Xe(e)?(n.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),n=r.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),i=t.value,this.advance())}}const o={type:"eventHandler",event:t,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...n.length>0&&{args:n},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:n,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,n=this.parseCommand();for(this.error&&this.error!==t&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(he("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)he("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){he('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const t=this.peek(),n=this.getPosition(),r="Expected command, got: "+t.value;this.addError(r);const s=yt(n,r,t.value);if(e.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===e.length?e[0]:function(e){return{type:"CommandSequence",commands:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1}}(e)}getMultiWordPattern(e){return function(e){return gt.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return vt(e,t)}parseMultiWordCommand(e,t){return function(e,t,n){const r=e.getMultiWordPattern(n);if(!r)return null;const s=[],i={};for(;!wt(e,["catch","finally",...r.keywords])&&!vt(e.peek(),r.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&vt(e.peek(),r.keywords))break}for(;!e.isAtEnd()&&vt(e.peek(),r.keywords);){const t=e.advance().value,n=e.parseExpression();if(n&&(i[t]=n),!vt(e.peek(),r.keywords))break}const o=Nt.from(t).withArgs(...s).endingAt(e.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();t.push(e)}}return t}trySemanticParse(e){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const t=this.semanticAdapter.trySemanticParse(e);return t.success&&t.node?(he(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(he(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return he("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),n=t.value.toLowerCase();if(e.includes(n))break;if(Be(t))break;this.advance()}}parseCommand(){const e=this.previous();let t=e.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(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return function(e,t){const n={};let r=null;if(!e.isAtEnd()&&e.check("/")&&(r=function(e){const t=e.savePosition();let n="";for(;!e.isAtEnd()&&!Pt(e);)n+=e.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:t,end:e.savePosition()}:(e.restorePosition(t),null)}(e)),r||(r=e.parsePrimary()),!r)return e.addError("fetch requires a URL"),Nt.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(n.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||n.as){if(!e.check("with")||n.with){if(e.check("do")&&!n.doNotThrow){const t=e.peekAt(1),r=e.peekAt(2);if("not"===t?.value&&"throw"===r?.value){const t=e.advance();e.advance();const r=e.advance();n.doNotThrow={type:"literal",value:!0,start:t.start,end:r.end,line:t.line,column:t.column};continue}}break}e.advance(),n.with=Bt(e)?Ft(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||St(e,"a")||St(e,"an"),n.as=e.parsePrimary();const s=Nt.from(t).withArgs(r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}(this.getContext(),e);const n=this.parseMultiWordCommand(e,t);if(n)return n;const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||function(e,t){return{type:"command",name:e,args:[],partial:!0,start:t.start,end:t.end,line:t.line,column:t.column}}(r,this.getPosition());const s=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const n=t.value,r="increment"===n?"+":"-";let s=!1;e.check(v)&&(s=!0,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+n);let o;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);o=t}else o=ct(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:t.start,end:e.previous().end,line:t.line,column:t.column},l=ut(r,i,o,c),u=[a,lt(f,c),l];return Nt.from(t).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(this.getContext(),e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const e=this.parseExpression();if(s.push(e||this.parsePrimary()),this.match(","))continue;const t=["into","from","to","with","by","at","before","after","over"];if(t.some(e=>this.check(e)))continue;const n=s[s.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!t.includes(n.name??n.value))break}const i=this.getPosition();return{type:"command",name:t,args:s,isBlocking:!1,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(e),t)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;return["first","last","next","previous","random","closest"].includes(t)?(this.advance(),this.parseNavigationFunction(t)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parsePrimary(),line:e.line,column:e.column}):this.createIdentifier(t))}parseContextPropertyAccess(e){if("me"===e&&this.match("*")){let t="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(""),!1);for(t=this.advance().value;this.check("-")&&!this.isAtEnd();){if(t+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}t+=this.advance().value}const n="computed-"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n),!1)}{if(Ge(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}const t=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;R(t)&&he(`💡 Tip: CSS functions like ${t}() should be quoted for clean parsing. Use '${t}(...)' or \`${t}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return ct(e,t,this.getPosition())}createIdentifier(e){return lt(e,this.getPosition())}createBinaryExpression(e,t,n){return ut(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(he(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return he("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return he(`✅ createProgramNode: Returning single statement (type=${e[0].type})`),e[0];const t={type:"Program",statements:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1};return he(`✅ createProgramNode: Returning Program node with ${e.length} statements, type=${t.type}`),t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!ot(t)||t.value!==e||(this.advance(),0))}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(We)}matchSelector(){return this.matchPredicate(We)}checkAnySelector(){return this.checkPredicate(Ue)}checkLiteral(){return this.checkPredicate(ze)}checkIdentifierLike(){return this.checkPredicate(He)}checkIsCommand(){return this.checkPredicate(Be)}checkCommandTerminator(){return this.checkPredicate(at)}checkReference(){return this.checkPredicate(Je)}checkTimeExpression(){return this.checkPredicate(Ze)}checkEvent(){return this.checkPredicate(Ve)}checkContextVar(){return this.checkPredicate(_e)}checkComment(){return this.checkPredicate(Ke)}checkIdentifier(){return this.checkPredicate(Xe)}checkKeyword(){return this.checkPredicate(Fe)}checkString(){return this.checkPredicate(Ye)}matchString(){return this.matchPredicate(Ye)}checkNumber(){return this.checkPredicate(Qe)}matchNumber(){return this.matchPredicate(Qe)}checkBoolean(){return this.checkPredicate(et)}matchBoolean(){return this.matchPredicate(et)}checkTemplateLiteral(){return this.checkPredicate(tt)}matchTemplateLiteral(){return this.matchPredicate(tt)}checkQueryReference(){return this.checkPredicate(nt)}matchQueryReference(){return this.matchPredicate(nt)}checkIdSelector(){return this.checkPredicate(rt)}checkClassSelector(){return this.checkPredicate(st)}checkCssSelector(){return this.checkPredicate(it)}checkBasicOperator(){return this.checkPredicate(ot)}matchBasicOperator(){return this.matchPredicate(ot)}matchTimeExpression(){return this.matchPredicate(Ze)}matchIdentifierLike(){return this.matchPredicate(He)}matchComparisonOperator(){return this.matchPredicate(qe)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Xe,e)}consumeIdentifierLike(e){return this.consumePredicate(He,e)}consumeEvent(e){return this.consumePredicate(Ve,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let n=t.start||0,r=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,s=e.column||1,0===n&&this.current>0&&(n=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;n=e.start||0,r=e.line||1,s=e.column||1,0===n&&(n=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const n=this.tokens[t];if(n&&("+"===n.value||"-"===n.value)){e=n;break}}n=e.start||0,r=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,r),column:Math.max(1,s),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const e=this.peek();if("then"===e.value||"end"===e.value||"on"===e.value)return;if(this.checkIsCommand()||this.isCommand(e.value)&&!this.isKeyword(e.value))return;he("⚠️ synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();r.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s="["+r.join("")+"]";return{type:"literal",value:s,raw:s,start:e,end:this.previous().end,line:t,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&r.has(i.value)&&"string"===this.tokens[this.current+2]?.kind)){let e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:e,end:this.previous().end,line:t,column:n}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>{const n=e.current+t;return n>=0&&e.tokens.length>n?e.tokens[n]:null},getInputSlice:(e,t)=>this.originalInput?0>e||e>=this.originalInput.length?"":void 0!==t?this.originalInput.slice(e,t):this.originalInput.slice(e):""};return Object.defineProperty(t,"current",{get:()=>e.current,set:t=>{e.current=t},enumerable:!0,configurable:!0}),t}}function _t(e,t){const n=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const n=e.length;for(;n>t.position&&(q(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==V(t,1))if('"'!==n){if("'"===n||"'"===n){const e=V(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||n.kind!==P.IDENTIFIER&&n.kind!==P.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)z(t);else{const e=t.position;_(t),_(t),H(t,P.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===V(t,1)){const e=t.position;_(t),_(t),H(t,P.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],n=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),r=e&&e.kind===P.IDENTIFIER&&E.has(e.value.toLowerCase()),s=e&&e.kind===P.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===P.OPERATOR&&")"!==e.value&&"]"!==e.value||r||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(te(V(t))||"{"===V(t))){Z(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===P.IDENTIFIER&&M.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==P.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(H(t,P.SYMBOL,"["),_(t)):(H(t,P.OPERATOR,"["),_(t));continue}if("]"!==n){if("$"===n){const e=V(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){ee(t);continue}}se(n)?X(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(H(t,P.UNKNOWN,n),_(t)):Q(t):Y(t)}else H(t,P.OPERATOR,"]"),_(t)}else H(t,P.OPERATOR,"}"),_(t);else H(t,P.OPERATOR,"{"),_(t);else K(t)}else Z(t);else re(t)?G(t):X(t);else J(t)}else z(t);else W(t)}return t.tokens}(e);return new Vt(n,t,e).parse()}Vt.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Vt.PRATT_TABLE=Se,Vt.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class qt{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const n of this.afterExecuteHooks)await n(e,t)}async runOnError(e,t){let n=t;for(const t of this.onErrorHooks){const r=await t(e,n);r instanceof Error&&(n=r)}return n}shouldIntercept(e,t){for(const n of this.interceptCommandHooks)if(n(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Ht(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function Ut(e){return{ok:!0,value:e}}function Wt(e){return{ok:!1,error:e}}function zt(e){return!0===e.ok}const Jt=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,n]of this.types)if(n.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),n=this.types.get(t);return n?.hyperscriptType??"unknown"}coerce(e,t,n){const r=this.types.get(t);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(r.isType(e))return e;if(this.config.cacheCoercions){const n=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const s=this.inferType(e),i=r.coerceFrom?.[s];if(i){const r=i(e,n);if(this.config.cacheCoercions&&null!==r){const n=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(e,t){const n=this.types.get(t);if(!n)return!1;if(n.isType(e))return!0;const r=this.inferType(e);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(e,t){const n=this.types.get(t);return n&&(e===t||n.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const n=e;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,n)=>{t[n+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Zt(e){const t=Jt.get("String");return t?t.isType(e):"string"==typeof e}function Gt(e){const t=Jt.get("Number");return t?t.isType(e):"number"==typeof e}function Kt(e){const t=Jt.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Xt(e){const t=Jt.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Yt(e){const t=Jt.get("Function");return t?t.isType(e):"function"==typeof e}function Qt(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}const en=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function tn(e,t){return en.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const nn={id:e=>e.id,classname:e=>e.className,class:e=>e.className,tagname:e=>e.tagName.toLowerCase(),innertext:e=>e.textContent?.trim(),innerHTML:e=>e.innerHTML,outerhtml:e=>e.outerHTML,value:e=>function(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}(e)?e.value:void 0,checked:e=>function(e){return null!==e&&"object"==typeof e&&"tagName"in e&&"INPUT"===e.tagName}(e)?e.checked:void 0,disabled:e=>"disabled"in e?e.disabled:void 0,selected:e=>function(e){return null!=e&&"object"==typeof e&&"tagName"in e&&"OPTION"===e.tagName}(e)?e.selected:void 0,tabindex:e=>Qt(e)?e.tabIndex:void 0,hidden:e=>Qt(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e.getAttribute("name");n&&"value"in e&&t.append(n,e.value)}),t}(e)};function rn(e,t){if(t.startsWith("computed-")){const n=t.slice(9);return function(e){return e instanceof HTMLElement}(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return tn(e,t.slice(1));const n=nn[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return tn(e,t);const r=e[t];return Yt(r)?r.bind(e):r}function sn(e){return Array.isArray(e)?e:null==e?[]:"string"==typeof e?[e]:e instanceof NodeList||e instanceof HTMLCollection||"number"==typeof e.length?Array.from(e):[e]}function on(e,t){const n=e.registry?.get(t);if(!n)throw Error(`Expression '${t}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function an(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}async function cn(e,t){if(!e)throw Error("Cannot evaluate null or undefined AST node");if("literal"===e.type)return e.value;if("identifier"===e.type)return fn(e,t);const n=e;switch(e.type){case"literal":return function(e){return e.value}(n);case"identifier":return fn(n,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,s=e.left;if("has"===n||"have"===n){const n=await cn(e.left,t);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(s.arguments)){const r=s.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const s=await cn(e.right,t);if(s&&"function"==typeof s.querySelectorAll){const e=Array.from(s.querySelectorAll(r.value));return 0===e.length?null:"first"===n?e[0]:e[e.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const n=await cn(e.right,t),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(s.value))}}const i=await cn(e.left,t);if("and"===n){if(!i)return i;const n=await cn(e.right,t);return on(t,"and").evaluate(t,i,n)}if("or"===n){if(i)return i;const n=await cn(e.right,t);return on(t,"or").evaluate(t,i,n)}const o=await cn(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(i):i,l=e.ignoringCase?a(o):o;switch(n){case"+":return"string"==typeof i||"string"==typeof o?(i??"")+""+(o??""):an(await on(t,"addition").evaluate(t,{left:i,right:o}));case"-":return an(await on(t,"subtraction").evaluate(t,{left:i,right:o}));case"*":return an(await on(t,"multiplication").evaluate(t,{left:i,right:o}));case"/":return an(await on(t,"division").evaluate(t,{left:i,right:o}));case"%":case"mod":return an(await on(t,"modulo").evaluate(t,{left:i,right:o}));case"^":case"**":return an(await on(t,"power").evaluate(t,{left:i,right:o}));case">":case"is greater than":return on(t,"greaterThan").evaluate(t,i,o);case"<":case"is less than":return on(t,"lessThan").evaluate(t,i,o);case">=":case"is greater than or equal to":return on(t,"greaterThanOrEqual").evaluate(t,i,o);case"<=":case"is less than or equal to":return on(t,"lessThanOrEqual").evaluate(t,i,o);case"==":case"is":case"am":case"equals":case"is equal to":return on(t,"equals").evaluate(t,c,l);case"!=":case"is not":case"is not equal to":return on(t,"notEquals").evaluate(t,c,l);case"===":case"really equals":case"is really equal to":return on(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really equal to":return on(t,"strictNotEquals").evaluate(t,c,l);case"as":return on(t,"as").evaluate(t,i,pn(o));case"contains":return on(t,"contains").evaluate(t,c,l);case"does not contain":case"does not include":return on(t,"doesNotContain").evaluate(t,c,l);case"starts with":return on(t,"startsWith").evaluate(t,c,l);case"ends with":return on(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await on(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await on(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return on(t,"matches").evaluate(t,c,l);case"in":case"is in":return hn(i,o);case"is not in":return!hn(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return dn(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!dn(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return dn(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!dn(i,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,t);case"asExpression":return async function(e,t){const n=await cn(e.expression,t),r=pn(e.targetType);return on(t,"as").evaluate(t,n,r)}(n,t);case"betweenExpression":return async function(e,t){const n=await cn(e.value,t),r=await cn(e.min,t),s=await cn(e.max,t),i=e=>"string"==typeof e?e.toLowerCase():e,[o,a,c]=e.ignoringCase?[i(n),i(r),i(s)]:[n,r,s],l=await on(t,"between").evaluate(t,o,a,c);return e.negated?!l:l}(n,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await cn(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(n,t);case"collectionExpression":return async function(e,t){const n=await cn(e.collection,t),r=async(e,n)=>cn(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=sn(e),s=[];for(const e of r)await n(t,e)&&s.push(e);return s}(n,e.right,r);case"sorted by":return async function(e,t,n,r){const s=[...sn(e)],i=await Promise.all(s.map(e=>r(t,e))),o=s.map((e,t)=>t);o.sort((e,t)=>{const n=i[e],r=i[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(e=>s[e]);return"desc"===n?a.reverse():a}(n,e.right,e.order??"asc",r);case"mapped to":return async function(e,t,n){const r=sn(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return i=await cn(e.right,t),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return sn(e).map(e=>null==e?"":e+"").join(n)}(n,await cn(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var s,i}(n,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await cn(n,t);switch(e.operator){case"not":case"!":return on(t,"not").evaluate(t,r);case"no":return on(t,"no").evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return on(t,"exists").evaluate(t,r);case"does not exist":return on(t,"doesNotExist").evaluate(t,r);case"is empty":return on(t,"isEmpty").evaluate(t,r);case"is not empty":return on(t,"isNotEmpty").evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(n,t);case"memberExpression":return async function(e,t){const n=await cn(e.object,t);if(e.computed){const r=await cn(e.property,t);return n?.[r]}{const t=e.property.name;if("string"==typeof t&&t.startsWith("@")){const e=t.substring(1);return n&&"function"==typeof n.getAttribute?n.getAttribute(e):void 0}return n instanceof Element&&"string"==typeof t?rn(n,t):n?.[t]}}(n,t);case"callExpression":return async function(e,t){const n=await cn(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>cn(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,s=await async function(e,t,n){return gn.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:cn(e,n))):Promise.all(e.map(e=>cn(e,n)))}(e.arguments,r,t);switch(r){case"closest":return on(t,"closest").evaluate(t,...s);case"previous":return on(t,"previous").evaluate(t,...s);case"next":return on(t,"next").evaluate(t,...s);case"first":return on(t,"first").evaluate(t,...s);case"last":return on(t,"last").evaluate(t,...s);default:if("function"==typeof n)return n(...s);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(e.arguments.map(e=>cn(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const s=await cn(e.callee.object,t);return n.apply(s,r)}return n(...r)}throw Error("Cannot call non-function")}(n,t);case"selector":return async function(e,t){const n=e.value,r="string"==typeof n?function(e){return e.replace(vn,"$1\\:")}(n):n,s=await on(t,"elementWithSelector").evaluate(t,r);return!e.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(n,t);case"possessiveExpression":return async function(e,t){const n=await cn(e.object,t),r=e.property.name;return on(t,"possessive").evaluate(t,n,r)}(n,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await cn(t,r)}}}(n,t);case"conditionalExpression":return async function(e,t){return await cn(e.test,t)?cn(e.consequent,t):e.alternate?cn(e.alternate,t):void 0}(n,t);case"string":return n.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await cn(r,t));return n}(n,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await cn(e,t)+"",n[s]=await cn(r.value,t)}return n}(n,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(n,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,s=await cn(e.target,t);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);if(function(e){return e instanceof Element}(s))return rn(s,r);const i=s[r];return"function"==typeof i?i.bind(s):i}(n,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await yn(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const e=n.split(".");let r=mn(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(mn(n,t)??"")+""}catch{return""}}),n=await yn(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const s=n||r;try{const e=await async function(e,t){const n=_t(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const r=t.registry?t:{...t,registry:await un()};return cn(n.node,r)}(s,t);return e+""}catch{return"undefined"}}),n}(n,t);default:{const n=Ne.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}}}let ln=null;async function un(){if(!ln){const e=await Promise.resolve().then(function(){return Ao});ln=e.createFullExpressionRegistry()}return ln}async function fn(e,t){const n=e.name;return"me"===n||"my"===n||"I"===n?on(t,"me").evaluate(t):"you"===n||"your"===n||"yourself"===n?on(t,"you").evaluate(t):"it"===n||"its"===n?on(t,"it").evaluate(t):"window"===n?on(t,"window").evaluate(t):"document"===n?on(t,"document").evaluate(t):t.locals&&t.locals.has(n)?(De(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?(n.startsWith("$")&&je(n.slice(1),t),t.globals.get(n)):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?(je(n.slice(1),t),t.globals.get(n.slice(1))):void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function hn(e,t){return Array.isArray(t)?t.includes(e):"string"==typeof t?t.includes(e+""):e instanceof Node&&t instanceof Node?e===t||t.contains(e):null!=t&&"object"==typeof t&&e in t}function dn(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function pn(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e+""}function mn(e,t){return t.locals?.has(e)?(De(e,t),t.locals.get(e)):"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function yn(e,t,n){const r=[];let s;for(;null!==(s=t.exec(e));)r.push({index:s.index,length:s[0].length,replacement:await n(s[0],...s.slice(1))});let i=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:s}=r[e];i=i.substring(0,t)+s+i.substring(t+n)}return i}const gn=new Set(["closest","previous","next"]),vn=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g");class bn{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,n,r,s){this.addCleanup(e,{type:"listener",target:t,eventName:n,cleanup:()=>{t.removeEventListener(n,r,s),this.debugMode&&de(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&de("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&de("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&de("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,n){this.addCleanup(e,{type:"custom",cleanup:t,description:n||"Custom cleanup"})}registerGlobal(e,t="custom",n){this.globalCleanups.push({type:t,cleanup:e,description:n||"Global cleanup"}),this.debugMode&&de("CleanupRegistry: Registered global cleanup: "+(n||t))}addCleanup(e,t){const n=this.elementCleanups.get(e);n?n.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&de(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let n=0;for(const e of t){try{e.cleanup(),n++}catch(e){this.debugMode&&de("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&de(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(e){let t=this.cleanupElement(e);const n=e.querySelectorAll("*");for(const e of n)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&de("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&de(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,n=0,r=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const wn=new Map;function En(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||wn,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class xn{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&de("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(n,t)}unregister(e){const t=e.toLowerCase(),n=this.sources.get(t);if(n){for(const[e,n]of this.subscriptions.entries())n.source===t&&(n.unsubscribe(),this.subscriptions.delete(e));return n.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,n){const r=this.get(e);if(!r)return void de("[EventSourceRegistry] Unknown event source: "+e);r.initialize?.();const s=r.subscribe(t,n);return this.subscriptions.set(s.id,s),s}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,n]of this.sources.entries())if(n.supports?.(e)??n.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class kn{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,n){const r=e.toLowerCase();this.providers.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}registerGlobal(e,t,n){const r=e.toLowerCase();this.globalProviders.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,n){const r=this.get(e);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);if(r.dependencies)for(const e of r.dependencies)await this.resolve(e,t,n);const i=await r.provide(t);return r.cache&&n&&n.set(s,i),i}resolveSync(e,t,n){const r=this.get(e);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);const i=r.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(s,i),i}enhance(e){const t=this,n=new Map;return new Proxy(e,{get(e,r,s){if("string"==typeof r&&t.get(r))try{return t.resolveSync(r,e,n)}catch{return t.resolve(r,e,n)}return Reflect.get(e,r,s)},has:(e,n)=>!("string"!=typeof n||!t.has(n))||Reflect.has(e,n)})}async resolveAll(e){const t=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of r)try{n[s]=await this.resolve(s,e,t)}catch(e){de(`[ContextProviderRegistry] Failed to resolve '${s}':`,e),n[s]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Sn={evaluate:(e,t)=>cn(e,t)};class An{static toTyped(e){return{me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},...void 0!==e.registry&&{registry:e.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class Nn{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(e)?e.join(" | "):e||""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(ue(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void ue(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=An.toTyped(e);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ue(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!await cn(r,e))return void ue(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName},Sn,e)}else i=t;else ue(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;if(ue("CommandAdapterV2: Calling execute with parsed input:",i),2===this.impl.execute.length)o=await this.impl.execute(i,s);else{const e=Array.isArray(i)?i:[i];o=await this.impl.execute(s,...e)}return ue("CommandAdapterV2: Command result:",o),Object.assign(e,An.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(e){if(Ln(e)||ue(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class Cn{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);de(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=t.toLowerCase();de(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new Nn(e,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const s=e.metadata?.aliases;if(s&&Array.isArray(s))for(const t of s){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r),E.add(n)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const n=this.getAdapter(e);return n?n.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Tn=null;function On(){return Tn||(Tn=function(e){const t=e?.commands??new Cn,n=e?.eventSources??new xn,r=e?.context??new kn,s=new Set,i={commands:t,eventSources:n,context:r,use(e){if(s.has(e.name))de(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:n,options:s}of e.contextProviders)r.register(t,n,s);e.setup?.(i),s.add(e.name)}},reset(){s.clear()}};return i}()),Tn}class Rn{constructor(e={}){this.contextCache=new WeakMap;const t=On();this.options={enableContextProviders:e.enableContextProviders??!0,enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,de(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(e){if(!this.options.enableContextProviders)return e;const t=this.contextCache.get(e);if(t)return t;try{const t=this.contextRegistry.enhance(e);return this.contextCache.set(e,t),de(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return de("[RegistryIntegration] Failed to enhance context: "+(t instanceof Error?t.message:t+"")),e}}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return de(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return de(`[RegistryIntegration] Found event source '${n}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(e,t,n);if(!r)throw Error(`Failed to subscribe to event source '${e}'`);return de(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,de("[RegistryIntegration] Destroyed")}}function $n(e){const t=Error(e.type.toUpperCase()+"_EXECUTION");return t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}function Ln(e){return e instanceof Error&&(null!==Ht(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function In(e){if(void 0===e)return;let t=e;if(t&&"object"==typeof t){const e=t;if("result"in e&&"wasAsync"in e)t=e.result;else if("result"in e&&"executed"in e){if(t=e.result,e.preserveArrayResult)return void 0!==t?t:void 0}else if("lastResult"in e&&"type"in e)t=e.lastResult;else if("conditionResult"in e&&"executedBranch"in e){if(void 0===e.result)return;t=e.result}else"value"in e&&1===Object.keys(e).length||"value"in e&&"target"in e&&"targetType"in e?t=e.value:"data"in e&&"status"in e&&"headers"in e&&(t=e.data)}return Array.isArray(t)&&t.length>0&&(t=t[0]),t}function jn(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const Mn=new WeakMap;class Dn{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=wn,this.hookRegistry=new qt,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new bn,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Rn("object"==typeof e.registryIntegration?e.registryIntegration:{}),de("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,n)=>await this.installBehaviorOnElement(e,t,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const n of e)for(const e of n.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&de(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}trackListener(e,t,n,r,s){this.cleanupRegistry.registerListener(e,t,n,r,s)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),de("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){de(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.registry||(t.registry=this.expressionRegistry),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,n)=>this.execute(e,n||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return de("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern)try{const n=await this.processCommandWithResult(e,t);if(!zt(n))throw $n(n.error);return n.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(n,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=e,r=await this.executeCommandSequenceWithResult(n.commands||[],t);if(!zt(r))throw $n(r.error);return r.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(e,t);if(!zt(n))throw $n(n.error);return n.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:n,args:r,modifiers:s}=e,i=n.toLowerCase();if(ue(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const e=await this.registry.getAdapter(i);if(!e)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:r||[],modifiers:s||{},commandName:i,runtime:this})}catch(e){throw Ln(e)||this.logError(`Error executing command '${i}':`,e),e}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(e){const t=Ht(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:n,args:r,modifiers:s}=e,i=n.toLowerCase();if(ue(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const e=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Ut(await o.execute(t,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return Wt(t);throw this.logError(`Error executing command '${i}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const r of e){if(this.hasErrorDiagnostics(r)){const e=r.diagnostics?.[0];de("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===r.type){const e=await this.processCommandWithResult(r,t);if(!zt(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),Ut(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(r,t);if(!zt(e))return e;n=e.value}}return Ut(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await cn(e,n);return jn(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await async function(e,t){try{return Ut(await cn(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return Wt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return Wt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return Wt({type:"break"});if(t.isContinue)return Wt({type:"continue"});if(t.isReturn)return Wt({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!zt(r))return r;const s=r.value;if(jn(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return Ut(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return Wt(t);throw e}}return Ut(s)}async executeCommandFromPattern(e,t,n){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},n)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let n;const r=[],s=[],i=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"initBlock"===t.type?s.push(t):i.push(t);for(const e of r)try{await this.execute(e,t)}catch(e){if(Ln(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{n=await this.execute(e,t)}catch(e){if(Ln(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{n=await this.execute(e,t)}catch(e){if(Ln(e)&&(e.isHalt||e.isExit))break;throw e}return n}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const n of e.commands)try{await this.execute(n,t)}catch(e){if(Ln(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let n;for(const r of e.commands)try{n=await this.execute(r,t)}catch(e){if(Ln(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return n}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const s=await this.execute(r.value,t);n[e]=s}return n}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:s=[],initBlock:i}=e,o=e.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),de(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:s,initBlock:i}),de(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){de("BEHAVIOR: installBehaviorOnElement called: "+e);let r=this.behaviorRegistry.get(e);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(r=this.behaviorRegistry.get(e)),!r))throw Error(`Behavior "${e}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(de(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),de(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));de("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const s={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(r.parameters)for(const e of r.parameters)i.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||i.locals.set(e,t);if(r.initBlock){de("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),de("BEHAVIOR: Init block completed for "+e)}catch(t){if(de(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&Ln(t)))throw t}}if(de(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${e}`),r.eventHandlers){const t=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}de("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:n,events:r,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,f=r&&r.length>0?r:[n];de(`BEHAVIOR: executeEventHandler: event='${n}', target='${i}'`);let h=[],d=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)d=window;else if("document"===e||"the document"===e||"body"===e)d=document;else if("me"===e||"myself"===e)h=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);de(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(e)}`),this.isElement(e)?h=[e]:Array.isArray(e)?h=e.filter(e=>this.isElement(e)):"string"==typeof e&&(h=this.queryElements(e,t))}else de(`BEHAVIOR: Target resolution: querying for '${i}'`),h=this.queryElements(i,t)}else h=t.me?[t.me]:[];if(0===h.length&&!d)return void de(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(h,c,s,t);if("change"===n&&l)return void this.setupChangeObserver(l,s,t);const p=e.customEventSource;if(p&&this.registryIntegration){de(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),i={...t,locals:r,it:e,event:e},o=this.enhanceContext(i);de(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:s},o)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,e)}};try{const r=this.registryIntegration.subscribeToEventSource(p,{event:n,handler:e,target:i,selector:a},t);de(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${p}' subscription ${r.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,e)}return}const m=Dn.createEventHandler(this,s,t,a,o);let y,g=null;if(u){let e=m;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},g=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const t=u.throttle;let n=0;y=r=>{const s=Date.now();t>s-n||(n=s,e(r))}}else y=e}else y=m;const v=u?.once?{once:!0}:void 0;if(d){for(const e of f)d.addEventListener(e,y,v),h.length>0?this.cleanupRegistry.registerListener(h[0],d,e,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(e,y),"listener",`Global ${e} listener`);g&&(h.length>0?this.cleanupRegistry.registerCustom(h[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const e of h){for(const t of f){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const n of e){const e=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(e.synthetic=!0,y(e),v?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,y,v),this.cleanupRegistry.registerListener(e,e,t,y)}g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,n,r,s){return async i=>{const o=Mn.get(i)??0;if(o>=100)return;if(Mn.set(i,o+1),r&&i.target instanceof Element)try{if(!i.target.matches(r)&&!i.target.closest(r))return}catch{de(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const a=new Map(n.locals),c={...n,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=e.enhanceContext(c);if(s&&s.length>0){const e=i,t=e.detail;for(const n of s)l.locals.set(n,e[n]??t?.[n]??null)}for(const n of t)try{const t=In(await e.execute(n,l));void 0!==t&&Object.assign(l,{it:t,result:t})}catch(t){if(Ln(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(l,{it:t.returnValue,result:t.returnValue});break}}throw e.logError("COMMAND FAILED:",t),t}}}setupMutationObserver(e,t,n,r){de(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const s of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){fe(`MUTATION DETECTED: attribute '${t}' changed on`,s);const e={...r,me:s,it:i,locals:new Map(r.locals)},o=i.oldValue,a=s.getAttribute(t);e.locals.set("oldValue",o),e.locals.set("newValue",a);const c=this.enhanceContext(e);for(const e of n)try{await this.execute(e,c)}catch(e){if(Ln(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing mutation handler command:",e)}}});e.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),de("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){de("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(e,n);let s=[];this.isElement(r)?s=[r]:Array.isArray(r)&&(s=r.filter(e=>this.isElement(e))),de(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const e of s){const r=new MutationObserver(async r=>{for(const s of r)if("childList"===s.type||"characterData"===s.type){fe("CONTENT CHANGE DETECTED on",e,"mutation type:",s.type);const r={...n,me:n.me,it:s,locals:new Map(n.locals)};r.locals.set("target",e);const i=s.oldValue,o=e.textContent;null!==i&&r.locals.set("oldValue",i),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const e of t)try{await this.execute(e,a)}catch(e){if(Ln(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing change handler command:",e)}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),de("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const n=t.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let s=e;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(s))}catch{return de(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function Pn(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}const Bn={1:"one",2:"two",3:"three",4:"four",5:"five"};function Fn(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${s=t,Bn[s]??s+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var s;return null}function Vn(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function _n(e,t,n){return Fn(e,1,t,n)??Vn(e,0,t,n)}function qn(e,t){return Fn(e,2,t,"left, right")}function Hn(){return null}function Un(e,t,n,r){return e.length>t?`${n} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${r?` (${r})`:""}`:null}function Wn(e,t,n,r,s){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${s?` (${s})`:""}`:null}function zn(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const Jn="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Zn;function Gn(){return Zn({validate:e=>({success:!0,data:e})})}function Kn(e,t){if(Jn)return Gn();const n=Zn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:zn("type-mismatch","Expected object, received "+typeof n)};const r=n,s={};if(t?.strict){const t=Object.keys(e),n=Object.keys(r).filter(e=>!t.includes(e));if(n.length>0)return{success:!1,error:zn("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[t,n]of Object.entries(e)){const e=r[t];if(!(t in r)&&!n.t)return{success:!1,error:zn("missing-argument",`Required field "${t}" is missing`,t)};const i=n.validate(e);if(!i.success)return{success:!1,error:zn("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};void 0!==i.data&&(s[t]=i.data)}return{success:!0,data:s}}});return n.strict=()=>Kn(e,{strict:!0}),n}Zn=function(e){return e.describe||(e.describe=function(e){return this.description=e,this}),e.safeParse||(e.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),e.parse||(e.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),e.optional||(e.optional=function(){const e=this.validate.bind(this),t={...this,t:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return Zn(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&e>r.data.length?{success:!1,error:zn("runtime-error",`String must be at least ${e} characters long`)}:r}};return Zn(n)}),e.max||(e.max=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length>e?{success:!1,error:zn("runtime-error",`String must be at most ${e} characters long`)}:r}};return Zn(n)}),e.default||(e.default=function(e){const t=this.validate.bind(this),n={...this,i:e,o:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return Zn(n)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const n=this.validate.bind(this),r={...this,validate:r=>{const s=n(r);return s.success?e(s.data)?s:{success:!1,error:zn("runtime-error",t||"Refinement validation failed")}:s}};return Zn(r)}),new Proxy(e,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const Xn=e=>function(e={}){return Jn?Gn():Zn({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:zn("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:zn("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:zn("runtime-error",`String must be at most ${e.maxLength} characters long`)}:e.pattern&&!e.pattern.test(t)?e.pattern.source.startsWith("^")&&e.pattern.source.endsWith("$")?{success:!1,error:zn("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:zn("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),Yn=e=>function(e={}){return Jn?Gn():Zn({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:zn("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:zn("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:zn("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(e||{}),Qn=()=>Jn?Gn():Zn({validate:e=>"boolean"!=typeof e?{success:!1,error:zn("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),er=e=>Kn(e),tr=e=>function(e){return Jn?Gn():Zn({validate:t=>{if(!Array.isArray(t))return{success:!1,error:zn("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:zn("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const n=[];for(let r=0;e.length>r;r++){const s=e[r].validate(t[r]);if(!s.success)return{success:!1,error:zn("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:!0,data:n}}})}(e),nr=()=>Gn(),rr=()=>Gn(),sr=()=>function(e,t="Custom validation failed"){return Jn?Gn():Zn({validate:n=>e(n)?{success:!0,data:n}:{success:!1,error:zn("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class ir{trackPerformance(e,t,n,r){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(e,t,n,r=(n?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:t,duration:Date.now()-t,success:n})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||Gt(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,n,r,s=[]){return{success:!1,error:{name:e,type:t,message:n,code:r,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,n=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:n}],suggestions:n}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":Xt(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":Zt(e)?"String":Gt(e)?"Number":Kt(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Zt(e)?e.split(""):null==e?[]:Xt(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Gt(e)&&Number.isFinite(e))return e;if(Zt(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Kt(e)?e?1:0:null}}const or=er({selector:Xn().min(1),single:Qn().optional().default(!1)});new class extends ir{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=sr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.me,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,n),i}catch(r){const s=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,s,n),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends ir{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=sr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.you,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,n),i}catch(r){const s=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,s,n),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends ir{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=sr(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.it,s={success:!0,value:r,type:this.inferType(r)};return this.trackPerformance(e,t,s,n),s}catch(r){const s=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,s,n),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends ir{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(e,t){const n=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,r,n),r}let r;if(t.single)r=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));r=e.length>0?e:null}const s={success:!0,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(e,t,s,n),s}catch(r){const s=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=t.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}};const ar={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:Hn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:Hn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Hn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Hn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Hn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:e=>_n(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>_n(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:e=>_n(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:e=>_n(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let n=t[0];if(n&&"object"==typeof n&&"type"in n){const e=n;"identifier"===e.type&&e.name?n=e.name:"literal"===e.type&&"string"==typeof e.value&&(n=e.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return e.me?e.me.closest(n):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:Hn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Hn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Hn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>_n(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const s=r||e.me;if(s&&s instanceof HTMLElement){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(n)||void 0}},validate:e=>Wn(e,1,2,"styleRef","property, optional element")??Vn(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===n&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(r)||void 0}},validate:e=>Fn(e,2,"possessiveStyleRef","possessor, property")??Vn(e,0,"possessiveStyleRef","possessor")??Vn(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===r&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(n)||void 0}},validate:e=>Fn(e,2,"ofStyleRef","property, reference")??Vn(e,0,"ofStyleRef","property")??Vn(e,1,"ofStyleRef","reference")}};class cr{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(this.ttl>=Date.now()-t.timestamp)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU(),this.cache.set(e,{result:t,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[n,r]of this.accessOrder)t>r&&(t=r,e=n);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,n)=>e+(t-n.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const lr=new class{constructor(){this.domQueryCache=new cr(200,3e3),this.exprResultCache=new cr(500,2e3),this.cssMatchCache=new cr(100,5e3),this.formValueCache=new cr(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(e);return this.domQueryCache.set(t,r),r}querySelectorAll(e){const t="querySelectorAll:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,r),r}getElementById(e){const t="getElementById:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(e);return this.domQueryCache.set(t,r),r}getElementsByClassName(e){const t="getElementsByClassName:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,r),r}matches(e,t){const n=`matches:${this.getElementCacheKey(e)}:${t}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(n,s),s}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),n=this.formValueCache.get("formValue:"+t);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(e,t){const n=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+n,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(e.cache.keys()))"string"==typeof n&&n.includes(t)&&e.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),n=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${n}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([n,r])=>{e-r.timestamp>t.ttl&&t.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{lr.cleanup()},1e4);const ur=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const n=performance.now()-t;return this.startTimes.delete(e),n}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=lr.getPerformanceStats();this.metrics.cacheHitRate=e.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function fr(){lr.cleanup(),ur.getMetrics().memoryUsage>52428800&&ur.reset()}let hr=null;function dr(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const n=e.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${t} cannot be converted to number: "${e}"`);return r}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const n=e[0];if(Array.isArray(n))throw Error(t+" is a nested array, cannot convert to number");return dr(n,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const n=parseFloat(e);if(!isNaN(n))return n}}const n=e.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function pr(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const n=parseFloat(t);return isNaN(n)?null:n}return"boolean"==typeof e?e?1:0:null==e?0:null}function mr(e,t){if(!Number.isFinite(e)){if(Number.isNaN(e))throw Error(t+" resulted in non-finite value: NaN");throw Error(`${t} resulted in non-finite value: ${e>0?"Infinity":"-Infinity"}`)}return e}function yr(e){try{return dr(e,"_"),!0}catch{return!1}}function gr(e,t,n){if("==="===n)return e===t;if("!=="===n)return e!==t;if(null==e||null==t)return function(e,t,n){if(null==e&&null==t)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,n);const[r,s]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const n=parseFloat(e),r=parseFloat(t);return isNaN(n)||isNaN(r)?[e,t]:[n,r]}const n=pr(e),r=pr(t);return null!==n&&null!==r?[n,r]:[e+"",t+""]}(e,t);switch(n){case">":return r>s;case"<":return s>r;case">=":return r>=s;case"<=":return s>=r;case"==":return vr(e,t);case"!=":return!vr(e,t);default:return!1}}function vr(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const n=parseFloat(t);return!isNaN(n)&&e===n}if("string"==typeof e&&"number"==typeof t){const n=parseFloat(e);return!isNaN(n)&&n===t}return"boolean"==typeof e?vr(e?1:0,t):"boolean"==typeof t?vr(e,t?1:0):e+""==t+""}function br(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function wr(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function Er(e,t,n,r,s,i=!0,o){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:n,output:r,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(e=3e4){hr&&clearInterval(hr),hr=setInterval(fr,e)}();const xr=er({left:nr().describe("Left operand value"),right:nr().describe("Right operand value")}).strict(),kr=er({operand:nr().describe("Operand value to negate")}).strict();function Sr(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new class extends ir{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=xr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,n,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),o=s&&i;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends ir{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=xr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,n,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),o=s||i;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends ir{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=kr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,n,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Ar=tr([nr(),nr()]),Nr=tr([nr(),Xn()]),Cr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){const r=Date.now();try{return Er(this,e,[t,n],t==n,r)}catch(s){throw Er(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>qn(e,"equals"),inputSchema:Ar,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},Tr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,n){const r=e.evaluationHistory,s=t===n;return r&&Er(this,e,[t,n],s,r?Date.now():0),s},validate:e=>qn(e,"strictEquals")},Or={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,n){const r=e.evaluationHistory,s=t!=n;return r&&Er(this,e,[t,n],s,r?Date.now():0),s},validate:e=>qn(e,"notEquals")},Rr={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,n){const r=e.evaluationHistory,s=t!==n;return r&&Er(this,e,[t,n],s,r?Date.now():0),s},validate:e=>qn(e,"strictNotEquals")},$r={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=gr(t,n,"<");return r&&Er(this,e,[t,n],i,s),i},validate:e=>qn(e,"lessThan")},Lr={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=gr(t,n,"<=");return r&&Er(this,e,[t,n],i,s),i},validate:e=>qn(e,"lessThanOrEqual")},Ir={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=gr(t,n,">");return r&&Er(this,e,[t,n],i,s),i},validate:e=>qn(e,"greaterThan")},jr={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=gr(t,n,">=");return r&&Er(this,e,[t,n],i,s),i},validate:e=>qn(e,"greaterThanOrEqual")},Mr={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){const r=Date.now();try{return Er(this,e,[t,n],t&&n,r)}catch(s){throw Er(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>qn(e,"and"),inputSchema:Ar,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},Dr={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,n){const r=e.evaluationHistory,s=t||n;return r&&Er(this,e,[t,n],s,r?Date.now():0),s},validate:e=>qn(e,"or")},Pr={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const n=e.evaluationHistory,r=!t;return n&&Er(this,e,[t],r,n?Date.now():0),r},validate:e=>Fn(e,1,"not","operand")},Br={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let s;return s=null==t||(Zt(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Xt(t)||0!==Object.keys(t).length)),n&&Er(this,e,[t],s,r),s},validate:e=>Fn(e,1,"isEmpty","value")},Fr={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let s;return s=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:(Zt(t),!1)),n&&Er(this,e,[t],s,r),s},validate:e=>Fn(e,1,"no","value")},Vr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,s=!await Br.evaluate(e,t);return n&&Er(this,e,[t],s,r),s},validate:e=>Fn(e,1,"isNotEmpty","value")},_r={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const n=e.evaluationHistory,r=null!=t;return n&&Er(this,e,[t],r,n?Date.now():0),r},validate:e=>Fn(e,1,"exists","value")},qr={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const n=e.evaluationHistory,r=null==t;return n&&Er(this,e,[t],r,n?Date.now():0),r},validate:e=>Fn(e,1,"doesNotExist","value")},Hr={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0;let i;if(t&&n){if(Sr(t)&&Sr(n))return i=t.contains(n),r&&Er(this,e,[t,n],i,s),i;if(Zt(t)&&t.match(/^[.#][\w-]+$/)){const o=document.querySelector(t);if(o&&Sr(n))return i=o.contains(n),r&&Er(this,e,[t,n],i,s),i;if(o&&Zt(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=!!a&&o.contains(a),r&&Er(this,e,[t,n],i,s),i}}if(Zt(n)&&n.match(/^[.#][\w-]+$/)&&Sr(t)){const o=document.querySelector(n);return i=!!o&&t.contains(o),r&&Er(this,e,[t,n],i,s),i}}return i=Zt(t)&&Zt(n)||Array.isArray(t)?t.includes(n):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(n):!(!Xt(t)||!Zt(n))&&n in t,r&&Er(this,e,[t,n],i,s),i},validate:e=>Fn(e,2,"contains","container, value")},Ur={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!await Hr.evaluate(e,t,n);return r&&Er(this,e,[t,n],i,s),i},validate:e=>Fn(e,2,"doesNotContain","container, value")},Wr={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!(!Zt(t)||!Zt(n))&&t.startsWith(n);return r&&Er(this,e,[t,n],i,s),i},validate:e=>Fn(e,2,"startsWith","str, prefix")},zr={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!(!Zt(t)||!Zt(n))&&t.endsWith(n);return r&&Er(this,e,[t,n],i,s),i},validate:e=>Fn(e,2,"endsWith","str, suffix")},Jr={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){const s=e.evaluationHistory;let i=n,o=r;if(null!=i&&null!=o&&i>o){const e=i;i=o,o=e}const a=null!=i&&null!=o&&t>=i&&o>=t;return s&&Er(this,e,[t,n,r],a,s?Date.now():0),a},validate:e=>Fn(e,3,"between","value, min, max")},Zr={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){const r=Date.now();try{let s;if(t instanceof Element&&Zt(n)){const e=n;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{s=function(e,t){return lr.matches(e,t)}(t,e)}catch(e){s=!1}else s=!1}else if(Zt(t)&&Zt(n)){const e=t,r=n;try{s=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(e)}catch(t){s=e.includes(r)}}else s=!1;return Er(this,e,[t,n],s,r)}catch(s){throw Er(this,e,[t,n],!1,r,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Fn(e,2,"matches","element, selector"),inputSchema:Nr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},Gr={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0;let i=!1;if(t instanceof Element&&Zt(n)){const e=n;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return r&&Er(this,e,[t,n],i,s),i},validate:e=>Fn(e,2,"has","element, selector")},Kr={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,n){const r=e.evaluationHistory,s=r?Date.now():0,i=!await Gr.evaluate(e,t,n);return r&&Er(this,e,[t,n],i,s),i},validate:e=>Fn(e,2,"doesNotHave","element, selector")},Xr={equals:Cr,strictEquals:Tr,notEquals:Or,strictNotEquals:Rr,lessThan:$r,lessThanOrEqual:Lr,greaterThan:Ir,greaterThanOrEqual:jr,and:Mr,or:Dr,not:Pr,no:Fr,isEmpty:Br,isNotEmpty:Vr,exists:_r,doesNotExist:qr,contains:Hr,doesNotContain:Ur,startsWith:Wr,endsWith:zr,between:Jr,matches:Zr,has:Gr,doesNotHave:Kr},Yr=er({value:Xn().describe("String literal value")}).strict(),Qr=er({value:Yn().describe("Number literal value")}).strict(),es=er({value:Qn().describe("Boolean literal value")}).strict(),ts=er({left:nr().describe("Left operand"),right:nr().describe("Right operand")}).strict();const ns={stringLiteral:new class extends ir{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=Yr,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid){const t=this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(e,n,!1),t}let s=t.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,e));const i=this.success(s,"string");return this.trackSimple(e,n,!0,s),i}catch(t){return this.trackSimple(e,n,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let n=e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=this.resolveExpression(n.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,n)=>{try{const e=this.resolveVariable(n,t);return void 0!==e?e+"":""}catch(e){return""}}),n}resolveExpression(e,t){if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++)r=r[n[e]];return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?(De(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends ir{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Qr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?Number.isFinite(t.value)?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends ir{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=es,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends ir{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=ts,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=dr(t.left,"left operand")+dr(t.right,"right operand");return this.trackSimple(e,n,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends ir{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=ts,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const s=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,n,!0,s),this.success(s,"string")}catch(t){return this.trackSimple(e,n,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=ts.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Zt(e))return e;if(Gt(e))return""+e;if(Kt(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends ir{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=ts,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const s=dr(t.left,"left operand")*dr(t.right,"right operand");return this.trackSimple(e,n,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};function rs(e,t,n,r,s="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:s,message:n,code:t,suggestions:r}}}function ss(e,t){return{success:!0,value:e,type:t}}function is(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const os={Array:(e,t)=>{try{return Array.isArray(e)?ss(e,"array"):e instanceof NodeList?ss(Array.from(e),"array"):ss(null==e?[]:[e],"array")}catch(e){return rs("Array","ARRAY_CONVERSION_FAILED",is("Failed to convert value to Array",e),["Check if value is iterable","Ensure value is not circular reference"])}},String:(e,t)=>{try{return null==e?ss("","string"):Zt(e)?ss(e,"string"):Xt(e)?ss(JSON.stringify(e),"string"):ss(e+"","string")}catch(e){return rs("String","STRING_CONVERSION_FAILED",is("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Kt(e))return ss(e,"boolean");if(null==e)return ss(!1,"boolean");if(Zt(e)){const t=e.toLowerCase().trim();return ss("false"!==t&&"0"!==t&&""!==t,"boolean")}return Gt(e)?ss(0!==e&&!isNaN(e),"boolean"):ss(!!e,"boolean")}catch(e){return rs("Boolean","BOOLEAN_CONVERSION_FAILED",is("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Gt(e))return ss(e,"number");if(null==e)return ss(0,"number");const t=Number(e);return isNaN(t)?rs("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):ss(t,"number")}catch(e){return rs("Number","NUMBER_CONVERSION_FAILED",is("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const n=os.Number(e,t);return n.success?ss(Math.trunc(n.value),"number"):n},Float:(e,t)=>{const n=os.Number(e,t);return n.success?ss(parseFloat(""+n.value),"number"):n},Date:(e,t)=>{try{if(e instanceof Date)return ss(e,"object");if(null==e)return ss(new Date(""),"object");if(Zt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return ss(new Date(t,n-1,r),"object")}const t=new Date(e);return isNaN(t.getTime())?rs("Date","INVALID_DATE",`Cannot convert "${e}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):ss(t,"object")}catch(e){return rs("Date","DATE_CONVERSION_FAILED",is("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{if(!Zt(e))return ss(e,"object");try{return ss(JSON.parse(e),"object")}catch(e){return rs("JSON","JSON_PARSE_FAILED",is("Failed to parse value as JSON",e),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(e,t)=>{try{return ss(JSON.stringify(e),"string")}catch(e){return rs("JSONString","JSON_STRINGIFY_FAILED",is("Failed to stringify value as JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(Xt(e))return ss(e,"object");if(Zt(e))try{return ss(JSON.parse(e),"object")}catch(e){return rs("Object","JSON_PARSE_FAILED",is("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return ss({},"object")}catch(e){return rs("Object","OBJECT_CONVERSION_FAILED",is("Failed to convert value to Object",e),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(e,t)=>{try{if(e instanceof HTMLFormElement)return ss(us(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;if(t.name){const e=fs(t);void 0!==e&&(n[t.name]=e)}}),ss(n,"object")}return ss({},"object")}catch(e){return rs("FormValues","FORM_VALUES_EXTRACTION_FAILED",is("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(e,t)=>{try{let n=e;if(e instanceof HTMLElement){const r=os.Values(e,t);if(!r.success)return r;n=r.value}if(!Xt(n))return ss("","string");const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return ss(""+r,"string")}catch(e){return rs("FormEncoded","FORM_ENCODE_FAILED",is("Failed to URL-encode values",e),["Ensure input is a form element or plain object of scalar/array values"])}}},as=er({value:rr(),type:Xn().min(1)}),cs=er({value:rr(),type:Xn().min(1)});new class extends ir{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=as,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=t;if(i.startsWith("Fixed")){const r=i.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):2,a=os.Number(s,e);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(e,t,c,n),c}let o=os[i];if(o){const r=o(s,e);return this.trackPerformance(e,t,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[i.toLowerCase()];if(a&&(o=os[a],o)){const r=o(s,e);return this.trackPerformance(e,t,r,n),r}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(e,t,c,n),c}catch(r){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends ir{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=cs,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=t,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=Zt(s);break;case"number":a=Gt(s)&&!isNaN(s);break;case"boolean":a=Kt(s);break;case"object":a=Xt(s);break;case"array":a=Array.isArray(s);break;case"function":a=Yt(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||Xt(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(e,t,c,n),c}catch(r){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const ls={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Zt(e)?e:Xt(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Kt(e))return e;if(null==e)return!1;if(Zt(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Gt(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(Gt(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Gt(e))return e;if(null==e)return 0;const t=(e+"").trim();if(!t)return 0;try{return function(e){if(e=e.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(e))throw Error("Invalid characters in math expression");try{const t=Function(`"use strict"; return (${e})`)();if(!Gt(t)||!isFinite(t))throw Error("Expression did not evaluate to a finite number");return t}catch(e){throw Error("Math expression evaluation failed: "+(e instanceof Error?e.message:e+""))}}(t)}catch(e){return console.warn("Math conversion failed:",e),0}},Int:e=>{const t=ls.Number(e);return Math.trunc(t)},Float:e=>{const t=ls.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Zt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r)}return new Date(e)},JSON:e=>{if(!Zt(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(Xt(e))return e;if(Zt(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{Zt(e)||(e=ls.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>Zt(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:ls.String(e)).join(""):e instanceof Element?e.outerHTML:ls.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return us(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=fs(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?ls.Values(e,t):e;if(!Xt(n))return"";const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return""+r},"Values:Form":(e,t)=>{const n=ls.Values(e,t);return ls.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=ls.Values(e,t);return JSON.stringify(n)}};function us(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=fs(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}function fs(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}const hs={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof r)throw Error("Conversion type must be a string");if(r.startsWith("Fixed")){const{precision:e}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}(r);return ls.Number(n).toFixed(e||2)}let s=ls[r];if(s)return s(n,e);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[r.toLowerCase()];return i&&(s=ls[i],s)?s(n,e):(console.warn("Unknown conversion type: "+r),n)},validate:e=>Fn(e,2,"as","value, type")??Vn(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[n,r]=t;if(!Zt(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return Zt(n);case"number":return Gt(n)&&!isNaN(n);case"boolean":return Kt(n);case"object":return Xt(n);case"array":return Array.isArray(n);case"function":return Yt(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||Xt(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>Fn(e,2,"is","value, type")??Vn(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Fn(e,1,"async","expression")}},ds={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"},ps=er({collection:nr().describe("Collection to operate on (array, NodeList, or string)")}).strict(),ms=er({collection:nr().describe("Collection to access"),index:Yn().describe("Index position to access")}).strict(),ys=er({collection:nr().describe("Collection to select random item from")}).strict();new class extends ir{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=ps,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,o={success:!0,value:i,type:ds[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends ir{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=ps,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,o={success:!0,value:i,type:ds[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends ir{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=ms,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection),i=this.normalizeIndex(t.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:!0,value:o,type:ds[this.inferEvaluationType(o)]};return this.trackPerformance(e,t,a,n),a}catch(r){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid at input: "+e.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return 0>e?t+e:e}},new class extends ir{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=ys,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const r={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,r,n),r}const i=s[this.getSecureRandomIndex(s.length)],o={success:!0,value:i,type:ds[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,o,n),o}catch(r){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,s,n),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid random input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}};const gs={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const n=void 0!==t?t:e.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:Zt(n)?n.length>0?n[0]:null:Xt(n)&&"length"in n&&Gt(n.length)&&n.length>0?n[0]:null},validate:e=>Un(e,1,"first","collection")},vs={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const e=n.children;return e.length>0?e[e.length-1]:null}return Zt(n)?n.length>0?n[n.length-1]:null:Xt(n)&&"length"in n&&Gt(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>Un(e,1,"last","collection")},bs={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!Gt(n))throw Error("Index must be a number");const s=n,i=void 0!==r?r:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>s?e.length+s:s;return t>=0&&e.length>t?e[t]:null}if(Zt(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(Xt(i)&&"length"in i&&Gt(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>Wn(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function ws(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;const e=n.querySelector(t);if(e)return e;n=n.nextElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?ws(r,t):null}function Es(e,t){let n=e.previousElementSibling;for(;n;){const e=Array.from(n.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(n.matches(t))return n;n=n.previousElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Es(r,t):null}function xs(e){let t=0,n=e;for(;n&&n.parentElement;)t+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,t+=1e3;return t}const ks={first:gs,last:vs,at:bs,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r]=t,s=r||e.me;return s&&s instanceof Element?n?ws(s,n):s.nextElementSibling:null},validate:e=>Un(e,2,"next","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[n,r]=t,s=r||e.me;return s&&s instanceof Element?n?Es(s,n):s.previousElementSibling:null},validate:e=>Un(e,2,"previous","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[n,r,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),s=xs(e);for(const e of r)if(xs(e)>s)return e;return null}(i,n,o):null},validate:e=>Wn(e,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[n,r,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),s=xs(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(s>xs(t))return t}return null}(i,n,o):null},validate:e=>Wn(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}};function Ss(){return Pn(ar,Xr,ns,hs,ks)}class As{constructor(e){this.observer=null,this.initialized=!1,this.runtime=e}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,this.scanDocument(),this.observer=new MutationObserver(e=>{for(const t of e)"childList"===t.type?t.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(this.processElement(e),this.scanElement(e))}):"attributes"===t.type&&"_"===t.attributeName&&this.processElement(t.target)}),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(e){e.hasAttribute("_")&&this.processElement(e),e.querySelectorAll("[_]").forEach(e=>this.processElement(e))}processElement(e){const t=e.getAttribute("_");if(!t)return;const n=En(e);this.runtime.execute(t,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",e),console.error("Code:",t)})}}function Ns(e,t,n,r,s,i){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(e||null))};var y=(0,n[d])("accessor"===c?{get:f.get,set:f.set}:f[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),h=!0}function Cs(e,t,n){for(var r=arguments.length>2,s=0;t.length>s;s++)n=r?t[s].call(e,n):t[s].call(e);return r?n:void 0}function Ts(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function Os(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function Rs(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),n=e.indexOf("=");if(-1===n)return{name:e.trim()};const r=e.slice(0,n).trim();let s=e.slice(n+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:r,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function $s(e,t){for(const n of e)t(n);return e}function Ls(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function Is(e,t,n){const r=e.hasAttribute(t);void 0!==n?r&&e.getAttribute(t)===n?e.removeAttribute(t):e.setAttribute(t,n):r?e.removeAttribute(t):e.setAttribute(t,"")}function js(e){if(!e)return[];if("string"==typeof e)return e.trim().split(/[\s,]+/).map(e=>{const t=e.trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&Ds(e));if(Array.isArray(e))return e.map(e=>{const t=(e+"").trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&Ds(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&Ds(n)?[n]:[]}function Ms(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Ds(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Ms(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Ps(e,t){return e.map(e=>{if(Ms(e)){const n=function(e){const t=e.trim(),n=t.match(/^\{(.+)\}$/);return n?n[1].trim():t}(e),r=t.locals.get(n)??t.globals.get(n);return null!=r?r+"":(ue(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}"function"==typeof SuppressedError&&SuppressedError;const Bs=Symbol("command:name"),Fs=Symbol("command:category"),Vs=Symbol("command:metadata");function _s(e){return function(t,n){const r=t;r[Bs]=e.name,r[Fs]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function qs(e){return function(t,n){const r=t,s=r[Fs];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const i={description:e.description,syntax:e.syntax,examples:e.examples,category:s,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};r[Vs]=i,Object.defineProperty(t,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function Hs(e){return()=>new e}function Us(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function Ws(e,t){return t}function zs(e,t,n){if(Us(e))return e;if(!e){const e=t.me;if(!e)throw Error(Ws(0,"No target element — provide explicit target or ensure context.me is set"));return Zs(e)}if("string"==typeof e){const n=e.trim();if("me"===n){if(!t.me)throw Error(Ws(0,'Context reference "me" is not available'));return Zs(t.me)}if("it"===n){if(!Us(t.it))throw Error(Ws(0,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===n){if(!t.you)throw Error(Ws(0,'Context reference "you" is not available'));return Zs(t.you)}const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(Ws(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(Ws(0,"Element not found with selector: "+n));if(!Us(s))throw Error(Ws(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(Ws(0,"Invalid target type: "+typeof e))}function Js(e,t){if(Array.isArray(e))return e.filter(Us);if(e instanceof NodeList)return Array.from(e).filter(Us);if(Us(e))return[e];if(!e){const e=t.me;return e&&Us(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&Us(t.me)?[t.me]:[];if("it"===n)return Us(t.it)?[t.it]:[];if("you"===n)return t.you&&Us(t.you)?[t.you]:[];const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let e=n;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.querySelectorAll(e);return Array.from(t).filter(Us)}}return[]}function Zs(e){if(Us(e))return e;throw Error("Value is not an HTMLElement")}function Gs(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(Ws(0,'No "me" element in context'));if(!Us(t.me))throw Error(Ws(0,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(Ws(0,'No "it" value in context'));if(!Us(t.it))throw Error(Ws(0,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(Ws(0,'No "you" element in context'));if(!Us(t.you))throw Error(Ws(0,"context.you is not an HTMLElement"));return t.you;default:throw Error(Ws(0,"Unknown possessive: "+e))}}const Ks=["on","from","to","in","with","at"];async function Xs(e,t,n,r,s={},i){let o=e;if(s.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Ks.includes(t.name.toLowerCase())})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const e=i[s.fallbackModifierKey];e&&(o=[e])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!Us(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of o){const s=await t.evaluate(e,n);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(Us(s))a.push(s);else if(s instanceof NodeList){const e=Array.from(s).filter(Us);a.push(...e)}else if(Array.isArray(s)){const e=s.filter(Us);a.push(...e)}else{if("string"!=typeof s)throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let e=s;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const r=t.querySelectorAll(e),i=Array.from(r).filter(Us);a.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!Us(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Ys(e){return"string"==typeof e&&e.trim().startsWith("*")}function Qs(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const n=t.substring(1).trim();return n?{property:n}:null}(e);if(!t)return null;const n=t.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function ei(e,t,n){e.style.setProperty(t,n)}const ti=["dialog","details","summary","select"];function ni(e){return e&&"object"==typeof e?"string"==typeof e.selector?e.selector:"string"==typeof e.value?e.value:"string"==typeof e.name?e.name:null:null}async function ri(e,t,n){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const n=ni(e);return"string"==typeof n&&n.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const n=ni(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:ni(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;if("attributeAccess"===e.type)return!0;if("selector"===e.type||"cssSelector"===e.type){const t=ni(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:ni(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class si{async resolveTargets(e,t,n,r){return Xs(e,t,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(e,t,n){return ri(e,t,n)}parseClassNames(e){return js(e)}isAttribute(e){return Os(e.trim())}isCSSProperty(e){return Ys(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>Us(e))}(e)}validateType(e,t){return function(e,t){return"string"==typeof e&&t.includes(e)}(e,t)}validateStringArray(e,t=1){return Array.isArray(e)&&function(e,t=1){return Array.isArray(e)&&e.length>=t&&e.every(e=>"string"==typeof e&&e.length>0)}(e,t)}}let ii=(()=>{let e,t,n=[qs({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"]}),_s({name:"add",category:"dom"})],r=[],s=si;return t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s)){const{name:r,value:i}=function(e){const t=Rs(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:r,value:i,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(s)){const r=s.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const i=await t.evaluate(e.args[1],n);return{type:"styles",styles:{[r]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,n,e.modifiers)}}}const s=this.parseClassNames(r);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=Ps(e.classes,t);n.length>0&&Ls(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,$s(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){Ls(e,Object.entries(t),(e,[t,n])=>{e.style.setProperty(t,n)})}(e.targets,e.styles)}var n,r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const n=t.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(e=>"string"==typeof e))return!1}return!0}},Ts(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Cs(t,r)})(),t})();const oi=Hs(ii);function ai(e){return!!e.parentNode&&(e.remove(),!0)}let ci=(()=>{let e,t,n=[qs({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"]}),_s({name:"remove",category:"dom"})],r=[],s=si;return t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(Us(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&Us(r[0]))return{type:"element",targets:r.filter(e=>Us(e))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:Rs(s).name,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}const s=this.parseClassNames(r);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=Ps(e.classes,t);n.length>0&&Ls(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,$s(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){Ls(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)ai(t)}var n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}},Ts(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Cs(t,r)})(),t})();const li=Hs(ci);function ui(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function fi(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=ui(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function hi(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function di(e){return"DIALOG"===e.tagName}function pi(e){return"DETAILS"===e.tagName}function mi(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&Is(e,n)}}function yi(e,t,n,r){const s=mi(e,t,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function gi(e,t,n,r){const s=mi(e,t,n),i=()=>{s(),e.removeEventListener(r,i)};return e.addEventListener(r,i,{once:!0}),()=>{e.removeEventListener(r,i)}}function vi(e,t,n){if(t.startsWith("@")){const r=t.substring(1);return void(!1===n?e.removeAttribute(r):e.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(t){case"textContent":return void(e.textContent=r);case"innerHTML":return void(e.innerHTML=r);case"innerText":return void(e.innerText=r);case"id":return void(e.id=r);case"className":return void(e.className=r);case"value":return void("value"in e&&(e.value=r));case"checked":return void("checked"in e&&(e.checked=!!n))}if(t.includes(".")){const r=t.split(".");let s=e;for(let e=0;r.length-1>e;e++)if(s=s[r[e]],null==s)return;return void(s[r[r.length-1]]=n)}if(t.includes("-")||t in e.style)e.style.setProperty(t,r);else try{e[t]=n}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}const bi=/^the\s+(.+?)\s+of\s+(.+)$/i,wi=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 Ei(e){return"string"==typeof e&&bi.test(e)}function xi(e,t){const n=e.match(bi);if(!n)return null;try{return{element:zs(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function ki(e,t,n){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let s=await t.evaluate(e.target,n);return Array.isArray(s)&&(s=s[0]),Us(s)?{element:s,property:r}:null}(e,t,n);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let s=await t.evaluate(e.object,n);return Array.isArray(s)&&(s=s[0]),Us(s)?{element:s,property:r}:null}(e,t,n);const r=e;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const e=r.object,s=r.property;let i=await t.evaluate(e,n);if(Array.isArray(i)&&(i=i[0]),!Us(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function Si(e,t){const{element:n,property:r}=e;r.startsWith("*")?ei(n,r.substring(1),t+""):vi(n,r,t)}async function Ai(e,t,n){let r,s;if(e?.for){const s=await t.evaluate(e.for,n);r="number"==typeof s?s:"string"==typeof s?function(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const n=ui(e);return n?n.milliseconds:t}return t}(s):void 0}if(e?.until){const r=await t.evaluate(e.until,n);"string"==typeof r&&(s=r)}return{duration:r,untilEvent:s}}function Ni(e,t){const n=t?.name,r=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return ti.includes(t)}(t)}(t);if(Us(e)||Array.isArray(e)&&e.every(e=>Us(e)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return ti.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const Ci=Hs((()=>{let e,t,n=[qs({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"]}),_s({name:"toggle",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("toggle command requires an argument");const r=e.args[0],s=r?.name;if("between"===s&&e.args.length>=4){const{duration:r,untilEvent:s}=await Ai(e.modifiers,t,n),i=await t.evaluate(e.args[1],n),o=await t.evaluate(e.args[3],n),a=[];for(let t=4;e.args.length>t;t++){const n=e.args[t]?.name;"on"!==n&&"from"!==n&&a.push(e.args[t])}const c={filterPrepositions:!0,fallbackModifierKey:"on"},l=await Xs(a,t,n,"toggle",c,e.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:r,untilEvent:s}}const i=await ki(r,t,n);if(i)return{type:"property",target:i};if("selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("*")){let s=r.value,i=1;if("*"===s&&e.args.length>1&&"identifier"===e.args[1].type&&(s="*"+e.args[1].name,i=2),"*"===s&&e.modifiers?.on){const r=e.modifiers.on?.name;if(r&&["display","visibility","opacity"].includes(r)){s="*"+r;const{duration:i,untilEvent:o}=await Ai(e.modifiers,t,n),a=Qs(s);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:i,untilEvent:o}}}}const o=Qs(s);if(o){const{duration:r,untilEvent:s}=await Ai(e.modifiers,t,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Xs(e.args.slice(i),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:s}}}const{duration:o,untilEvent:a}=await Ai(e.modifiers,t,n),{value:c}=await ri(r,t,n);if(Ei(c)){const e=xi(c,n);if(e)return{type:"property",target:e}}const{type:l,expression:u}=Ni(c,r),f={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:s}=Rs(u);return{type:"attribute",name:r,value:s,targets:await Xs(e.args.slice(1),t,n,"toggle",f,e.modifiers),duration:o,untilEvent:a}}case"css-property":{const r=Qs(u);if(!r)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:r,targets:await Xs(e.args.slice(1),t,n,"toggle",f,e.modifiers)}}case"element":{let s;if(Us(c))s=[c];else if(Array.isArray(c)&&c.every(e=>Us(e)))s=c;else if(u){const e=document.querySelectorAll(u);s=Array.from(e).filter(e=>Us(e))}else s=await Xs([r],t,n,"toggle",f,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(s);if("dialog"===i){const r=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await n.evaluate(e[1],r);if("string"==typeof t){const s=t.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&e.length>=3){const t=await n.evaluate(e[2],r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,n);return{type:"dialog",mode:r,targets:s}}return"details"===i?{type:"details",targets:hi(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:js(u),targets:s,duration:o,untilEvent:a}}default:{const r=js(u||c);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Xs(e.args.slice(1),t,n,"toggle",f,e.modifiers),duration:o,untilEvent:a}}}}async execute(e,t){switch(e.type){case"classes":{const n=Ps(e.classes,t);if(0===n.length)return[...e.targets];if(Ls(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&yi(t,"class",n[0],e.duration),e.untilEvent&&gi(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,$s(e.targets,e=>{Is(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&yi(t,"attribute",e.name,e.duration),e.untilEvent&&gi(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return $s(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):rn(t,n)}(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||wi.has(r)||wi.has(r.toLowerCase())){const n=!t;return Si(e,n),n}if("number"==typeof t){const n=0===t?1:0;return Si(e,n),n}if("string"==typeof t){const r="__ht_"+n,s=e.element[r];return""===t&&void 0!==s?(Si(e,s),s):(e.element[r]=t,Si(e,""),"")}Si(e,!t)}(e.target),[e.target.element];case"dialog":return $s(e.targets,t=>{return r=e.mode,void((n=t).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return $s(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return $s(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const n=t.classList.contains(e.classA),r=t.classList.contains(e.classB);n?(t.classList.remove(e.classA),t.classList.add(e.classB)):r?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&yi(t,"class",e.classA,e.duration),e.untilEvent&&gi(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}},Ts(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());class Ti{async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await Xs(e.args,t,n,r)}}(e,t,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>Us(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const n=e.dataset.originalDisplay;void 0!==n?(e.style.display=n||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let Oi=(()=>{let e,t,n=[qs({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),_s({name:"show",category:"dom"})],r=[],s=Ti;return t=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>Us(e))&&"string"==typeof t.defaultDisplay}},Ts(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Cs(t,r)})(),t})();const Ri=Hs(Oi);let $i=(()=>{let e,t,n=[qs({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),_s({name:"hide",category:"dom"})],r=[],s=Ti;return t=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(e,t){for(const t of e.targets)this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>Us(e))}},Ts(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Cs(t,r)})(),t})();const Li=Hs($i);const Ii=Hs((()=>{let e,t,n=[qs({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"]}),_s({name:"put",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=e=>e?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let t=0;e.args.length>t;t++){const n=e.args[t],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=t,o=c;break}}let a=null,c=null;if(-1===i)if(e.modifiers.into||e.modifiers.before||e.modifiers.after){const t=e.modifiers.into?"into":e.modifiers.before?"before":"after";a=e.args[0],o=t,c=e.modifiers[t]}else if(3>e.args.length){if(2>e.args.length)throw Error("put requires content and position");a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||"into"}else a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||null,c=e.args[2];else a=e.args.slice(0,i)[0]||null,c=e.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await t.evaluate(a,n),u=this.mapPosition(o);let f,h,d=null;if(c){const e=r(c),s=await ki(c,t,n);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===e){const e=c.object,r=c.property;if("selector"===e?.type)d=e.value;else if("identifier"===e?.type){const s=e.name;if("my"===s||"me"===s||"I"===s){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===s||"it"===s){const e=await t.evaluate(c,n);"string"==typeof e&&(d=e)}else d=s}if(d&&r?.name)f=r.name;else if(!d&&!f){const e=await t.evaluate(c,n);"string"==typeof e&&(d=e)}}else if("identifier"===e&&"me"===c.name)d=null;else if("selector"===e||"cssSelector"===e)d=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&Ei(e)){const t=xi(e,n);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?d=e:h=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))d=e;else{const r=await t.evaluate(c,n),s=this.resolveEvaluatedAsElements(r);if(s)return{value:l,targets:s,position:u,memberPath:f};h=e}}else{const e=await t.evaluate(c,n),r=this.resolveEvaluatedAsElements(e);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?d=e:h=e)}}return h?{value:l,targets:[],position:u,memberPath:f,variableName:h}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:f}}async execute(e,t){const{value:n,targets:r,position:s,memberPath:i,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,n),t[o]=n,void Object.assign(t,{it:n});if(i)for(const e of r)this.setProperty(e,i,n);else for(const e of r){const t=this.parseValue(n);this.insertContent(e,t,s)}return r}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!Us(t.me))throw Error("put: no target and context.me is null");return[t.me]}const n=Array.from(document.querySelectorAll(e)).filter(e=>Us(e));if(!n.length)throw Error(`No elements: "${e}"`);return n}parseValue(e){return Us(e)?e:null==e?"":e+""}insertContent(e,t,n){if("replace"!==n)if(Us(t)){const r=t;switch(n){case"beforebegin":e.parentElement?.insertBefore(r,e);break;case"afterbegin":e.insertBefore(r,e.firstChild);break;case"beforeend":e.appendChild(r);break;case"afterend":e.parentElement?.insertBefore(r,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t);else Us(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(Us(e))return[e];if(Array.isArray(e)){const t=e.filter(Us);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(Us);return t.length>0?t:null}return null}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,n){const r=t.split(".");let s=e;for(let e=0;r.length-1>e;e++){if(!s[r[e]])throw Error(`Property path "${t}" does not exist`);s=s[r[e]]}s[r[r.length-1]]=n}},Ts(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());function ji(e){if(null==e)return 0;if("number"==typeof e)return isFinite(e)?e:0;if("string"==typeof e)return parseFloat(e);if("boolean"==typeof e)return e?1:0;if(Array.isArray(e))return e.length;if("object"==typeof e){if("length"in e&&"number"==typeof e.length)return e.length;if("function"==typeof e.valueOf){const t=e.valueOf();if("number"==typeof t)return t}return NaN}return 0}function Mi(e,t,n){return"global"===n&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==n&&t.locals&&t.locals.has(e)?(De(e,t),t.locals.get(e)):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===n&&t.locals&&t.locals.has(e)?(De(e,t),t.locals.get(e)):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function Di(e,t,n,r){if("global"===r)return Pe(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))Pe(n,e.slice(1),t);else{if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void Me(e,t,n);if(n.globals&&n.globals.has(e))return Pe(n,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(n.variables&&n.variables.has(e))n.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void Pe(n,e,t);n.locals.set(e,t),Me(e,t,n)}}}function Pi(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Mi(e,t)}const Bi=Hs((()=>{let e,t,n=[qs({description:"Create DOM elements or class instances",syntax:["make a <tag#id.class1.class2/>","make a <ClassName> from <args> called <identifier>"],examples:["make an <a.navlink/> called linkElement",'make a URL from "/path/", "https://origin.example.com"'],sideEffects:["dom-creation","data-mutation"]}),_s({name:"make",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args.length>0?await t.evaluate(e.args[0],n):void 0;if(!r)throw Error("Make command requires class name or DOM element expression");const s=void 0!==e.modifiers.an?"an":"a",i=await async function(e,t,n){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const r=[];for(const s of e.args)r.push(await t.evaluate(s,n));return r}const r=await t.evaluate(e,n);return Array.isArray(r)?r:[r]}(e.modifiers.from,t,n),o=await async function(e,t,n){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const r=await t.evaluate(e,n);return"string"==typeof r?r:r+""}(e.modifiers.called,t,n);return{article:s,expression:r,constructorArgs:i,variableName:o}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:s}=e,i="string"==typeof n&&n.startsWith("<")&&n.endsWith("/>")?function(e){const t=e.slice(1,-2);let n="div",r=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(n=s[1],r=t.slice(s[0].length));const i=document.createElement(n),o=r.split(/(?=[.#])/);for(const e of o)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(n):function(e,t,n){if(Us(e))return e;const r=e+"";let s;if("undefined"!=typeof window&&(s=window[r]),s||"undefined"==typeof global||(s=global[r]),!s&&n.variables?.has(r)&&(s=n.variables.get(r)),!s||"function"!=typeof s)throw Error(`Constructor '${r}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(n,r,t);return Object.assign(t,{it:i}),s&&Di(s,i,t),i}},Ts(t,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),Fi=Hs((()=>{let e,t,n=[qs({description:"Remove all children from an element (sets innerHTML to empty)",syntax:["empty","empty <target>","empty the <target>"],examples:["empty me","empty #list","empty .results"],sideEffects:["dom-mutation"]}),_s({name:"empty",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Xs(e.args,t,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>Us(e))}},Ts(t,"EmptyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());function Vi(e){return e.hasAttribute("popover")}const _i=Hs((()=>{let e,t,n=[qs({description:"Open a dialog, details element, or popover",syntax:["open [<target>]","open <dialog> as modal","open <dialog> as non-modal"],examples:["open","open #myDialog","open #details","open #popup as non-modal"],sideEffects:["dom-mutation"]}),_s({name:"open",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),s=hi(await Xs(r,t,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)),i=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e){const t=e.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}for(let t=0;e.length-1>t;t++){const s=e[t];if("identifier"===s?.type&&"as"===s.name?.toLowerCase()){const s=await n.evaluate(e[t+1],r);if("string"==typeof s){const e=s.toLowerCase().trim();if("non-modal"===e||"nonmodal"===e)return"non-modal";if("modal"===e)return"modal"}}}return"modal"}(e.args??[],e.modifiers??{},t,n);return{targets:s,dialogMode:i}}async execute(e,t){for(const t of e.targets)if(di(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(pi(t))t.open=!0;else if(Vi(t)){const e=t;if("function"==typeof e.showPopover)try{e.showPopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>Us(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}},Ts(t,"OpenCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());function qi(e){return e.hasAttribute("popover")}const Hi=Hs((()=>{let e,t,n=[qs({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"]}),_s({name:"close",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:hi(await Xs(e.args,t,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(di(t))t.open&&t.close();else if(pi(t))t.open=!1;else if(qi(t)){const e=t;if("function"==typeof e.hidePopover)try{e.hidePopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>Us(e))}},Ts(t,"CloseCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());function Ui(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const Wi=Hs((()=>{let e,t,n=[qs({description:"Select the contents of a text field, or select the contents of a DOM element",syntax:["select","select <target>"],examples:["select #search","select <textarea/>","select me"],sideEffects:["focus","dom-mutation"]}),_s({name:"select",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Xs(e.args,t,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(Ui(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),n=e?.defaultView;if(!e||!n)continue;const r=n.getSelection?.();if(r)try{const n=e.createRange();n.selectNodeContents(t),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>Us(e))}},Ts(t,"SelectCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());function zi(e){return"FORM"===e.tagName}const Ji=Hs((()=>{let e,t,n=[qs({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"]}),_s({name:"reset",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Xs(e.args,t,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)zi(t)&&t.reset()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>Us(e))}},Ts(t,"ResetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),Zi=Hs((()=>{let e,t,n=[qs({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"]}),_s({name:"focus",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Xs(e.args,t,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>Us(e))}},Ts(t,"FocusCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),Gi=Hs((()=>{let e,t,n=[qs({description:"Remove focus from an element (calls HTMLElement.blur())",syntax:["blur","blur <target>","blur on <target>"],examples:["blur","blur #search","blur on <input/>"],sideEffects:["focus"]}),_s({name:"blur",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await Xs(e.args,t,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>Us(e))}},Ts(t,"BlurCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),Ki=Hs((()=>{let e,t,n=[qs({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"]}),_s({name:"set",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],s=r?.name||r?.value,i=r?.type;if(i){const s=Ie(i);if(s)return{type:"node-write",node:r,value:await this.extractValue(e,t,n),writer:s}}const o=await ki(r,t,n);if(o){const r=await this.extractValue(e,t,n);if(o.property.startsWith("*")){const e=o.property.substring(1);return{type:"style",element:o.element,property:e,value:r+""}}return{type:"property",element:o.element,property:o.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,e,t,n);if(s)return s}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof s?await t.evaluate(r,n):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(Us(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(Ei(a)){const r=xi(a,n);if(r){const s=await this.extractValue(e,t,n);return{type:"property",element:r.element,property:r.property,value:s}}return this.parseTheXofY(a,e,t,n)}if("string"==typeof a&&Ys(a)){const r=a.substring(1).trim(),s=await this.extractValue(e,t,n);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,n),property:r,value:s+""}}if("string"==typeof a&&Os(a)){const r=a.substring(1).trim(),s=await this.extractValue(e,t,n);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,n),name:r,value:s}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=Gs(r[1],n),i=await this.extractValue(e,t,n);return{type:"property",element:s,property:r[2],value:i}}}if(Us(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(a)&&a.length>0&&Us(a[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} — check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(e,t,n)}}async execute(e,t){switch(e.type){case"variable":return Di(e.name,e.value,t),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":return e.element.setAttribute(e.name,e.value+""),Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return vi(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return ei(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[n,r]of Object.entries(e.properties))vi(t,n,r);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};case"node-write":return await e.writer(e.node,e.value,t),Object.assign(t,{it:e.value}),{target:e.node.name??"",value:e.value,targetType:"variable"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,n,r){const s=e.object,i=e.property;if(s?.name&&i?.name){const e=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const s=Gs(e,r),o=await this.extractValue(t,n,r);return{type:"property",element:s,property:i.name,value:o}}}const o=e.object,a=e.computed;if(o){const s=await n.evaluate(o,r);if(null!=s&&"object"==typeof s){const o=a?await n.evaluate(e.property,r)+"":i?.name||"";if(o)return{type:"member-assignment",container:s,property:o,value:await this.extractValue(t,n,r)}}}return null}async extractValue(e,t,n){if(e.modifiers.to)return t.evaluate(e.modifiers.to,n);const r=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(r>=0&&e.args.length>r+1)return t.evaluate(e.args[r+1],n);if(e.args.length>=2)return t.evaluate(e.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return zs(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return Js(e?await t.evaluate(e,n):void 0,n)}async parseTheXofY(e,t,n,r){const s=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=zs(o,r),c=await this.extractValue(t,n,r);return{type:"property",element:a,property:i.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&Us(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&Us(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&Us(t.element)&&"string"==typeof t.value;case"object-literal":return null!==t.properties&&"object"==typeof t.properties&&Array.isArray(t.targets)&&t.targets.length>0;default:return!1}}},Ts(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());let Xi=(()=>{let e,t,n=[qs({description:"Modify a variable or property by a specified amount (default: 1)",syntax:["increment <target> [by <number>]","decrement <target> [by <number>]"],examples:["increment counter","increment counter by 5","decrement counter","decrement counter by 5"],sideEffects:["data-mutation","context-modification"],aliases:["decrement"]}),_s({name:"increment",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,n,r){if(!e.args||0===e.args.length)throw Error(r+" command requires a target");const s=e.args[0];let i,o,a;const c=(l=s)&&"object"==typeof l&&l.type||"unknown";var l;if("identifier"===c)i=s.name,s.scope&&(o=s.scope);else if("literal"===c)i=s.value;else{const e=Ie(c);if(e){const r=await t.evaluate(s,n),o="number"==typeof r?r:null==r?0:Number(r)||0;i=o,a={node:s,writer:e,currentValue:o}}else{const e=await t.evaluate(s,n);i=Array.isArray(e)&&e.length>0?e[0]:e}}let u=1,f=o;for(let r=1;e.args.length>r;r++){const s=e.args[r];if(s&&"literal"===s.type){const e=s.value;"global"===e?f="global":"number"==typeof e&&(u=e)}else if(s&&"literal"!==s.type){const e=await t.evaluate(s,n);"number"==typeof e&&(u=e)}}return{target:i,amount:u,...f&&{scope:f},...a&&{customWrite:a}}}(e,t,n,r);return{...s,operation:r}}async execute(e,t){const{target:n,property:r,scope:s,amount:i=1,operation:o="increment",customWrite:a}=e;if(a){const e=isFinite(i)?i:1,n="increment"===o?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(Us(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?ji(n.getAttribute(t)):ji(n[t]):ji(n.value||n.textContent)}return"string"==typeof e?"global"===n?ji(Mi(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],s=Pi(n[0],t);return s?ji(s[r]):0}(e,r):ji("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:Mi(e,r)):ji(e)}(n,r,s,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(i)?i:1;l="increment"===o?c+e:c-e}return function(e,t,n,r,s){if(Us(e)){const n=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?n.setAttribute(t,r+""):n[t]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof e){if("global"===n)return void Di(e,r,s,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),s=r[1],i=Pi(r[0],n);i&&(i[s]=t)}(e,r,s);if("me"===e&&s.me)return void(s.me.value=r);if("it"===e)return void Object.assign(s,{it:r});if("you"===e&&s.you)return void(s.you.value=r);Di(e,r,s)}}(n,r,s,l,t),Object.assign(t,{it:l}),l}},Ts(t,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})();const Yi=Hs(Xi),Qi=Hs(Xi);function eo(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const to=Hs((()=>{let e,t,n=[qs({description:"Reset a variable to null or clear the value of a form field (<input>, <textarea>, <select>)",syntax:["clear <var>","clear :var","clear <target>"],examples:["clear :count","clear myVar","clear #search","clear <textarea/>"],sideEffects:["state-mutation","dom-mutation"]}),_s({name:"clear",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args?.[0],s=r?.type,i=r?.name;if(r&&("variable"===s||"identifier"===s&&"string"==typeof i))try{const e=await t.evaluate(r,n);if(!Us(e)&&!Array.isArray(e))return{type:"variable",name:i}}catch{return{type:"variable",name:i}}return{type:"form-fields",targets:await Xs(e.args,t,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return t.locals.set(e.name,null),void Object.assign(t,{it:null});for(const t of e.targets)eo(t)&&("SELECT"===t.tagName?t.selectedIndex=-1:t.value="")}validate(e){if("object"!=typeof e||null===e)return!1;if("variable"===e.type)return"string"==typeof e.name;if("form-fields"===e.type){const t=e.targets;return Array.isArray(t)&&t.every(e=>Us(e))}return!1}},Ts(t,"ClearCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})());function no(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}let ro=(()=>{let e,t,n=[qs({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"]}),_s({name:"trigger",category:"event"})],r=[];return t=class{async parseInput(e,t,n){const r="send"===e.commandName?.toLowerCase()?"send":"trigger",s=r;if(!e.args?.length)throw Error(s+" command requires an event name");const i=e=>e?.type||"unknown",o=e.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const e=o.args||o.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const e=await t.evaluate(o,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,n,s);else{const r=e.args.findIndex((e,t)=>{if(0===t)return!1;const n=e.name||e.value;return"on"===n||"to"===n});if(-1!==r&&e.args.length-1>r){const i=e.args.slice(r+1),o=i.findIndex(e=>"with"===(e.name||e.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,t,n,s)}else{if(!n.me)throw Error(s+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(e.args,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const s=[];for(const r of e){const e=await t.evaluate(r,n);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&n.me)s.push(n.me);else if("you"===e&&n.you)s.push(n.you);else if("it"===e&&n.it)s.push(n.it);else if(Us(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(Us));else if(Array.isArray(e))s.push(...e.filter(Us));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);s.push(...Array.from(t).filter(Us));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);s.push(e)}else s.push(document);else s.push(window)}if(!s.length)throw Error(r+": no valid targets");return s}async parseEventDetail(e,t,n){if(!e?.length)return;if(1===e.length){const r=e[0];if("objectLiteral"!==r?.type)return await t.evaluate(r,n)}const r={};for(const s of e){const e=await t.evaluate(s,n);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,n]=e.split(":",2);r[t.trim()]=no(n.trim())}}else Object.assign(r,e)}return Object.keys(r).length?r:void 0}async parseEventOptions(e,t,n){const r={bubbles:!0,cancelable:!0,composed:!1},s=e.findIndex(e=>"with"===(e.name||e.value));if(-1===s)return r;for(const i of e.slice(s+1)){const e=await t.evaluate(i,n);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?r.bubbles=!0:"nobubbles"===t?r.bubbles=!1:"cancelable"===t?r.cancelable=!0:"nocancelable"===t?r.cancelable=!1:"composed"===t&&(r.composed=!0)}}return r}},Ts(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})();const so=Hs(ro),io=Hs(ro);function oo(e,t,n,r){return e?new Promise(n=>{const s=()=>{i({event:null,timedOut:!1,cancelled:!0})},i=function(n,i){let a=!1;return n=>{a||(a=!0,e.removeEventListener(t,o),r&&r.removeEventListener("abort",s),i(n))}}(0,n),o=e=>{i({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,o),r&&r.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function ao(e){return new Promise(t=>setTimeout(t,e))}const co=Hs((()=>{let e,t,n=[qs({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"]}),_s({name:"wait",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,n);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n);const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await ao(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,s=(await oo(r,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const n of e.destructure)n in s&&t.locals.set(n,s[n]);return{type:"event",result:s,duration:Date.now()-n}}const{result:r,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:r}),r instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in r&&t.locals.set(e,r[e]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(e,t,n){return{type:"time",milliseconds:fi(await t.evaluate(e,n))}}async parseEventWait(e,t,n,r){const s=await n.evaluate(e,r);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(e,t,n,r){const s=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",n=[];for(const r of e.properties){const e=r.key?.name||r.key?.value;"name"===e&&r.value?t=r.value.value||"":"args"===e&&r.value?.elements&&(n=r.value.elements.map(e=>e.value||e.name||""))}t&&s.push({name:t,params:n})}}let i;if(t){const e=await n.evaluate(t,r);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=r.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,n){const r=[];e.modifiers.for?r.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n)):e.args[0]&&r.push(await this.parseTimeWait(e.args[0],t,n));const s=await t.evaluate(e.modifiers.or,n),i=Array.isArray(s)?s:[s];for(const e of i)try{r.push({type:"time",milliseconds:fi(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);r.push(t?{type:"event",eventName:t[1],target:n.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(e,t){const n=new AbortController,r=n.signal,s=e.map(e=>"time"===e.type?ao(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):oo(e.target??t.me??document,e.eventName,0,r).then(t=>({result:t.event,winningCondition:e})));try{return await Promise.race(s)}finally{n.abort()}}},Ts(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),lo=new Map;let uo=[/^4\d{2}$/,/^5\d{2}$/],fo=(()=>{let e,t,n=[qs({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),_s({name:"fetch",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),s=this.parseResponseType(e.modifiers.as);return{url:r,responseType:s,options:await this.parseRequestOptions(e.modifiers.with,t,n),throwOnError:!e.modifiers.doNotThrow&&"response"!==s}}async execute(e,t){const n=Date.now(),{url:r,responseType:s,options:i}=e,o=new AbortController;let a;t.me&&(a=()=>o.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...i,signal:o.signal},l=lo.get(s);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>o.abort(),i.timeout));try{let i=await fetch(r,c);if(t.me){const e={response:i};this.dispatchEvent(t.me,"fetch:afterResponse",e),i=e.response}if(e.throwOnError&&function(e){const t=e+"";return uo.some(e=>e.test(t))}(i.status)){const e=Error(`Fetch failed for ${r}: HTTP ${i.status} ${i.statusText}`.trim());throw e.response=i,e.isFetchStatusError=!0,e}const o=await this.handleResponse(i,s,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:o});const a={status:i.status,statusText:i.statusText,headers:i.headers,data:o,url:i.url,duration:Date.now()-n};return Object.assign(t,{it:o}),a}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r)throw Error("fetch: URL must be a non-empty string");return r}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(lo.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,n){if(!e)return{};const r=await t.evaluate(e,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const s={};return"method"in r&&(s.method=(r.method+"").toUpperCase()),"headers"in r&&(s.headers=this.parseHeaders(r.headers)),"body"in r&&(s.body=this.parseBody(r.body)),"credentials"in r&&(s.credentials=r.credentials),"mode"in r&&(s.mode=r.mode),"cache"in r&&(s.cache=r.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[n,r]of Object.entries(e))t.set(n,r+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,n){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const r=lo.get(t);return r?r.handler(e,n):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),1===n.childNodes.length&&Us(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}},Ts(t,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})();const ho=Hs(fo),po=Hs((()=>{let e,t,n=[qs({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),_s({name:"go",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{args:[]}}async execute(e,t){const{args:n}=e;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,t),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}findBareUrl(e){for(const t of e)if("to"!==t&&"the"!==t)return"string"==typeof t&&this.isBareUrl(t)?t:null;return null}async navigateToBareUrl(e,t){if(t.includes("new")&&t.includes("window")){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e));return e}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const n=e.findIndex(e=>"url"===e),r=e[n+1];if(!r)throw Error('URL is required after "url" keyword');const s="string"==typeof r?r:r+"",i=e.includes("new")&&e.includes("window");if(!this.isValidUrl(s))throw Error(`Invalid URL: "${s}"`);if(i){if("undefined"!=typeof window&&window.open){const e=window.open(s,"_blank");e?.focus&&e.focus()}}else s.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=s):"undefined"!=typeof window&&(window.location.assign?.(s)??(window.location.href=s));return s}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const n=this.parseScrollPosition(e),r=this.parseScrollTarget(e),s=this.parseScrollOffset(e),i=!e.includes("instantly"),o=this.resolveScrollTarget(r,t);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==s){o.scrollIntoView?.({behavior:e,block:t,inline:r});const{x:i,y:a}=this.calculateScrollPosition(o,n,s);window.scrollTo?.({left:i,top:a,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:r})}return o}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},n=["top","middle","bottom"],r=["left","center","right"];let s=!1,i=!1;for(const o of e)"string"==typeof o&&(n.includes(o)?(t.vertical=o,s=!0):r.includes(o)&&(t.horizontal=o,i=!0));return i&&!s&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let n=e[t+1];return"the"===n&&e.length>t+2&&(n=e[t+2]),n}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!n.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const n=e[t];if("string"==typeof n){const e=n.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===n||"-"===n)&&e.length>t+1){const r=e[t+1],s="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(s))return"-"===n?-s:s}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&Us(t.me))return t.me;if("it"===n&&Us(t.it))return t.it;if("you"===n&&Us(t.you))return t.you;const r=Mi(n,t);if(Us(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=e.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=s,l=i;switch(t.horizontal){case"left":c=r.left+s;break;case"center":c=r.left+s+r.width/2-o/2;break;case"right":c=r.right+s-o}switch(t.vertical){case"top":l=r.top+i+n;break;case"middle":l=r.top+i+r.height/2-a/2+n;break;case"bottom":l=r.bottom+i-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}},Ts(t,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),mo=Hs((()=>{let e,t,n=[qs({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"]}),_s({name:"log",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},Ts(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),yo=Hs((()=>{let e,t,n=[qs({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"]}),_s({name:"breakpoint",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}},Ts(t,"BreakpointCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Ns(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Cs(t,r)})(),t})()),go=function(e,t){const n=new Cn(null);for(const t of e)n.register(t);return new Dn({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([oi(),li(),Ci(),Ri(),Li(),Ii(),Bi(),Fi(),_i(),Hi(),Wi(),Ji(),Zi(),Gi(),Ki(),Yi(),Qi(),to(),io(),so(),co(),ho(),po(),mo(),yo()],{expressionRegistry:Ss()}),vo={parse:e=>_t(e),execute:async(e,t)=>{const n=function(e){if(!e)return En();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=En(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}(t),r=_t(e);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await go.execute(r.node,n)}},bo=function(e){return new As(e)}(vo),wo={runtime:vo,parse:e=>vo.parse(e),execute:async(e,t)=>vo.execute(e,t),createContext:En,attributeProcessor:bo,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","empty","open","close","select","reset","focus","blur","set","increment","decrement","clear","send","trigger","wait","fetch","go","log","breakpoint"],eval:async(e,t)=>vo.execute(e,t),init:()=>{bo.init()}};"undefined"!=typeof window&&(window.hyperfixi=wo,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{bo.init()}):bo.init());const Eo=new Set(["__proto__","constructor","prototype"]),xo={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[n,r]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return rn(n,r);if(Xt(n)){if(Eo.has(r))return;return n[r]}return n[r]}},validate:e=>Fn(e,2,"possessive","element, property")??Vn(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[n]=t;if(e.me){if("string"!=typeof n)throw Error("Property name must be a string");if(e.me instanceof Element)return rn(e.me,n);if(Xt(e.me)){if(Eo.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>_n(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[n]=t;if(null==e.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=e.it;if(r instanceof Element)return rn(r,n);if(Xt(r)){if(Eo.has(n))return;return r[n]}return r[n]},validate:e=>_n(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[n]=t;if(e.you){if("string"!=typeof n)throw Error("Property name must be a string");if(e.you instanceof Element)return rn(e.you,n);if(Xt(e.you)){if(Eo.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>_n(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[n,r]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return rn(r,n);if(Xt(r)){if(Eo.has(n))return;return r[n]}return r[n]}},validate:e=>Fn(e,2,"of","property, object")??Vn(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");const s=r||e.me;return s&&s instanceof Element?s.getAttribute(n):null},validate:e=>Wn(e,1,2,"attribute","attributeName, optional element")??Vn(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[n,r,s]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const i=s||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(n)===r},validate:e=>Wn(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Vn(e,0,"attributeWithValue","attribute name")??Vn(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,s=document.getElementsByClassName(r);return Array.from(s)},validate:e=>_n(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:e=>_n(e,"idReference","idValue")}};class ko{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=dr(e,"left operand");return{success:!0,value:mr(r+dr(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[wr("runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){const t=function(e){if(null==e)return br([wr("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return br([wr("type-mismatch","Expected object, got "+typeof e)],["Provide an object with left and right operands"]);const t=e;if(!("left"in t)||!("right"in t)){const e=[];return"left"in t||e.push("left"),"right"in t||e.push("right"),br([wr("missing-argument",`Missing ${e.join(" and ")} operand${e.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(e);if(!t.isValid)return t;const{left:n,right:r}=e;return yr(n)?yr(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[wr("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[wr("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const So={addition:new ko,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=dr(e,"left operand");return{success:!0,value:mr(r-dr(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[wr("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ko).validate(e)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=dr(e,"left operand");return{success:!0,value:mr(r*dr(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[wr("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ko).validate(e)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t,n=!0){if(0===t){if(n)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(dr(e,"left operand"),dr(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[wr("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ko).validate(e)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(dr(e,"left operand"),dr(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[wr("runtime-error","Modulo failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(e){return(new ko).validate(e)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=dr(e,"left operand"),s=dr(n,"right operand");return{success:!0,value:mr(Math.pow(r,s),"power"),type:"number"}}catch(e){return{success:!1,errors:[wr("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new ko).validate(e)}}};var Ao=Object.freeze({__proto__:null,conversion:hs,conversionExpressions:hs,createCommonRegistry:Ss,createCoreRegistry:function(){return Pn(ar,Xr,ns)},createExpressionRegistry:Pn,createFullExpressionRegistry:function(){return Pn(ar,Xr,hs,ks,xo,ns,So)},createFullRegistry:function(){return Pn(ar,Xr,ns,hs,ks,xo)},logical:Xr,logicalExpressions:Xr,positional:ks,positionalExpressions:ks,properties:xo,propertiesExpressions:xo,references:ar,referencesExpressions:ar,special:ns,specialExpressions:ns});return wo}();
|
|
2
|
+
//# sourceMappingURL=hyperfixi-standard.js.map
|