@hyperfixi/core 2.3.1 → 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.
Files changed (194) hide show
  1. package/dist/api/dom-processor.d.ts +8 -4
  2. package/dist/api/hyperscript-api.d.ts +5 -1
  3. package/dist/ast-utils/index.js +25320 -94
  4. package/dist/ast-utils/index.mjs +25320 -94
  5. package/dist/ast-utils/interchange/types.d.ts +7 -1
  6. package/dist/behaviors/index.js +54 -100
  7. package/dist/behaviors/index.mjs +54 -100
  8. package/dist/bundle-generator/index.js +19 -2
  9. package/dist/bundle-generator/index.mjs +19 -2
  10. package/dist/bundle-generator/parser-templates.d.ts +1 -1
  11. package/dist/bundle-generator/template-capabilities.d.ts +1 -1
  12. package/dist/chunks/bridge-C4d3blZX.js +2 -0
  13. package/dist/chunks/browser-modular-BwIRlrTM.js +2 -0
  14. package/dist/chunks/feature-eventsource-BpZvPy_K.js +2 -0
  15. package/dist/chunks/{feature-sockets-ClOH7vk7.js → feature-sockets-CrYvjZ4j.js} +2 -2
  16. package/dist/chunks/feature-webworker-BSYguEIW.js +2 -0
  17. package/dist/chunks/index-Beno_SBy.js +2 -0
  18. package/dist/commands/advanced/async.d.ts +6 -2
  19. package/dist/commands/advanced/js.d.ts +1 -1
  20. package/dist/commands/animation/start-view-transition.d.ts +24 -0
  21. package/dist/commands/async/fetch.d.ts +6 -1
  22. package/dist/commands/control-flow/repeat.d.ts +2 -0
  23. package/dist/commands/data/clear.d.ts +23 -0
  24. package/dist/commands/data/set.d.ts +6 -0
  25. package/dist/commands/dom/close.d.ts +19 -0
  26. package/dist/commands/dom/empty.d.ts +19 -0
  27. package/dist/commands/dom/open.d.ts +21 -0
  28. package/dist/commands/dom/reset.d.ts +19 -0
  29. package/dist/commands/dom/select.d.ts +19 -0
  30. package/dist/commands/dom/swap.d.ts +7 -4
  31. package/dist/commands/events/trigger.d.ts +1 -1
  32. package/dist/commands/execution/blur.d.ts +19 -0
  33. package/dist/commands/execution/call.d.ts +1 -2
  34. package/dist/commands/execution/focus.d.ts +19 -0
  35. package/dist/commands/helpers/element-resolution.d.ts +2 -2
  36. package/dist/commands/helpers/event-waiting.d.ts +1 -1
  37. package/dist/commands/helpers/numeric-target-parser.d.ts +7 -0
  38. package/dist/commands/index.d.ts +34 -2
  39. package/dist/commands/index.js +19352 -4845
  40. package/dist/commands/index.mjs +19320 -4846
  41. package/dist/commands/navigation/go.d.ts +3 -0
  42. package/dist/commands/navigation/scroll-to.d.ts +26 -0
  43. package/dist/commands/utility/beep.d.ts +2 -2
  44. package/dist/commands/utility/breakpoint.d.ts +19 -0
  45. package/dist/commands/utility/pick.d.ts +11 -2
  46. package/dist/compatibility/browser-bundle-modular.d.ts +2 -2
  47. package/dist/compatibility/browser-bundle-multilingual.d.ts +1 -1
  48. package/dist/compatibility/browser-bundle-semantic-complete.d.ts +3 -3
  49. package/dist/compatibility/browser-bundle.d.ts +13 -6
  50. package/dist/compatibility/browser-modular.d.ts +1 -3
  51. package/dist/core/expression-evaluator.d.ts +4 -4
  52. package/dist/core/expression-registry.d.ts +8 -0
  53. package/dist/expressions/bundles/common-expressions.d.ts +2 -2
  54. package/dist/expressions/bundles/core-expressions.d.ts +2 -2
  55. package/dist/expressions/bundles/full-expressions.d.ts +2 -2
  56. package/dist/expressions/bundles/index.d.ts +3 -3
  57. package/dist/expressions/collection/index.d.ts +35 -0
  58. package/dist/expressions/conversion/impl/index.d.ts +1 -1
  59. package/dist/expressions/index.d.ts +4 -3
  60. package/dist/expressions/index.js +1117 -1590
  61. package/dist/expressions/index.mjs +1113 -1586
  62. package/dist/expressions/logical/index.d.ts +2 -0
  63. package/dist/expressions/mathematical/index.d.ts +11 -0
  64. package/dist/expressions/shared/index.d.ts +1 -1
  65. package/dist/expressions/shared/number-utils.d.ts +1 -0
  66. package/dist/htmx/htmx-attribute-processor.d.ts +37 -1
  67. package/dist/htmx/htmx-translator.d.ts +2 -0
  68. package/dist/htmx/i18n-hooks.d.ts +15 -0
  69. package/dist/htmx/i18n-orchestrator.d.ts +15 -0
  70. package/dist/htmx/lang-resolver.d.ts +3 -0
  71. package/dist/htmx/sse.d.ts +60 -0
  72. package/dist/htmx/ws.d.ts +59 -0
  73. package/dist/hyperfixi-browser-classic-i18n.js +2 -0
  74. package/dist/hyperfixi-browser-minimal.js +1 -0
  75. package/dist/hyperfixi-browser-standard.js +2 -0
  76. package/dist/hyperfixi-browser.js +2 -0
  77. package/dist/hyperfixi-classic-i18n.js +1 -1
  78. package/dist/hyperfixi-hx-v4.js +1 -0
  79. package/dist/hyperfixi-hx.js +1 -1
  80. package/dist/hyperfixi-hybrid-complete.js +1 -1
  81. package/dist/hyperfixi-hybrid-hx.js +1 -0
  82. package/dist/hyperfixi-minimal.js +1 -1
  83. package/dist/hyperfixi-multilingual.js +1 -1
  84. package/dist/hyperfixi-standard.js +1 -1
  85. package/dist/hyperfixi.js +1 -1
  86. package/dist/hyperfixi.mjs +1 -1
  87. package/dist/index.d.ts +2 -0
  88. package/dist/index.js +43591 -45060
  89. package/dist/index.min.js +1 -1
  90. package/dist/index.mjs +43588 -45061
  91. package/dist/lib/index.d.ts +2 -2
  92. package/dist/lib/morph-adapter.d.ts +0 -13
  93. package/dist/lib/swap-executor.d.ts +0 -10
  94. package/dist/lib/view-transitions.d.ts +1 -30
  95. package/dist/lokascript-browser-classic-i18n.js +1 -1
  96. package/dist/lokascript-browser-minimal.js +1 -1
  97. package/dist/lokascript-browser-standard.js +1 -1
  98. package/dist/lokascript-browser.js +1 -1
  99. package/dist/lokascript-hybrid-complete.js +1 -1
  100. package/dist/lokascript-hybrid-hx.js +1 -1
  101. package/dist/lokascript-multilingual.js +1 -1
  102. package/dist/lsp-metadata.d.ts +9 -4
  103. package/dist/lsp-metadata.js +187 -3
  104. package/dist/lsp-metadata.mjs +185 -4
  105. package/dist/metadata.d.ts +1 -1
  106. package/dist/metadata.js +3 -3
  107. package/dist/metadata.mjs +3 -3
  108. package/dist/multilingual/bridge.d.ts +1 -1
  109. package/dist/multilingual/index.js +79 -22
  110. package/dist/multilingual/index.mjs +79 -22
  111. package/dist/parser/command-parsers/animation-commands.d.ts +1 -0
  112. package/dist/parser/command-parsers/utility-commands.d.ts +1 -0
  113. package/dist/parser/extensions.d.ts +51 -0
  114. package/dist/parser/full-parser.js +1224 -899
  115. package/dist/parser/full-parser.mjs +1224 -899
  116. package/dist/parser/helpers/ast-helpers.d.ts +1 -0
  117. package/dist/parser/helpers/parsing-helpers.d.ts +4 -0
  118. package/dist/parser/parser-types.d.ts +8 -28
  119. package/dist/parser/parser.d.ts +3 -7
  120. package/dist/parser/pratt-parser.d.ts +0 -3
  121. package/dist/parser/runtime.d.ts +4 -0
  122. package/dist/parser/semantic-integration.d.ts +17 -0
  123. package/dist/parser/types.d.ts +7 -1
  124. package/dist/reference/index.js +91 -0
  125. package/dist/reference/index.mjs +91 -0
  126. package/dist/registry/index.js +12866 -5876
  127. package/dist/registry/index.mjs +12866 -5876
  128. package/dist/registry/universal-types.d.ts +2 -1
  129. package/dist/runtime/command-adapter.d.ts +23 -16
  130. package/dist/runtime/plugin.d.ts +14 -0
  131. package/dist/runtime/runtime-base.d.ts +32 -7
  132. package/dist/runtime/runtime-factory.d.ts +3 -3
  133. package/dist/runtime/runtime.d.ts +2 -2
  134. package/dist/test-setup.d.ts +1 -0
  135. package/dist/types/base-types.d.ts +3 -0
  136. package/dist/types/feature-types.d.ts +1 -1
  137. package/dist/types/index.d.ts +2 -2
  138. package/package.json +26 -20
  139. package/vocab/htmx/ar.js +60 -0
  140. package/vocab/htmx/bn.js +49 -0
  141. package/vocab/htmx/de.js +60 -0
  142. package/vocab/htmx/en.js +21 -0
  143. package/vocab/htmx/es.js +60 -0
  144. package/vocab/htmx/fr.js +59 -0
  145. package/vocab/htmx/he.js +40 -0
  146. package/vocab/htmx/hi.js +60 -0
  147. package/vocab/htmx/id.js +57 -0
  148. package/vocab/htmx/it.js +58 -0
  149. package/vocab/htmx/ja.js +60 -0
  150. package/vocab/htmx/ko.js +60 -0
  151. package/vocab/htmx/ms.js +35 -0
  152. package/vocab/htmx/pl.js +60 -0
  153. package/vocab/htmx/pt.js +60 -0
  154. package/vocab/htmx/qu.js +60 -0
  155. package/vocab/htmx/ru.js +60 -0
  156. package/vocab/htmx/sw.js +59 -0
  157. package/vocab/htmx/th.js +49 -0
  158. package/vocab/htmx/tl.js +33 -0
  159. package/vocab/htmx/tr.js +60 -0
  160. package/vocab/htmx/uk.js +60 -0
  161. package/vocab/htmx/vi.js +51 -0
  162. package/vocab/htmx/zh.js +60 -0
  163. package/dist/bundles/test-minimal.d.ts +0 -3
  164. package/dist/bundles/test-standard.d.ts +0 -3
  165. package/dist/chunks/bridge-Clbh_xAj.js +0 -2
  166. package/dist/chunks/browser-modular-DIOxQqhV.js +0 -2
  167. package/dist/chunks/feature-eventsource-B5F2-H1r.js +0 -2
  168. package/dist/chunks/feature-webworker-3bAp0ac9.js +0 -2
  169. package/dist/chunks/index-DcxoRUBe.js +0 -2
  170. package/dist/compatibility/browser-bundle-minimal.d.ts +0 -8
  171. package/dist/compatibility/browser-bundle-standard.d.ts +0 -8
  172. package/dist/compatibility/hyperscript-tests/test-adapter.d.ts +0 -13
  173. package/dist/core/base-expression-evaluator.d.ts +0 -74
  174. package/dist/core/binary-expression-evaluator.d.ts +0 -7
  175. package/dist/core/call-expression-evaluator.d.ts +0 -7
  176. package/dist/core/configurable-expression-evaluator.d.ts +0 -5
  177. package/dist/core/lazy-expression-evaluator.d.ts +0 -22
  178. package/dist/core/parser.d.ts +0 -21
  179. package/dist/core/selector-evaluator.d.ts +0 -15
  180. package/dist/core/template-literal-evaluator.d.ts +0 -5
  181. package/dist/expressions/comparison/index.d.ts +0 -80
  182. package/dist/expressions/comparison/utils.d.ts +0 -2
  183. package/dist/expressions/conversion/impl/bridge.d.ts +0 -117
  184. package/dist/expressions/logical/impl/pattern-matching.d.ts +0 -58
  185. package/dist/expressions/positional/impl/bridge.d.ts +0 -95
  186. package/dist/expressions/property/index.d.ts +0 -55
  187. package/dist/expressions/references/impl/bridge.d.ts +0 -54
  188. package/dist/extensions/index.d.ts +0 -3
  189. package/dist/extensions/tailwind.d.ts +0 -22
  190. package/dist/mod.d.ts +0 -63
  191. package/dist/parser/expression-parser.d.ts +0 -6
  192. package/dist/runtime/runtime-experimental.d.ts +0 -18
  193. package/dist/scripts/code-generator.d.ts +0 -64
  194. package/dist/scripts/generate-missing-commands.d.ts +0 -4
@@ -1,2 +1,2 @@
1
- var hyperfixi=function(){"use strict";const e="then",t="else",r="end",n="and",s="for",i="while",a="until",o="forever",l="times",c="index",u="in",d="to",m="from",p="with",h="of",f="on",y="event",g="behavior",v="global",b="the",w="start",k=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),E=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","swap","morph","push","replace","process"]),x=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),C="at end of",A=["into","before","after","at",x,C,"at the start of","at the end of"],S=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),T=e=>k.has(e.toLowerCase()),L=e=>E.has(e.toLowerCase()),O=e=>S.has(e.toLowerCase()),P=e=>N.has(e.toLowerCase()),N=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),I=new Set(["me","it","you","result","my","its","your"]),j=new Set(["and","or","not","no"]),R=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals"]),q=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"]),_=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 M;!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"}(M||(M={}));const $=new Set(["+","-","*","/","mod"]),V=new Set(["ms","s","seconds","minutes","hours","days"]);function D(e,t=1){const r=e.position+t;return e.input.length>r?e.input[r]:""}function B(e){const t=e.input[e.position];return e.position++,"\n"===t?(e.line++,e.column=1):"\r"===t?("\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1):e.column++,t}function F(e){const t=e.input,r=t.length;for(;r>e.position;){const r=t[e.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;B(e)}}function z(e,t,r,n,s){const i=n??e.position-r.length,a=e.position;let o=e.column-r.length;if(void 0!==n){o=1;let t=-1;for(let r=0;n>r;r++)"\n"!==e.input[r]&&"\r"!==e.input[r]||(t=r);o=n-t}const l={kind:t,value:r,start:i,end:a,line:H(e,i),column:o};e.tokens.push(l)}function H(e,t){let r=1;for(let n=0;t>n&&e.input.length>n;n++){const t=e.input[n];"\n"===t?r++:"\r"===t&&(r++,e.input.length>n+1&&"\n"===e.input[n+1]&&n++)}return r}function U(e){const t=e.position;let r="";for(B(e),B(e);e.input.length>e.position&&"\n"!==e.input[e.position];)r+=B(e);z(e,M.COMMENT,"--"+r,t)}function W(e){const t=e.position,r=B(e);let n=r;for(;e.input.length>e.position;){const t=B(e);if(n+=t,t===r)break;"\\"===t&&e.input.length>e.position&&(n+=B(e))}z(e,M.STRING,n,t)}function J(e){const t=e.position;B(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){B(e);break}if("\\"===t){if(B(e),e.input.length>e.position){const t=B(e);switch(t){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=t}}}else r+=B(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-r.length}`);z(e,M.TEMPLATE,r,t)}function K(e){const t=e.position;let r=B(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(r+=B(e);e.input.length>e.position;){const t=e.input[e.position];if(r+=B(e),"}"===t)break}z(e,M.SELECTOR,r,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if(!re(t)&&"-"!==t&&"_"!==t&&":"!==t)break;r+=B(e)}z(e,M.SELECTOR,r,t)}}function Z(e){const t=e.position;let r="";for(r+=B(e);e.input.length-1>e.position;){const t=e.input[e.position],n=e.input[e.position+1];if(r+=B(e),"/"===t&&">"===n){r+=B(e);break}}z(e,M.SELECTOR,r,t)}function Y(e){const t=e.position;let r=B(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!re(t)&&"_"!==t&&"-"!==t)break;r+=B(e)}z(e,M.SYMBOL,r,t)}function G(e){const t=e.position;let r="";const n=e.input[e.position];if(("'"===n||"'"===n)&&"s"===D(e,1))return r="'s",B(e),B(e),void z(e,M.OPERATOR,r,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(r=i,B(e),B(e),B(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,B(e),B(e)):r=B(e),z(e,M.OPERATOR,r,t)}function X(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=B(e)}if(n>e.position&&"."===r[e.position]&&(e.position+1>=n||"."!==r[e.position+1]))for(s+=B(e);n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=B(e)}if(n>e.position){const t=r[e.position];if("e"===t||"E"===t){const t=n>e.position+1?r[e.position+1]:"",i=n>e.position+2?r[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=B(e),"+"!==r[e.position]&&"-"!==r[e.position]||(s+=B(e));n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=B(e)}}}const i=e.position;let a="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;a+=B(e)}V.has(a)?z(e,M.TIME,s+a,t):(e.position=i,z(e,M.NUMBER,s,t))}function Q(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=B(e)}const i=function(e,t,r){const n=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;const i=e.tokens[e.tokens.length-1];if(i&&(i.kind===M.IDENTIFIER||i.kind===M.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}F(e);let a="";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;a+=B(e)}if(a){const t=a.toLowerCase(),s=`${n} ${t}`,i=function(e,t,r,n){const s=t.toLowerCase(),i=r.toLowerCase();if("at"===s){const t=e.position;if("the"===i){F(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=B(e)}const s=r.toLowerCase();if("start"===s||"end"===s){F(e);let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;t+=B(e)}if("of"===t.toLowerCase())return z(e,M.IDENTIFIER,`at the ${s} of`,n),!0}return e.position=t,!1}if("start"===i||"end"===i){F(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=B(e)}return"of"===r.toLowerCase()?(z(e,M.IDENTIFIER,`at ${i} of`,n),!0):(e.position=t,!1)}}return!1}(e,n,t,r);if(i)return!0;const o=function(e,t,r){const n=e.position;let s=`${t} ${r}`,i=e.position;const a=[t,r];for(;8>a.length&&(F(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;t+=B(e)}if(!t)break;a.push(t.toLowerCase());const r=a.join(" ");R.has(r)&&(s=r,i=e.position)}return R.has(s)&&s!==`${t} ${r}`?(e.position=i,s):(e.position=n,null)}(e,n,t);if(o)return z(e,M.OPERATOR,o,r),!0;if(R.has(s))return z(e,M.OPERATOR,s,r),!0}return R.has(n)?(e.position=s,z(e,M.OPERATOR,t,r),!0):(e.position=s,!1)}(e,s,t);if(i)return;const a=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||j.has(t)||$.has(e)||$.has(t)||R.has(t)?M.OPERATOR:M.IDENTIFIER}(s);z(e,a,s,t)}function ee(e){const t=e.position,r=e.input,n=r.length;B(e);let s="$";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=B(e)}z(e,M.IDENTIFIER,s,t)}function te(e){return/[a-zA-Z]/.test(e)}function re(e){return/[a-zA-Z0-9]/.test(e)}function ne(e){let t=e.position+1,r=!1;for(;e.input.length>t;){const n=e.input[t];if("/"===n&&e.input.length>t+1&&">"===e.input[t+1])return r;if(re(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=!0,t++;else{if(" "!==n&&"\t"!==n)return!1;t++}if(t-e.position>50)return!1}return!1}function 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}(),ae=ie,oe=ie,le=ie,ce=ie,ue=ie,de=(...e)=>{ae&&console.log("🔧",...e)},me=(...e)=>{oe&&console.log("🎯",...e)},pe=(...e)=>{le&&console.log("📝",...e)},he=(...e)=>{ce&&console.log("🔍",...e)},fe=(...e)=>{ue&&console.log("🚀",...e)};let ye=!1,ge=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ye=!0,ge=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let ve={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class be{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(be.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const r=e.toLowerCase();return!!/\bjs\b/.test(r)||!!/\btell\b/.test(r)||!!/\*[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 n=this.analyzer.analyze(e,this.language),s=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,a=!i&&n.confidence>0;if(ye){const t={};if(n.command?.roles)for(const[e,r]of n.command.roles)t[e]=r.value;const o={input:e.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:a,command:n.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(e){if(!ye)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",r=Math.round(100*e.confidence),n=Math.round(100*e.threshold),s=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),e.command&&console.log("Command: "+e.command),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),ge){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});ge.dispatchEvent(t)}}(o),r=o,ve.totalParses++,r.semanticSuccess?ve.semanticSuccesses++:r.fallbackTriggered?ve.semanticFallbacks++:ve.traditionalParses++,ve.confidenceHistory.push(r.confidence),ve.confidenceHistory.length>100&&ve.confidenceHistory.shift(),ve.averageConfidence=ve.confidenceHistory.reduce((e,t)=>e+t,0)/ve.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:!1,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var r}buildCommandNode(e){const{command:t}=e;if(!t)throw Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const r=[],n={};for(const[e,s]of t.roles){const i=this.semanticValueToExpression(s);switch(e){case"patient":case"event":r.push(i);break;case"destination":"put"===t.name?n.into=i:"add"===t.name||"append"===t.name||"prepend"===t.name?n.to=i:n.on=i;break;case"source":"fetch"===t.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[e]=i}}return{type:"command",name:t.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],r={},n=e.roles.get("loopType");n&&t.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("patient");"for"==(n?n.value+"":"")&&s&&t.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=e.roles.get("event");i&&t.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const a=e.roles.get("source");a&&t.push(this.semanticValueToExpression(a));const o=e.roles.get("quantity");o&&t.push(this.semanticValueToExpression(o));const l=e.roles.get("condition");return l&&(r.condition=this.semanticValueToExpression(l)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],r=e.roles.get("destination");if(r)if("property-path"===r.type){const e=r;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(r));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=e.roles.get("patient");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],r=e.roles.get("condition");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:e.name,args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(e.raw||"")}}parseExpressionString(e){let t=0;const r=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},n=()=>{r();const n=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(n,t)},s=()=>{const n=[];if(t++,r(),")"!==e[t])for(n.push(i()),r();","===e[t];)t++,r(),n.push(i()),r();return")"===e[t]&&t++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let a={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;e.length>t;){r();const i=e[t];if("."===i){t++;const e=n();e&&(a={type:"memberExpression",object:a,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;a={type:"callExpression",callee:a,arguments:s(),start:0,end:0,line:1,column:0}}}return a};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function we(e){return e.kind===M.IDENTIFIER&&k.has(e.value.toLowerCase())}function ke(e){return e.kind===M.IDENTIFIER&&_.has(e.value.toLowerCase())}function Ee(e){return e.kind===M.IDENTIFIER&&q.has(e.value.toLowerCase())}function xe(e){return e.kind===M.IDENTIFIER&&I.has(e.value.toLowerCase())}function Ce(e){return R.has(e.value.toLowerCase())}function Ae(e){return e.kind===M.IDENTIFIER}function Se(e){return e.kind===M.SELECTOR}function Te(e){return e.kind===M.SELECTOR&&!e.value.startsWith("<")}function Le(e){return e.kind===M.STRING||e.kind===M.NUMBER||e.kind===M.TEMPLATE}function Oe(e){return e.kind===M.IDENTIFIER}function Pe(e){return e.kind===M.TIME}function Ne(e){return e.kind===M.SYMBOL}function Ie(e){return e.kind===M.COMMENT}function je(e){if(e.kind!==M.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(k.has(t)||_.has(t)||q.has(t)||I.has(t))}function Re(e){return e.kind===M.STRING}function qe(e){return e.kind===M.NUMBER}function _e(e){if(e.kind===M.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function Me(e){return e.kind===M.TEMPLATE}function $e(e){return e.kind===M.SELECTOR&&e.value.startsWith("<")}function Ve(e){return e.kind===M.SELECTOR&&e.value.startsWith("#")}function De(e){return e.kind===M.SELECTOR&&e.value.startsWith(".")}function Be(e){return e.kind===M.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function Fe(e){if(e.kind!==M.OPERATOR)return!1;const t=e.value.toLowerCase();return!j.has(t)&&!R.has(t)}function ze(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function He(e,t,r){return{type:"literal",value:e,raw:t,start:r.start,end:r.end,line:r.line,column:r.column}}function Ue(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function We(e,t,r,n){return{type:"binaryExpression",operator:e,left:t,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function Je(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ke(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ze(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ye(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ge(e,t,r){return{type:"propertyOfExpression",property:e,target:t,start:r.start,end:r.end,line:r.line,column:r.column}}function Xe(e,t,r){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...r&&{source:r}}],start:e.start,end:e.end,line:e.line,column:e.column}}be.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const Qe=[{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 et(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const tt=[e,n,t,r];function rt(e,t=[]){if(e.isAtEnd())return!0;for(const t of tt)if(e.check(t))return!0;for(const r of t)if(e.check(r))return!0;return!!e.checkIsCommand()}function nt(e,t=[]){if(!rt(e,t))return e.parseExpression()}function st(e,t,r){return!!e.check(t)&&(e.advance(),r.push(e.createIdentifier(t)),!0)}function it(e,t,r){for(const n of t)if(e.check(n))return e.advance(),r.push(e.createIdentifier(n)),n;return null}function at(e,t){return!!e.check(t)&&(e.advance(),!0)}class ot{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new ot(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 ot(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 ot(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 ot(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 lt(e,t){const r=[];let n="";const s=e.peek().start||0,i=e.peek().line||1,a=e.peek().column||1;if(e.checkIdentifierLike()){for(n=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),n+=":",e.checkIdentifierLike()&&(n+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const r=e.savePosition();let n;if(e.checkIdentifierLike()){const t=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=t):e.restorePosition(r)}const s=e.parseExpression();if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:s}],start:s.start,end:s.end,line:s.line,column:s.column}:s),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),r.push({type:"functionCall",name:n,args:t,start:s,end:e.getPosition().end,line:i,column:a})}else r.push({type:"string",value:n,start:s,end:e.getPosition().end,line:i,column:a})}const o=[...r];if(e.check("on")||e.check("to")){const t=e.advance().value;for(o.push(e.createIdentifier(t));!rt(e);)o.push(e.parsePrimary())}return ot.fromIdentifier(t).withArgs(...o).endingAt(e.getPosition()).build()}function ct(e,t){const r=[];if(e.check(b)){const t=e.advance();if(r.push({type:"identifier",name:b,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(y)){const t=e.advance();r.push({type:"identifier",name:y,start:t.start,end:t.end,line:t.line,column:t.column})}}return ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function ut(n,s){const i=[];let a=!1;const o=n.savePosition();for(let t=0;500>t&&!n.isAtEnd();t++){const t=n.peek();if(t.value===e){a=!0;break}if(t.value===r||t.value===g||"def"===t.value||t.value===f)break;n.advance()}n.restorePosition(o);let l=!1;if(!a){const e=n.savePosition(),i=s.line,a=100;for(;!n.isAtEnd()&&a>n.current-e;){const e=n.peek(),s=e.value?.toLowerCase();if(s===g||"def"===s||s===f)break;if(s===t||s===r){e.line===i&&(l=!0);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==e.line&&e.line!==i){l=!0;break}n.advance()}n.restorePosition(e)}const c=a||l;let u;if(c)u=n.parseExpression();else{const t=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(e)&&r>i;){const e=n.savePosition();t.push(n.parseLogicalAnd()),n.savePosition()===e&&n.advance(),i++}if(0===t.length)throw Error("Expected condition after if/unless");u=1===t.length?t[0]:{type:"expression",tokens:t,start:t[0].start,end:t[t.length-1].end,line:s.line,column:s.column}}if(i.push(u),c){a&&n.advance();const e=[];for(;!n.isAtEnd()&&!n.check(t)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const t=n.parseCommand();t&&e.push(t)}if(0===e.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(Je(e,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}));let o=!1;if(n.check(t))if(n.advance(),n.check("if")){const e=n.peek();n.advance();const t=ut(n,e);i.push(Je([t],{start:e.start,end:n.getPosition().end,line:e.line,column:e.column})),o=!0}else{const e=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const t=n.parseCommand();t&&e.push(t)}i.push(Je(e,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}o||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const e=n.parseCommand();i.push(Je([e],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return ot.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function dt(e,t){const r=[],n={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(r.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();r.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();n.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function mt(e,t){const r=[],n=nt(e,[m]);n&&r.push(n),st(e,m,r);const s=nt(e);return s&&r.push(s),ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function pt(e,t){const r=[];if(e.check("between")){e.advance(),r.push(e.createIdentifier("between"));const i=nt(e,[n]);i&&r.push(i),st(e,n,r);const a=nt(e,[m,f,s]);if(a&&r.push(a),it(e,[m,f],r)){const t=nt(e);t&&r.push(t)}return ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}const i=nt(e,[m,f]);if(i&&r.push(i),it(e,[m,f],r)){const t=nt(e);t&&r.push(t)}return ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function ht(e,t){const n=e.parseExpression();if(!n)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 a=i.toLowerCase();"at start of"===a||"at the start of"===a?i=x:"at end of"===a||"at the end of"===a?i=C:"at"===i&&(e.check(w)||e.check(b)?(at(e,b),e.check(w)&&(e.advance(),e.check(h)&&(e.advance(),i=x))):e.check(r)&&(e.advance(),e.check(h)&&(e.advance(),i=C)));const o=e.parseExpression();return o?ot.fromIdentifier(t).withArgs(n,e.createIdentifier(i),o).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const ft=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function yt(s,i){const a=s.savePosition();let o=null,l=[];try{o=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(),r=e.advance();return{type:"identifier",name:r.value,scope:t.value,start:t.start,end:r.end}}(s)??function(e){if(!e.check(b))return null;const t=e.savePosition();e.advance();const r=e.parseExpression();if(!r)return e.restorePosition(t),null;if("binaryExpression"===r.type&&r.operator===h){const e=r.left,t=r.right;return Ge(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(d)?r:(e.restorePosition(t),null)}(s),o||(o=s.parseExpression())}catch{s.restorePosition(a),o=null}if(!o){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(d)||s.check(e)||s.check(n)||s.check(t)||s.check(r));)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")===h){const t=i[1],r=i[3];return{expression:Ge(Ue(e(t,"value")||e(t,"name")||"",{start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1}),{type:"idSelector"===r.type?"idSelector":"cssSelector",value:e(r,"value")||e(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:i[0].start??0,end:r.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);o=i.expression,l=i.tokens}if(!s.check(d)){const e=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+e)}s.advance();const c=s.parseExpression()??s.parsePrimary(),u=[];return o?u.push(o):l.length>0&&u.push(...l),u.push(s.createIdentifier(d)),c&&u.push(c),ot.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function gt(e,t){const r=[];for(;!rt(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)r.push(e.parsePrimary());return ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function vt(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||rt(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 wt(e){const t=[],r=e.getPosition();do{if(!e.checkIdentifierLike())break;const r=e.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};e.consume(":","Expected ':' after property name in fetch named arguments");const s=e.parsePrimary();s&&t.push({key:n,value:s})}while(e.match(",")&&!e.isAtEnd());const n=e.getPosition();return{type:"objectLiteral",properties:t,start:r.start,end:n.end,line:r.line,column:r.column}}const kt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),Et=new Set([")","]","}",","]);function xt(...e){const t=new Map;for(const r of e)for(const[e,n]of r){const r=t.get(e);t.set(e,r?{prefix:n.prefix??r.prefix,infix:n.infix??r.infix}:{...n})}return t}function Ct(e,t){return{infix:{bp:[e,e+1],handler:t??((t,r,n)=>({type:"binaryExpression",operator:r.value,left:t,right:n.parseExpr(e+1),start:t.start}))}}}function At(e,t){return{infix:{bp:[e+1,e],handler:(t,r,n)=>({type:"binaryExpression",operator:r.value,left:t,right:n.parseExpr(e),start:t.start})}}}function St(e,t){return{prefix:{bp:e,handler:t??((t,r)=>({type:"unaryExpression",operator:t.value,operand:r.parseExpr(e),start:t.start}))}}}const Tt=new Map([["or",Ct(10)],["||",Ct(10)],["and",Ct(20)],["&&",Ct(20)],["==",Ct(30)],["!=",Ct(30)],["<",Ct(30)],[">",Ct(30)],["<=",Ct(30)],[">=",Ct(30)],["is",Ct(30)],["matches",Ct(30)],["contains",Ct(30)],["+",{...Ct(40),...St(80)}],["-",{...Ct(40),...St(80)}],["*",Ct(50)],["/",Ct(50)],["%",Ct(50)],["mod",Ct(50)],["^",At(60)],["**",At(60)],["as",Ct(70,(e,t,r)=>({type:"asExpression",expression:e,targetType:r.parseExpr(71),start:e.start}))],["not",St(80)],["!",St(80)],["no",St(80)]]),Lt=new Map([["first",St(85,(e,t)=>({type:"positionalExpression",position:"first",operand:t.parseExpr(85),start:e.start}))],["last",St(85,(e,t)=>({type:"positionalExpression",position:"last",operand:t.parseExpr(85),start:e.start}))]]),Ot=new Map([[".",{infix:{bp:[90,91],handler:(e,t,r)=>({type:"propertyAccess",object:e,property:r.advance().value,start:e.start})}}],["?.",{infix:{bp:[90,91],handler:(e,t,r)=>({type:"optionalChain",object:e,property:r.advance().value,start:e.start})}}],["'s",{infix:{bp:[95,96],handler:(e,t,r)=>({type:"possessiveExpression",object:e,property:r.advance().value,start:e.start})}}]]),Pt=new Map([["===",Ct(30)],["!==",Ct(30)],["is not",Ct(30)],["is a",Ct(30)],["is an",Ct(30)],["is not a",Ct(30)],["is not an",Ct(30)],["is in",Ct(30)],["is not in",Ct(30)],["has",Ct(30)],["have",Ct(30)],["match",Ct(30)],["include",Ct(30)],["includes",Ct(30)],["equals",Ct(30)],["does not contain",Ct(30)],["does not include",Ct(30)],["in",Ct(30)],["of",Ct(30)],["really",Ct(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",St(80)]]),Nt=new Map([["=",At(5)]]);xt(Tt,Lt,Ot);const It=xt(Tt,Pt,Nt);class jt{constructor(e,t,r){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 be({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=r||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){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}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def"))break;{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){pe("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];pe(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){pe(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(pe("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),r++,pe(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),pe(`✅ 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 pe("⚠️ 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};pe("✅ PARSER: No more event handlers, at end of input");break}}return pe(`✅ PARSER: Finished parsing, creating Program node with ${t.length} statements`),this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const e=this.parseExpression();return this.error?{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,r=this.prattCache.get(t);if(r)return this.current=r.endPos,r.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const n=this.peek(),s=jt.PRATT_TABLE.get(n.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(),r=jt.PRATT_TABLE.get(t.value);if(!r?.infix){if(kt.has(t.value)||Et.has(t.value))break;break}const[n]=r.infix.bp;if(e>n)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{}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()&&!jt.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=r.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(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||kt.has(t.value)||Et.has(t.value)},atEnd:()=>e.current>=e.tokens.length}}parseAssignment(){let e=this.parseLogicalOr();if(this.match("=")){if(this.check(">")){if(this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpression()}catch{}return this.createErrorNode()}const t=this.previous().value,r=this.parseAssignment();e=this.createBinaryExpression(t,e,r)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("or");){const t=this.previous().value,r=this.parseLogicalAnd();e=this.createBinaryExpression(t,e,r)}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("and");){const t=this.previous().value,r=this.parseEquality();e=this.createBinaryExpression(t,e,r)}return e}parseEquality(){let e=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const t=this.previous().value;if(jt.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,!1);continue}const r=this.parseComparison();e=this.createBinaryExpression(t,e,r)}return e}parseComparison(){let e=this.parseAddition();for(;this.matchComparisonOperator();){const t=this.previous().value;if(jt.POSTFIX_UNARY_OPERATORS.has(t)){e=this.createUnaryExpression(t,e,!1);continue}const r=this.parseAddition();e=this.createBinaryExpression(t,e,r)}return e}parseAddition(){let e=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const t=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${t}${this.peek().value}`),e;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),e;const r=this.parseMultiplication();e=this.createBinaryExpression(t,e,r)}return e}parseMultiplication(){let e=this.parseUnary();for(;this.match("*","/","%","mod");){const t=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const r=this.peek().value;return this.addError("*"===t&&"*"===r?"Unexpected token: "+r:`Invalid operator combination: ${t}${r}`),e}if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),e;const r=this.parseUnary();e=this.createBinaryExpression(t,e,r)}return e}parseUnary(){if(this.match("not","no","exists","some","-","+")){const e=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression(e,t,!0)}if(this.check("does")&&this.tokens.length>this.current+1&&"not"===this.tokens[this.current+1].value&&this.tokens.length>this.current+2&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression("does not exist",e,!0)}return this.parseImplicitBinary()}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else if("wait"===e.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):T(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):O(e)}createCommandFromIdentifier(e){const t=[],r=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:!1,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return L(e)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return ht(s,i);case"trigger":case"send":return lt(s,i);case"remove":return mt(s,i);case"toggle":return pt(s,i);case"set":return yt(s,i);case"halt":return ct(s,i);case"measure":return dt(s,i);case"js":return function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const s=e.peek().start,i=function(e,t){const r=e.getInputSlice(t);if(!r)return t;let n=0;for(;r.length>n;){const e=r[n];if("'"!==e&&"’"!==e&&"‘"!==e)if('"'!==e)if("`"!==e)if("/"===e&&r.length>n+1&&"/"===r[n+1])for(n+=2;r.length>n&&"\n"!==r[n];)n++;else if("/"===e&&r.length>n+1&&"*"===r[n+1]){for(n+=2;r.length>n&&("*"!==r[n]||n+1>=r.length||"/"!==r[n+1]);)n++;n+=2}else{if(!("e"!==e&&"E"!==e||n+3>r.length||"end"!==r.slice(n,n+3).toLowerCase()||0!==n&&/[a-zA-Z0-9_]/.test(r[n-1])||r.length>n+3&&/[a-zA-Z0-9_]/.test(r[n+3])))return t+n;n++}else{for(n++;r.length>n&&"`"!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&'"'!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&r[n]!==e;)"\\"===r[n]&&n++,n++;n++}}return t+r.length}(e,s);for(;!e.isAtEnd()&&!e.check(r)&&e.peek().start<i;)e.advance();e.consume(r,"Expected end after js code body");const a={type:"literal",value:e.getInputSlice(s,i).trim(),start:t.start,end:e.getPosition().end},o={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return ot.fromIdentifier(t).withArgs(a,o).endingAt(e.getPosition()).build()}(s,i);case"tell":return function(s,i){const a=s.parseExpression();if(!a)throw Error("tell command requires a target expression");const o=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const e=s.parseCommand();if(!e)break;o.push(e)}catch{break}if(s.match(n))continue;if(s.check(e)||s.check(t)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===o.length)throw Error("tell command requires at least one command after the target");return ot.fromIdentifier(i).withArgs(a,...o).endingAt(s.getPosition()).build()}(s,i);case"swap":case"morph":return function(e,t){console.log("[PARSER DEBUG] parseSwapCommand called");const r=[];let n=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const s=t.value.toLowerCase();ft.includes(s)&&(n=s,e.advance(),r.push(e.createIdentifier(n)))}}if("delete"===n){const n=e.parseExpression();return n&&r.push(n),ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(h)&&(e.advance(),r.push(e.createIdentifier("of")));const s=e.parseExpression();if(s&&r.push(s),!e.isAtEnd()&&e.check(p)){e.advance(),r.push(e.createIdentifier("with"));const t=e.parseExpression();t&&r.push(t)}return ot.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}(s,i);default:return gt(s,i)}}(this.getContext(),s)}parsePutCommand(e){return ht(this.getContext(),e)}parseSetCommand(e){return yt(this.getContext(),e)}parseHaltCommand(e){return ct(this.getContext(),e)}parseMeasureCommand(e){return dt(this.getContext(),e)}parseTriggerCommand(e){return lt(this.getContext(),e)}parseCommandListUntilEnd(){const e=[];for(pe("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){pe("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;const r=this.checkIsCommand(),n=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||n){pe(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&&(pe("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(pe("✅ Parsed command:",r.name),e.push(r),t=!0)}catch(e){pe("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=n}}else this.checkIdentifier()&&pe("❌ IDENTIFIER is not a command:",this.peek().value);if(!t){pe("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(pe("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)pe("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))pe("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){pe("📍 No separator and no command, breaking. Current token:",this.peek().value);break}pe("✅ Next token is a command, continuing without separator")}}if(pe('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw pe('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return pe('✅ Found "end", consuming it'),this.advance(),pe("✅ parseCommandListUntilEnd: Successfully parsed",e.length,"commands"),e}parseRepeatCommand(e){return function(e,t){const r=[];let n="forever",d=null,h=null,f=null,g=null,v=null,w=null;if(e.check(s)){e.advance(),n=s;const t=e.peek();Ae(t)&&(v=t.value,e.advance()),e.check(u)&&(e.advance(),g=e.parseExpression())}else if(e.check(u))e.advance(),n=s,v="it",g=e.parseExpression();else if(e.check(i))e.advance(),n=i,f=e.parseExpression();else if(e.check(a))if(e.advance(),n=a,e.check(y)){e.advance(),n="until-event";const t=e.peek();if(pe("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Ae(t)&&!Ee(t))throw Error('Expected event name after "event"');if(d=t.value,e.advance(),pe("✅ Got event name:",d,"Next token:",e.peek().value),pe('🔍 Checking for "from", current token:',e.peek().value),e.check(m)){pe('✅ Found "from", advancing...'),e.advance(),pe('📍 After consuming "from", current token:',e.peek().value),at(e,b)&&pe('✅ Found "the", advancing...');const t=e.peek();pe("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),h=e.parsePrimary(),pe("✅ After parsePrimary, eventTarget:",h)}else pe('❌ No "from" found, skipping target parsing')}else f=e.parseExpression();else e.check(o)?(e.advance(),n=o):(w=e.parseExpression(),e.check(l)&&(e.advance(),n=l));let k=null;if(e.check(p)){const t=e.peekAt(1);t&&t.value.toLowerCase()===c&&(e.advance(),e.advance(),k=c)}else if(e.check(c)){e.advance();const t=e.peek();Ae(t)?(k=t.value,e.advance()):k=c}const E=e.parseCommandListUntilEnd();r.push({type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column});const x={start:t.start,end:t.end,line:t.line,column:t.column};return v&&r.push(Ke(v,x)),g&&r.push(g),f&&r.push(f),w&&r.push(w),d&&r.push(Ke(d,x)),h&&r.push(h),k&&r.push(Ke(k,x)),r.push(Je(E,{...x,end:x.end||0})),ot.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const r=[];let n=null,s=null;e.check("each")&&e.advance();const i=e.peek();if(!Ae(i))throw Error('Expected variable name after "for"');if(n=i.value,e.advance(),!e.check(u))throw Error('Expected "in" after variable name in for loop');if(e.advance(),s=e.parseExpression(),!s)throw Error('Expected collection expression after "in"');let a=null;if(e.check(p)){const t=e.peekAt(1);t&&t.value.toLowerCase()===c&&(e.advance(),e.advance(),a=c)}else if(e.check(c)){e.advance();const t=e.peek();Ae(t)?(a=t.value,e.advance()):a=c}const o=e.parseCommandListUntilEnd();r.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const l={start:t.start,end:t.end,line:t.line,column:t.column};return r.push(Ke(n,l)),r.push(s),a&&r.push(Ke(a,l)),r.push(Je(o,{...l,end:l.end||0})),ot.from({...t,value:"repeat"}).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const r=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!rt(e)){const n=e.parseExpression();return r.push(n),ot.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const n=[];do{const t=e.peek();if(!Ae(t))throw Error('Expected event name after "for"');const r=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!Ae(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(n.push({name:r,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(m)&&(e.advance(),at(e,b),s=e.parsePrimary());const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};r.push(Ye(n.map(e=>Ze([{key:Ue("name",i),value:He(e.name,`"${e.name}"`,i)},{key:Ue("args",i),value:Ye(e.params.map(e=>He(e,`"${e}"`,i)),i)}],i)),i)),s&&r.push(s)}return ot.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const r=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=e.advance().value,s=e.previous();if(r.push(Ue(n,{start:s.start,end:s.end,line:s.line,column:s.column})),e.check("(")){e.advance();const n=[];for(;!e.isAtEnd()&&!e.check(")");){const t=e.savePosition();let r;if(e.checkIdentifierLike()){const n=e.peek().value;e.advance(),e.check(":")?(e.advance(),r=n):e.restorePosition(t)}const s=e.parseExpression();if(n.push(void 0!==r?{name:r,value:s}:{value:s}),e.check(","))e.advance();else if(!e.check(")"))break}if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),n.length>0){const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};r.push(Ze(n.map(e=>({key:e.name?Ue(e.name,s):He("_positional","_positional",s),value:e.value})),s))}}return ot.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const r=[],n={};let s=null;const i=e.peek();if(Ae(i)||"*"===i.value){let t="";e.check("*")&&(t="*",e.advance());const r=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);r&&(t+=r,s={type:"string",value:t,start:i.start||0,end:e.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!e.check(d))throw Error('Expected "to" keyword after property in transition command');e.advance();const a=e.parsePrimary();if(n.to=a,e.check("over")){e.advance();const t=e.parsePrimary();n.over=t}if(e.check(p)){e.advance();const t=e.parsePrimary();n.with=t}return ot.from(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const r=[];if(e.match("{"))r.push(e.parseCSSObjectLiteral());else{const t=nt(e,[d]);t&&r.push(t)}if(e.check(d)){e.advance();const t=nt(e);t&&r.push(t)}return ot.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return ut(this.getContext(),e)}parseRemoveCommand(e){return mt(this.getContext(),e)}parseToggleCommand(e){return pt(this.getContext(),e)}parseRegularCommand(e){return gt(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifier("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}else{if(!this.check("'s"))break;{let t;this.advance(),this.check("*")?(this.advance(),t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):t=Ne(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()&&Ae(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),r=this.processEscapeSequences(t);return this.createLiteral(r,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value.slice(1,-2).trim();return this.createSelector(e)}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end,line:e.line,column:e.column}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if((!e||"end"!==e.value&&"else"!==e.value&&"then"!==e.value)&&(this.matchPredicate(je)||this.matchPredicate(ke)||this.matchPredicate(xe)||this.matchPredicate(we)||this.matchPredicate(Ee))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}return this.createIdentifier(e.value)}return"my"!==e.value||this.check(".")?"its"!==e.value||this.check(".")?"your"!==e.value||this.check(".")?"the"===e.value?this.parseTheXofY():"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(Ne(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(je))t=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const e=this.previous().value,r=e.slice(1,-1);t=this.createLiteral(r,e)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(e.push({key:t,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(je))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);r=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=!1,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();n.push(e.value),"$"===e.value&&this.check("{")&&(s=!0),"{"===e.value&&i++,"}"===e.value&&i--}const a=n.join(""),o=s?{type:"templateLiteral",value:a,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(a,a);if(t.push({key:r,value:o}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),r=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();if(this.advance(),this.check(")"))this.advance();else{let e=1;for(;e>0&&!this.isAtEnd();){const t=this.advance();"("===t.value&&e++,")"===t.value&&e--}}return{type:"callExpression",callee:{type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column},arguments:[],isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]);let s,i,a;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),a=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==a&&{finallyHandler:a},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 r=t.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}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,r,n,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)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],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 r=e.callee.name,n=this.peek();if(!(jt.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||je(n)&&!this.isCommand(n.value)||xe(n)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),jt.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(r,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&&(pe("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return pe("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseEventHandler(){pe("🔧 parseEventHandler: ENTRY - parsing event handler");const e=[],t=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(t),pe("🔧 parseEventHandler: Parsed first event name: "+t);this.check("or");){this.advance(),pe("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),pe("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(pe("🔧 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,pe(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),pe("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)s.once=!0,pe("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)s.prevent=!0,pe("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)s.stop=!0,pe("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),r=parseInt(t.value,10);if(isNaN(r))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(s.debounce=r,pe(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,pe(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else pe(`🔧 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 r=this.advance(),n=(i=r.value).endsWith("ms")?parseInt(i,10):i.endsWith("seconds")||i.endsWith("s")?1e3*parseFloat(i):i.endsWith("minutes")?6e4*parseFloat(i):i.endsWith("hours")?36e5*parseFloat(i):i.endsWith("days")?864e5*parseFloat(i):parseInt(i,10);s[t]=n,pe(`🔧 parseEventHandler: Parsed '${e} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);s[t]=r,pe(`🔧 parseEventHandler: Parsed '${e} at ${r}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`)}var i;let a,o,l,c;if(Object.keys(s).length>0&&pe("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(a=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();o=e.value,pe(`🔧 parseEventHandler: Parsed 'from' target: ${o} (kind: ${e.kind})`)}if(this.match("of")){const e=this.advance();l=e.value.startsWith("@")?e.value.substring(1):e.value,pe("🔧 parseEventHandler: Parsed attribute name: "+l)}this.match("in")&&(pe("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),c=this.parseExpression(),pe("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(pe(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(pe(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){pe("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())pe("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){pe("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const r=this.parseCommand();u.push(r);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.parseCommandWithErrorRecovery();e&&(u.push(e),pe("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&u.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){pe("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator)break;{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name))break;{const r={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};u.push(r)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const d=this.getPosition(),m={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:u,...n.length>0&&{params:n},...a&&{condition:a},...o&&{target:o},...l&&{attributeName:l},...c&&{watchTarget:c},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:d.start,end:d.end,line:d.line,column:d.column};return pe(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${l||"none"}, watchTarget: ${c?"yes":"none"}`),m}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();je(e)?(r.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),r=n.has(t.value);this.checkIsCommand()&&!r||(e.push(t.value),i=t.value,this.advance())}}const a={type:"eventHandler",event:t,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...r.length>0&&{args:r},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(a)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,r=this.parseCommand();for(this.error&&this.error!==t&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(pe("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)pe("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){pe('✅ 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(),r=this.getPosition(),n="Expected command, got: "+t.value;this.addError(n);const s=Xe(r,n,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 Qe.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return et(e,t)}parseMultiWordCommand(e,t){return function(e,t,r){const n=e.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!rt(e,["catch","finally",...n.keywords])&&!et(e.peek(),n.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&et(e.peek(),n.keywords))break}for(;!e.isAtEnd()&&et(e.peek(),n.keywords);){const t=e.advance().value,r=e.parseExpression();if(r&&(i[t]=r),!et(e.peek(),n.keywords))break}const a=ot.from(t).withArgs(...s).endingAt(e.getPosition());return Object.keys(i).length>0&&a.withModifiers(i),a.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?(pe(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(pe(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return pe("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),r=t.value.toLowerCase();if(e.includes(r))break;if(we(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 r={};let n=null;if(!e.isAtEnd()&&e.check("/")&&(n=function(e){const t=e.savePosition();let r="";for(;!e.isAtEnd()&&!vt(e);)r+=e.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:t,end:e.savePosition()}:(e.restorePosition(t),null)}(e)),n||(n=e.parsePrimary()),!n)return e.addError("fetch requires a URL"),ot.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(r.with=e.parsePrimary());for(let t=0;2>t&&!e.isAtEnd();t++)if(!e.check("as")||r.as){if(!e.check("with")||r.with)break;e.advance(),r.with=bt(e)?wt(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||at(e,"a")||at(e,"an"),r.as=e.parsePrimary();const s=ot.from(t).withArgs(n).endingAt(e.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),e);const r=this.parseMultiWordCommand(e,t);if(r)return r;const n=t.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(e);if("for"===n)return this.parseForCommand(e);if("if"===n||"unless"===n)return this.parseIfCommand(e);if("wait"===n)return this.parseWaitCommand(e);if("install"===n)return this.parseInstallCommand(e);if("transition"===n)return this.parseTransitionCommand(e);if("add"===n)return this.parseAddCommand(e);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||this.createErrorNode();const s=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const r=t.value,n="increment"===r?"+":"-";let s=!1;e.check(v)&&(s=!0,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let a;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${r} command`);a=t}else a=He(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let o=i;s&&"identifier"===i.type&&(o={...i,scope:"global"});const l={start:t.start,end:e.previous().end,line:t.line,column:t.column},c=We(n,i,a,l),u=[o,Ue(d,l),c];return ot.from(t).withName("set").withArgs(...u).withOriginalCommand(r).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 r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!t.includes(r.name??r.value))break}const i=this.getPosition();return{type:"command",name:t,args:s,isBlocking:!1,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(e),t)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;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 r="computed-"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(r),!1)}{if(Ne(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;P(t)&&pe(`💡 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 He(e,t,this.getPosition())}createIdentifier(e){return Ue(e,this.getPosition())}createBinaryExpression(e,t,r){return We(e,t,r,this.getPosition())}createUnaryExpression(e,t,r){return function(e,t,r,n){return{type:"unaryExpression",operator:e,argument:t,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}createCallExpression(e,t){return function(e,t,r){return{type:"callExpression",callee:e,arguments:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.getPosition())}createMemberExpression(e,t,r){return function(e,t,r,n){return{type:"memberExpression",object:e,property:t,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,r){return{type:"possessiveExpression",object:e,property:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(pe(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return pe("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return pe(`✅ 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 pe(`✅ 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!(!Fe(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(Te)}matchSelector(){return this.matchPredicate(Te)}checkAnySelector(){return this.checkPredicate(Se)}checkLiteral(){return this.checkPredicate(Le)}checkIdentifierLike(){return this.checkPredicate(Ae)}checkIsCommand(){return this.checkPredicate(we)}checkCommandTerminator(){return this.checkPredicate(ze)}checkReference(){return this.checkPredicate(Oe)}checkTimeExpression(){return this.checkPredicate(Pe)}checkEvent(){return this.checkPredicate(Ee)}checkContextVar(){return this.checkPredicate(xe)}checkComment(){return this.checkPredicate(Ie)}checkIdentifier(){return this.checkPredicate(je)}checkKeyword(){return this.checkPredicate(ke)}checkString(){return this.checkPredicate(Re)}matchString(){return this.matchPredicate(Re)}checkNumber(){return this.checkPredicate(qe)}matchNumber(){return this.matchPredicate(qe)}checkBoolean(){return this.checkPredicate(_e)}matchBoolean(){return this.matchPredicate(_e)}checkTemplateLiteral(){return this.checkPredicate(Me)}matchTemplateLiteral(){return this.matchPredicate(Me)}checkQueryReference(){return this.checkPredicate($e)}matchQueryReference(){return this.matchPredicate($e)}checkIdSelector(){return this.checkPredicate(Ve)}checkClassSelector(){return this.checkPredicate(De)}checkCssSelector(){return this.checkPredicate(Be)}checkBasicOperator(){return this.checkPredicate(Fe)}matchBasicOperator(){return this.matchPredicate(Fe)}matchTimeExpression(){return this.matchPredicate(Pe)}matchIdentifierLike(){return this.matchPredicate(Ae)}matchComparisonOperator(){return this.matchPredicate(Ce)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(je,e)}consumeIdentifierLike(e){return this.consumePredicate(Ae,e)}consumeEvent(e){return this.consumePredicate(Ee,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let r=t.start||0,n=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1,0===r&&this.current>0&&(r=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;r=e.start||0,n=e.line||1,s=e.column||1,0===r&&(r=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const r=this.tokens[t];if(r&&("+"===r.value||"-"===r.value)){e=r;break}}r=e.start||0,n=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)},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;pe("⚠️ synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();n.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:e,end:this.previous().end,line:t,column:r}}const n=[];if(!this.check("]"))do{if(this.check("]"))break;n.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:n,start:e,end:this.previous().end,line:t,column:r}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>{const r=e.current+t;return r>=0&&e.tokens.length>r?e.tokens[r]: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}}jt.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),jt.PRATT_TABLE=It,jt.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Rt{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const r of this.afterExecuteHooks)await r(e,t)}async runOnError(e,t){let r=t;for(const t of this.onErrorHooks){const n=await t(e,r);n instanceof Error&&(r=n)}return r}shouldIntercept(e,t){for(const r of this.interceptCommandHooks)if(r(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function qt(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function _t(e){return{ok:!0,value:e}}function Mt(e){return{ok:!1,error:e}}function $t(e){return!0===e.ok}class Vt{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,r,n,s){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,s),this.debugMode&&fe(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&fe("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&fe("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&fe("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,r){this.addCleanup(e,{type:"custom",cleanup:t,description:r||"Custom cleanup"})}registerGlobal(e,t="custom",r){this.globalCleanups.push({type:t,cleanup:e,description:r||"Global cleanup"}),this.debugMode&&fe("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e);r?r.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&fe(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let r=0;for(const e of t){try{e.cleanup(),r++}catch(e){this.debugMode&&fe("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&fe(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(e){let t=this.cleanupElement(e);const r=e.querySelectorAll("*");for(const e of r)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&fe("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&fe(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const Dt=new Map;function Bt(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||Dt,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function Ft(e){if(!e)return Bt();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=Bt(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}class zt{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const r=e.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(r,t)}unregister(e){const t=e.toLowerCase(),r=this.sources.get(t);if(r){for(const[e,r]of this.subscriptions.entries())r.source===t&&(r.unsubscribe(),this.subscriptions.delete(e));return r.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,r){const n=this.get(e);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+e);n.initialize?.();const s=n.subscribe(t,r);return this.subscriptions.set(s.id,s),s}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,r]of this.sources.entries())if(r.supports?.(e)??r.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class Ht{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,r){const n=e.toLowerCase();this.providers.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}registerGlobal(e,t,r){const n=e.toLowerCase();this.globalProviders.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,r){const n=this.get(e);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const e of n.dependencies)await this.resolve(e,t,r);const i=await n.provide(t);return n.cache&&r&&r.set(s,i),i}resolveSync(e,t,r){const n=this.get(e);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(e){const t=this,r=new Map;return new Proxy(e,{get(e,n,s){if("string"==typeof n&&t.get(n))try{return t.resolveSync(n,e,r)}catch{return t.resolve(n,e,r)}return Reflect.get(e,n,s)},has:(e,r)=>!("string"!=typeof r||!t.has(r))||Reflect.has(e,r)})}async resolveAll(e){const t=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,e,t)}catch(e){console.warn(`[ContextProviderRegistry] Failed to resolve '${s}':`,e),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Ut=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,r]of this.types)if(r.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),r=this.types.get(t);return r?.hyperscriptType??"unknown"}coerce(e,t,r){const n=this.types.get(t);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(n.isType(e))return e;if(this.config.cacheCoercions){const r=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(e),i=n.coerceFrom?.[s];if(i){const n=i(e,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(e,t){const r=this.types.get(t);if(!r)return!1;if(r.isType(e))return!0;const n=this.inferType(e);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(e,t){const r=this.types.get(t);return r&&(e===t||r.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const r=e;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,r)=>{t[r+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Wt(e){const t=Ut.get("String");return t?t.isType(e):"string"==typeof e}function Jt(e){const t=Ut.get("Number");return t?t.isType(e):"number"==typeof e}function Kt(e){const t=Ut.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Zt(e){const t=Ut.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Yt(e){const t=Ut.get("Function");return t?t.isType(e):"function"==typeof e}function Gt(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function Xt(e){return e instanceof Element}const Qt=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function er(e,t){return Qt.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const tr={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=>Gt(e)?e.tabIndex:void 0,hidden:e=>Gt(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 r=e.getAttribute("name");r&&"value"in e&&t.append(r,e.value)}),t}(e)};function rr(e,t){if(t.startsWith("computed-")){const r=t.slice(9);return function(e){return e instanceof HTMLElement}(e)?getComputedStyle(e).getPropertyValue(r):void 0}if(t.startsWith("@"))return er(e,t.slice(1));const r=tr[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return er(e,t);const n=e[t];return Yt(n)?n.bind(e):n}function nr(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 sr(e){return e.me?.ownerDocument??("undefined"!=typeof document?document:null)}function ir(e,t){return t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):t.variables?.has(e)?t.variables.get(e):"me"===e?t.me:"it"===e?t.it:"result"===e?t.result:void 0}async function ar(e,t){if(e.includes(".")){const r=e.split(".");let n=ir(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return ir(e,t)}async function or(e,t){if(he(`RESOLVE: Looking for '${e}' in context`,{hasInLocals:t.locals.has(e),localsKeys:Array.from(t.locals.keys()),value:t.locals.get(e)}),t.locals.has(e)){const r=t.locals.get(e);return he(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return he(`RESOLVE: Found '${e}' in globals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return he(`RESOLVE: Found '${e}' in variables (legacy):`,r),r}const r=Number(e);if(!isNaN(r))return r;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split("."),n=r[0];let s=null;if(t.locals.has(n)?s=t.locals.get(n):t.globals&&t.globals.has(n)?s=t.globals.get(n):t.variables&&t.variables.has(n)&&(s=t.variables.get(n)),null!=s){for(let e=1;r.length>e;e++){if(null==s)return void he(`RESOLVE: Property access failed at '${r[e-1]}'`);s=s[r[e]]}return he(`RESOLVE: Property access '${e}' =`,s),s}}return e}async function lr(e,t){he("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,s]=r;he("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:s});const i=await or(e.trim(),t);if(he("EVAL: Ternary condition value:",i),i){const e=await or(n.trim(),t);return he("EVAL: Ternary returned true branch:",e),e}{const e=await or(s.trim(),t);return he("EVAL: Ternary returned false branch:",e),e}}const n=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,e,r,s]=n;he("EVAL: Parsed arithmetic:",{left:e,operator:r,right:s});const i=await or(e.trim(),t),a=await or(s.trim(),t);he("EVAL: Resolved values:",{leftValue:i,rightValue:a});const o=Number(i),l=Number(a);if(!isNaN(o)&&!isNaN(l)){let e;switch(r){case"+":e=o+l;break;case"-":e=o-l;break;case"*":e=o*l;break;case"/":e=o/l;break;case"%":e=o%l;break;default:e=o}return he("EVAL: Arithmetic result:",e),e}}const s=await or(e.trim(),t);return he("EVAL: Fallback result:",s),s}function cr(e){if(Array.isArray(e)&&1===e.length&&(e=e[0]),null!==e&&"object"==typeof e&&"string"==typeof e.textContent){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?e:r}return 0}return e}async function ur(e,t,r,n,s){try{const i=s(await n(e.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const a=nr(e.property);if(!a||"string"!=typeof a)throw Error("Invalid method name: "+a);const o=i[a];if("function"!=typeof o)throw Error(`Property "${a}" is not a function on ${i.constructor?.name||typeof i}`);const l=await Promise.all(t.map(e=>n(e,r)));return o.apply(i,l)}catch(e){if(e instanceof Error)throw e;throw Error("Failed to evaluate method call: "+e)}}class dr{constructor(){this.expressionRegistry=new Map}registerCategory(e){Object.entries(e).forEach(([e,t])=>{this.expressionRegistry.set(e,t)})}unwrapSelectorResult(e){if(e instanceof NodeList&&e.length>0)return e[0];if(Array.isArray(e)&&e.length>0){const t=e[0];return"index"in e&&"input"in e?e:t instanceof Element||t instanceof Node?t:e}return e}async evaluate(e,t){if(!e)return he("EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));switch(e.type){case"identifier":return this.evaluateIdentifier(e,t);case"literal":return this.evaluateLiteral(e,t);case"string":return e.value??"";case"memberExpression":return this.evaluateMemberExpression(e,t);case"binaryExpression":return this.evaluateBinaryExpression(e,t);case"unaryExpression":return this.evaluateUnaryExpression(e,t);case"callExpression":return this.evaluateCallExpression(e,t);case"selector":return this.evaluateSelector(e,t);case"dollarExpression":return this.evaluateDollarExpression(e,t);case"possessiveExpression":return this.evaluatePossessiveExpression(e,t);case"templateLiteral":return this.evaluateTemplateLiteral(e,t);case"arrayLiteral":return this.evaluateArrayLiteral(e,t);case"objectLiteral":return this.evaluateObjectLiteral(e,t);case"conditionalExpression":return this.evaluateConditionalExpression(e,t);case"cssSelector":return this.evaluateCSSSelector(e,t);case"propertyAccess":return this.evaluatePropertyAccess(e,t);case"propertyOfExpression":return this.evaluatePropertyOfExpression(e,t);case"contextReference":return this.evaluateContextReference(e,t);case"queryReference":return this.evaluateQueryReference(e,t);case"idSelector":return this.evaluateIdSelector(e,t);case"attributeAccess":return this.evaluateAttributeAccess(e,t);case"asExpression":return this.evaluateAsExpression(e,t);default:throw Error("Unsupported AST node type for evaluation: "+e.type)}}async evaluateWithResult(e,t){try{return _t(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return Mt({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return Mt({type:"exit",returnValue:t.returnValue});if(t.isBreak)return Mt({type:"break"});if(t.isContinue)return Mt({type:"continue"});if(t.isReturn)return Mt({type:"return",returnValue:t.returnValue})}throw e}}async evaluateArrayLiteral(e,t){const r=e.elements||[],n=[];for(const e of r){const r=await this.evaluate(e,t);n.push(r)}return n}async evaluateObjectLiteral(e,t){const r=e.properties||[],n={};for(const e of r){let r;r="identifier"===e.key.type?e.key.name:"literal"===e.key.type?e.key.value+"":await this.evaluate(e.key,t)+"";const s=await this.evaluate(e.value,t);n[r]=s}return n}async evaluateConditionalExpression(e,t){return await this.evaluate(e.test,t)?this.evaluate(e.consequent,t):e.alternate?this.evaluate(e.alternate,t):void 0}async evaluateTemplateLiteral(e,t){return async function(e,t){let r=e.value||"";he("TEMPLATE LITERAL: Evaluating",{template:r,node:e});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,s=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&s.push({match:i[0],varName:i[1],index:i.index});for(let e=s.length-1;e>=0;e--){const{match:n,varName:i,index:a}=s[e],o=await ar(i,t);he(`TEMPLATE: $${i} resolved to`,o),r=r.slice(0,a)+((o??"")+"")+r.slice(a+n.length)}let a="",o=0;for(;r.length>o;){const e=r.indexOf("${",o);if(-1===e){a+=r.slice(o);break}a+=r.slice(o,e);let n=1,s=e+2;for(;r.length>s&&n>0;)"{"===r[s]&&n++,"}"===r[s]&&n--,n>0&&s++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(e+2,s);let l;he("TEMPLATE: Evaluating expression:",i);const c=i.trim();t.locals.has(c)?(l=t.locals.get(c),he(`TEMPLATE: Found in locals: ${c} =`,l)):t.globals&&t.globals.has(c)?(l=t.globals.get(c),he(`TEMPLATE: Found in globals: ${c} =`,l)):t.variables&&t.variables.has(c)?(l=t.variables.get(c),he(`TEMPLATE: Found in variables (legacy): ${c} =`,l)):(l=await lr(i,t),he(`TEMPLATE: Evaluated expression "${i}" =`,l)),a+=l+"",o=s+1}return a}(e,t)}async evaluateSimpleExpression(e,t){return lr(e,t)}async resolveValue(e,t){return or(e,t)}async evaluateIdentifier(e,t){const{name:r,scope:n}=e;if("me"===r||"my"===r||"I"===r)return t.me;if("you"===r||"your"===r)return t.you;if("it"===r||"its"===r)return t.it;if("result"===r)return t.result;if("event"===r)return t.event;const s=this.expressionRegistry.get(r);return s?s.evaluate(t):"local"===n?t.locals?.has(r)?t.locals.get(r):void 0:"global"===n?t.globals?.has(r)?t.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:t.locals?.has(r)?t.locals.get(r):t.globals?.has(r)?t.globals.get(r):t.variables?.has(r)?t.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(e,t){return e.value}async evaluateContextReference(e,t){const{contextType:r}=e;switch(r){case"me":return t.me;case"it":return t.result;case"you":return t.you;case"event":return t.event;case"body":return t.meta?.ownerDocument?.body||document?.body;case"detail":return t.event?.detail;case"target":return t.you||t.event?.target;case"sender":return t.event?.target;default:return t.locals&&t.locals.has(r)?t.locals.get(r):void he("Unknown context reference type: "+r)}}async evaluateMemberExpression(e,t){const{object:r,property:n,computed:s}=e;if("identifier"===r.type&&["add","remove"].includes(r.name)){const e=r.name,s=nr(n);if(!t.me)throw Error('Context element "me" is null');return void("add"===e?t.me.classList.add(s):"remove"===e&&t.me.classList.remove(s))}let i=await this.evaluate(r,t);if(s)return i[await this.evaluate(n,t)];{const e=nr(n);if(Array.isArray(i)&&"string"==typeof e&&("length"===e||e in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof e){if(e.startsWith("computed-")){const t=e.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(t):void 0}if(e.startsWith("@")){const t=e.substring(1);return i&&"function"==typeof i.getAttribute?er(i,t):void 0}if(i&&i instanceof Element){if("previous"===e||"prev"===e)return i.previousElementSibling;if("next"===e)return i.nextElementSibling}}const t=i?.[e];return"function"==typeof t?t.bind(i):t}}coerceArithmeticOperand(e){return cr(e)}async evaluateBinaryExpression(e,t){return async function(e,t,r,n,s){const{operator:i,left:a,right:o}=e;if("in"===i&&"selector"===a.type){let e=a.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const s=n(await r(o,t));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(e);return Array.from(i)}if("in"===i&&"queryReference"===a.type){let e=a.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const s=n(await r(o,t));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(e);return Array.from(i)}if("in"===i){let e=null,s=null;if("positionalExpression"===a.type){e=a.operator;const n=a.argument;"cssSelector"===n?.type?s=n.selector:"selector"===n?.type?s=n.value:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,t)+"")}else if("memberExpression"!==a.type||"identifier"!==a.object?.type||"first"!==a.object.name&&"last"!==a.object.name){if("callExpression"===a.type&&"identifier"===a.callee?.type&&("first"===a.callee.name||"last"===a.callee.name)){e=a.callee.name;const n=a.arguments?.[0];"selector"===n?.type?s=n.value:"cssSelector"===n?.type?s=n.selector:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,t)+"")}}else e=a.object.name,"identifier"===a.property?.type&&a.property.name&&(s="."+a.property.name);if(e&&s){const i=n(await r(o,t));if(!i||"function"!=typeof i.querySelectorAll)return;const a=i.querySelectorAll(s),l=Array.from(a);return"first"===e?l.length>0?l[0]:void 0:"last"===e?l.length>0?l[l.length-1]:void 0:l}}if("matches"===i&&("selector"===o.type||"cssSelector"===o.type||"classSelector"===o.type)){const e=await r(a,t),n=o.value||o.selector;if(e&&"function"==typeof e.matches)try{return e.matches(n)}catch{return!1}return!1}const l=await r(a,t),c=await r(o,t);if("has"===i||"have"===i){if(l instanceof Element){if("cssSelector"===o.type&&"class"===o.selectorType||"selector"===o.type&&o.value?.startsWith(".")){const e=o.selector?.slice(1)||o.value?.slice(1)||"";return l.classList.contains(e)}if("attributeAccess"===o.type||"attributeRef"===o.type){const e=o.attributeName||o.name||o.value?.replace(/^@/,"")||"";return l.hasAttribute(e)}if("cssSelector"===o.type&&"attribute"===o.selectorType){const e=(o.selector||o.value||"").replace(/^@/,"");return l.hasAttribute(e)}if("cssSelector"===o.type&&"id"===o.selectorType||"idSelector"===o.type){const e=(o.selector||o.value||"").replace(/^#/,"");return null!==l.querySelector("#"+CSS.escape(e))}if("selector"===o.type||"queryReference"===o.type){let e=o.value||o.selector||"";e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());try{return null!==l.querySelector(e)}catch{return!1}}if("cssSelector"===o.type){const e=o.selector||"";try{return null!==l.querySelector(e)}catch{return!1}}}return Array.isArray(l)?l.includes(c):"string"==typeof l&&l.includes(c+"")}switch(i){case">":case"is greater than":return l>c;case"<":case"is less than":return c>l;case">=":case"is greater than or equal to":return l>=c;case"<=":case"is less than or equal to":return c>=l;case"==":case"equals":case"is equal to":return l==c;case"===":case"is really equal to":case"really equals":return l===c;case"!=":case"is not equal to":return l!=c;case"!==":case"is not really equal to":return l!==c;case"+":{const e=cr(l),r=cr(c);if("string"==typeof e||"string"==typeof r){const n=s.get("stringConcatenation");if(n){he("Using string concatenation for:",{leftValue:e,rightValue:r});const s=await n.evaluate(t,{left:e,right:r});return s.success?s.value:e+r}}else{const n=s.get("addition");if(n){he("Using numeric addition for:",{leftValue:e,rightValue:r});const s=await n.evaluate(t,{left:e,right:r});return s.success?s.value:e+r}}return e+r}case"-":return cr(l)-cr(c);case"*":return cr(l)*cr(c);case"/":return cr(l)/cr(c);case"%":case"mod":return cr(l)%cr(c);case"as":const e="string"==typeof c?c:"identifier"===o.type?o.name:"literal"===o.type?o.value:c+"",r=s.get("as");return r?r.evaluate(t,l,e):l;case"&&":case"and":return l&&c;case"||":case"or":return l||c;case"is":return l===c;case"is not":return l!==c;case"is a":case"is an":switch("identifier"===o.type?o.name.toLowerCase():(c+"").toLowerCase()){case"string":return"string"==typeof l;case"number":return"number"==typeof l;case"boolean":return"boolean"==typeof l;case"object":return"object"==typeof l&&null!==l;case"array":return Array.isArray(l);case"function":return"function"==typeof l;case"null":return null===l;case"undefined":return void 0===l;default:const e="identifier"===o.type?o.name:c+"";return null!=l&&l.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===o.type?o.name.toLowerCase():(c+"").toLowerCase()){case"string":return"string"!=typeof l;case"number":return"number"!=typeof l;case"boolean":return"boolean"!=typeof l;case"object":return!("object"==typeof l&&null!==l);case"array":return!Array.isArray(l);case"function":return"function"!=typeof l;case"null":return null!==l;case"undefined":return void 0!==l;default:const e="identifier"===o.type?o.name:c+"";return!(null!=l&&l.constructor?.name===e)}case"=":if("identifier"===a.type){const e=a.name;return"result"===e?t.result=c:"it"===e?t.it=c:"you"===e?t.you=c:t.locals.set(e,c),c}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(l)?l.includes(c):"string"==typeof l?l.includes(c+""):!(!l||"function"!=typeof l.matches)&&l.matches(c+"");case"match":case"matches":if(l&&"function"==typeof l.matches){const e="string"==typeof c?c:c+"";try{return l.matches(e)}catch{return!1}}return!1;case"in":const n="string"==typeof l?l:l+"",u=c;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(l);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof l&&"string"==typeof c?{command:l,selector:c}:"identifier"===a.type&&"selector"===o.type?{command:a.name,selector:o.value}:c;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(e,t){const{operator:r,argument:n}=e,s=await this.evaluate(n,t);switch(r){case"not":case"!":const e=this.expressionRegistry.get("not");return e?e.evaluate(t,s):!s;case"no":const n=this.expressionRegistry.get("no");return!!n&&n.evaluate(t,s);case"some":return null!=s&&("string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"!=typeof s||Object.keys(s).length>0);case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(t,s):null!=s;case"does not exist":const a=this.expressionRegistry.get("doesNotExist");return a?a.evaluate(t,s):null==s;case"-":return-s;case"+":return+s;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(e,t){return async function(e,t,r,n,s,i){const{callee:a,arguments:o,isConstructor:l}=e;if(l){const e=a.name,n=t.globals?.get(e)||window[e];if("function"==typeof n)return new n(...await Promise.all(o.map(e=>r(e,t))));throw Error("Unknown constructor: "+e)}if("memberExpression"===a.type||"propertyAccess"===a.type)return ur(a,o,t,r,n);const c=a.name||a,u=s.get(c);if(u){const e=["first","last","random","at"],n=["closest","previous","next"].includes(c),s=e.includes(c),a=await Promise.all(o.map(e=>n&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:n&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:s&&e&&"selector"===e.type&&"string"==typeof e.value?i(e,t):r(e,t)));return u.evaluate(t,...a)}const d=t.globals?.get(c)||window[c];if("function"==typeof d)return d(...await Promise.all(o.map(e=>r(e,t))));throw Error("Unknown function: "+c)}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(e,t,r){return ur(e,t,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(e,t){return function(e,t){let r=e.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(t);if(!n)return[];const s=n.querySelectorAll(r);return Array.from(s).filter(e=>e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.tagName)}(e,t)}evaluateAttributeAccess(e,t){return t.me&&"function"==typeof t.me.getAttribute?er(t.me,e.attributeName):"@"+e.attributeName}async evaluateAsExpression(e,t){const r=await this.evaluate(e.expression,t),n=this.expressionRegistry.get("as");if(n)return n.evaluate(t,r,e.targetType);throw Error("Conversion type 'as' not registered")}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(e,t){const r=await this.evaluate(e.expression,t);if("identifier"===e.expression.type){const r=e.expression.name;return/^\d+$/.test(r)?r:t.locals?.has(r)?t.locals.get(r):"me"===r&&t.me?t.me:"you"===r&&t.you?t.you:"it"===r&&t.it?t.it:"result"===r&&t.result?t.result:"undefined"!=typeof window&&"window"===r?window:t.globals?.has(r)?t.globals.get(r):void 0}return r}async evaluatePossessiveExpression(e,t){const{object:r,property:n}=e,s=this.unwrapSelectorResult(await this.evaluate(r,t));if(!s)return;const i=nr(n);return"string"==typeof i&&Xt(s)?rr(s,i):s[i]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){return function(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(t);if(!n)return"id"===e.selectorType?null:[];if("id"===e.selectorType){const e=r.startsWith("#")?r.slice(1):r;return n.getElementById(e)}if("class"===e.selectorType){const e=r.replace(/:/g,"\\:"),t=n.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const s=n.querySelectorAll(r);return Array.from(s).filter(e=>e instanceof HTMLElement)}(e,t)}async evaluateIdSelector(e,t){return function(e,t){const r=sr(t);if(!r)return null;const n=e.value.startsWith("#")?e.value.slice(1):e.value;return r.getElementById(n)}(e,t)}async evaluateQueryReference(e,t){return function(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(t);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(e,t)}async evaluatePropertyAccess(e,t){const r=await this.evaluate(e.object,t),n=e.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const s=n.name||n.value;if(!s)throw Error("Property name must be an identifier");try{let e;return e=Xt(r)?rr(r,s):r[s],"function"==typeof e?e.bind(r):e}catch(e){throw Error(`Error accessing property "${s}": ${e}`)}}async evaluatePropertyOfExpression(e,t){const r=e.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const s=this.unwrapSelectorResult(await this.evaluate(e.target,t));if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);try{let e;return e=Xt(s)?rr(s,n):s[n],"function"==typeof e?e.bind(s):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const mr={1:"one",2:"two",3:"three",4:"four",5:"five"};function pr(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${s=t,mr[s]??s+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var s;return null}function hr(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function fr(e,t,r){return pr(e,1,t,r)??hr(e,0,t,r)}function yr(e,t){return pr(e,2,t,"left, right")}function gr(){return null}function vr(e,t,r,n){return e.length>t?`${r} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${n?` (${n})`:""}`:null}function br(e,t,r,n,s){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${s?` (${s})`:""}`:null}function wr(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const kr="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 Er;function xr(){return Er({validate:e=>({success:!0,data:e})})}function Cr(e,t){if(kr)return xr();const r=Er({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:wr("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(t?.strict){const t=Object.keys(e),r=Object.keys(n).filter(e=>!t.includes(e));if(r.length>0)return{success:!1,error:wr("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=n[t];if(!(t in n)&&!r._isOptional)return{success:!1,error:wr("missing-argument",`Required field "${t}" is missing`,t)};const i=r.validate(e);if(!i.success)return{success:!1,error:wr("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 r.strict=()=>Cr(e,{strict:!0}),r}Er=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,_isOptional:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return Er(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&e>n.data.length?{success:!1,error:wr("runtime-error",`String must be at least ${e} characters long`)}:n}};return Er(r)}),e.max||(e.max=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&n.data.length>e?{success:!1,error:wr("runtime-error",`String must be at most ${e} characters long`)}:n}};return Er(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,_defaultValue:e,_hasDefault:!0,validate:r=>void 0===r?{success:!0,data:e}:t(r)};return Er(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?e(s.data)?s:{success:!1,error:wr("runtime-error",t||"Refinement validation failed")}:s}};return Er(n)}),new Proxy(e,{get:(e,t,r)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,r):function(...e){return r}})};const Ar=e=>function(e={}){return kr?xr():Er({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:wr("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:wr("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:wr("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:wr("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:wr("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),Sr=e=>function(e={}){return kr?xr():Er({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:wr("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:wr("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:wr("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{}),Tr=()=>kr?xr():Er({validate:e=>"boolean"!=typeof e?{success:!1,error:wr("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),Lr=e=>Cr(e),Or=e=>function(e){return kr?xr():Er({validate:t=>{if(!Array.isArray(t))return{success:!1,error:wr("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:wr("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const r=[];for(let n=0;e.length>n;n++){const s=e[n].validate(t[n]);if(!s.success)return{success:!1,error:wr("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(e),Pr=()=>xr(),Nr=()=>xr(),Ir=()=>function(e,t="Custom validation failed"){return kr?xr():Er({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:wr("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class jr{trackPerformance(e,t,r,n){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(e,t,r,n=(r?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:t,duration:Date.now()-t,success:r})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||Jt(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,r,n,s=[]){return{success:!1,error:{name:e,type:t,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!==e&&"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":Zt(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":Wt(e)?"String":Jt(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):Wt(e)?e.split(""):null==e?[]:Zt(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Jt(e)&&Number.isFinite(e))return e;if(Wt(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Kt(e)?e?1:0:null}}class Rr extends jr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Ir(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}}class qr extends jr{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=Ir(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}}class _r extends jr{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=Ir(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.it,s={success:!0,value:n,type:this.inferType(n)};return this.trackPerformance(e,t,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}}const Mr=Lr({selector:Ar().min(1),single:Tr().optional().default(!1)});class $r extends jr{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=Mr,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const r=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,n,r),n}let n;if(t.single)n=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));n=e.length>0?e:null}const s={success:!0,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(e,t,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=t.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}}new Rr,new qr,new _r,new $r;const Vr={name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:gr},Dr={name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:gr},Br={name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:gr},Fr={name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:gr},zr={name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:gr},Hr={name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:e=>fr(e,"querySelector","selector")},Ur={name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>fr(e,"querySelectorAll","selector")},Wr={name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:e=>fr(e,"getElementById","ID")},Jr={name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:e=>fr(e,"getElementsByClassName","className")},Kr={name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let r=t[0];if(r&&"object"==typeof r&&"type"in r){const e=r;"identifier"===e.type&&e.name?r=e.name:"literal"===e.type&&"string"==typeof e.value&&(r=e.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return e.me?e.me.closest(r):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},Zr={name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:gr},Yr={name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:gr},Gr={name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:gr},Xr={name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>fr(e,"elementWithSelector","selector")},Qr={name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||e.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(r)||void 0}},validate:e=>br(e,1,2,"styleRef","property, optional element")??hr(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},en={name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===r&&e.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=>pr(e,2,"possessiveStyleRef","possessor, property")??hr(e,0,"possessiveStyleRef","possessor")??hr(e,1,"possessiveStyleRef","property")},tn={name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===n&&e.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=>pr(e,2,"ofStyleRef","property, reference")??hr(e,0,"ofStyleRef","property")??hr(e,1,"ofStyleRef","reference")},rn={me:Vr,you:Dr,it:Br,its:Fr,result:zr,querySelector:Hr,querySelectorAll:Ur,getElementById:Wr,getElementsByClassName:Jr,closest:Kr,parent:Zr,window:Yr,document:Gr,elementWithSelector:Xr,styleRef:Qr,possessiveStyleRef:en,ofStyleRef:tn};var nn=Object.freeze({__proto__:null,CSSSelectorExpression:$r,ItExpression:_r,MeExpression:Rr,YouExpression:qr,classExpression:Jr,closestExpression:Kr,createItExpression:function(){return new _r},createMeExpression:function(){return new Rr},createYouExpression:function(){return new qr},documentExpression:Gr,elementWithSelectorExpression:Xr,idExpression:Wr,itExpression:Br,itsExpression:Fr,meExpression:Vr,ofStyleRefExpression:tn,parentExpression:Zr,possessiveStyleRefExpression:en,querySelectorAllExpression:Ur,querySelectorExpression:Hr,referencesExpressions:rn,resultExpression:zr,styleRefExpression:Qr,windowExpression:Yr,youExpression:Dr});class sn{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.timestamp<=this.ttl)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU();const r={result:t,timestamp:Date.now(),accessCount:1};this.cache.set(e,r),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[r,n]of this.accessOrder)t>n&&(t=n,e=r);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,r)=>e+(t-r.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const an=new class{constructor(){this.domQueryCache=new sn(200,3e3),this.exprResultCache=new sn(500,2e3),this.cssMatchCache=new sn(100,5e3),this.formValueCache=new sn(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(e);return this.domQueryCache.set(t,n),n}querySelectorAll(e){const t="querySelectorAll:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,n),n}getElementById(e){const t="getElementById:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(e);return this.domQueryCache.set(t,n),n}getElementsByClassName(e){const t="getElementsByClassName:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,n),n}matches(e,t){const r=`matches:${this.getElementCacheKey(e)}:${t}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(r,s),s}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),r=this.formValueCache.get("formValue:"+t);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(e,t){const r=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+r,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(e.cache.keys()))"string"==typeof r&&r.includes(t)&&e.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),r=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${r}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([r,n])=>{e-n.timestamp>t.ttl&&t.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{an.cleanup()},1e4);const on=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const r=performance.now()-t;return this.startTimes.delete(e),r}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=an.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 ln(){an.cleanup(),on.getMetrics().memoryUsage>52428800&&on.reset()}let cn=null;function un(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const r=e.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${t} cannot be converted to number: "${e}"`);return n}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const r=e[0];if(Array.isArray(r))throw Error(t+" is a nested array, cannot convert to number");return un(r,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 r=parseFloat(e);if(!isNaN(r))return r}}const r=e.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function dn(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?null:r}return"boolean"==typeof e?e?1:0:null==e?0:null}function mn(e,t,r){if("==="===r)return e===t;if("!=="===r)return e!==t;if(null==e||null==t)return function(e,t,r){if(null==e&&null==t)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,r);const[n,s]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const r=parseFloat(e),n=parseFloat(t);return isNaN(r)||isNaN(n)?[e,t]:[r,n]}const r=dn(e),n=dn(t);return null!==r&&null!==n?[r,n]:[e+"",t+""]}(e,t);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return pn(e,t);case"!=":return!pn(e,t);default:return!1}}function pn(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 r=parseFloat(t);return!isNaN(r)&&e===r}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);return!isNaN(r)&&r===t}return"boolean"==typeof e?pn(e?1:0,t):"boolean"==typeof t?pn(e,t?1:0):e+""==t+""}function hn(e,t,r,n,s,i=!0,a){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==a&&{error:a}}),n}"undefined"!=typeof window&&function(e=3e4){cn&&clearInterval(cn),cn=setInterval(ln,e)}();const fn=Lr({left:Pr().describe("Left operand value"),right:Pr().describe("Right operand value")}).strict(),yn=Lr({operand:Pr().describe("Operand value to negate")}).strict();class gn extends jr{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=fn,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),a=s&&i;return this.trackSimple(e,r,!0,"boolean"),this.success(a,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class vn extends jr{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=fn,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),a=s||i;return this.trackSimple(e,r,!0,"boolean"),this.success(a,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class bn extends jr{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=yn,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function wn(){return new gn}function kn(){return new vn}function En(){return new bn}function xn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}wn(),kn(),En();const Cn=Or([Pr(),Pr()]),An=Or([Pr(),Ar()]),Sn={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return hn(this,e,[t,r],t==r,n)}catch(s){throw hn(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>yr(e,"equals"),inputSchema:Cn,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"]}},Tn={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=t===r;return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"strictEquals")},Ln={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=t!=r;return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"notEquals")},On={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=t!==r;return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"strictNotEquals")},Pn={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=mn(t,r,"<");return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"lessThan")},Nn={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=mn(t,r,"<=");return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"lessThanOrEqual")},In={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=mn(t,r,">");return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"greaterThan")},jn={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=mn(t,r,">=");return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"greaterThanOrEqual")},Rn={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return hn(this,e,[t,r],t&&r,n)}catch(s){throw hn(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>yr(e,"and"),inputSchema:Cn,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"]}},qn={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=t||r;return n&&hn(this,e,[t,r],i,s),i},validate:e=>yr(e,"or")},_n={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,s=!t;return r&&hn(this,e,[t],s,n),s},validate:e=>pr(e,1,"not","operand")},Mn={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let s;return s=null==t||(Wt(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Zt(t)||0!==Object.keys(t).length)),r&&hn(this,e,[t],s,n),s},validate:e=>pr(e,1,"isEmpty","value")},$n={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let s;return s=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!(Wt(t)||t instanceof Node||t instanceof Element||!Zt(t)||0!==Object.keys(t).length)),r&&hn(this,e,[t],s,n),s},validate:e=>pr(e,1,"no","value")},Vn={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,s=!await Mn.evaluate(e,t);return r&&hn(this,e,[t],s,n),s},validate:e=>pr(e,1,"isNotEmpty","value")},Dn={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,s=null!=t;return r&&hn(this,e,[t],s,n),s},validate:e=>pr(e,1,"exists","value")},Bn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,s=null==t;return r&&hn(this,e,[t],s,n),s},validate:e=>pr(e,1,"doesNotExist","value")},Fn={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0;let i;if(t&&r){if(xn(t)&&xn(r))return i=t.contains(r),n&&hn(this,e,[t,r],i,s),i;if(Wt(t)&&t.match(/^[.#][\w-]+$/)){const a=document.querySelector(t);if(a&&xn(r))return i=a.contains(r),n&&hn(this,e,[t,r],i,s),i;if(a&&Wt(r)&&r.match(/^[.#][\w-]+$/)){const o=document.querySelector(r);return i=!!o&&a.contains(o),n&&hn(this,e,[t,r],i,s),i}}if(Wt(r)&&r.match(/^[.#][\w-]+$/)&&xn(t)){const a=document.querySelector(r);return i=!!a&&t.contains(a),n&&hn(this,e,[t,r],i,s),i}}return i=Wt(t)&&Wt(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!Zt(t)||!Wt(r))&&r in t,n&&hn(this,e,[t,r],i,s),i},validate:e=>pr(e,2,"contains","container, value")},zn={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!await Fn.evaluate(e,t,r);return n&&hn(this,e,[t,r],i,s),i},validate:e=>pr(e,2,"doesNotContain","container, value")},Hn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!(!Wt(t)||!Wt(r))&&t.startsWith(r);return n&&hn(this,e,[t,r],i,s),i},validate:e=>pr(e,2,"startsWith","str, prefix")},Un={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!(!Wt(t)||!Wt(r))&&t.endsWith(r);return n&&hn(this,e,[t,r],i,s),i},validate:e=>pr(e,2,"endsWith","str, suffix")},Wn={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let s;if(t instanceof Element&&Wt(r)){const e=r;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{s=function(e,t){return an.matches(e,t)}(t,e)}catch(e){s=!1}else s=!1}else if(Wt(t)&&Wt(r)){const e=t,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(e)}catch(t){s=e.includes(n)}}else s=!1;return hn(this,e,[t,r],s,n)}catch(s){throw hn(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>pr(e,2,"matches","element, selector"),inputSchema:An,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"]}},Jn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0;let i=!1;if(t instanceof Element&&Wt(r)){const e=r;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return n&&hn(this,e,[t,r],i,s),i},validate:e=>pr(e,2,"has","element, selector")},Kn={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!await Jn.evaluate(e,t,r);return n&&hn(this,e,[t,r],i,s),i},validate:e=>pr(e,2,"doesNotHave","element, selector")},Zn={equals:Sn,strictEquals:Tn,notEquals:Ln,strictNotEquals:On,lessThan:Pn,lessThanOrEqual:Nn,greaterThan:In,greaterThanOrEqual:jn,and:Rn,or:qn,not:_n,no:$n,isEmpty:Mn,isNotEmpty:Vn,exists:Dn,doesNotExist:Bn,contains:Fn,doesNotContain:zn,startsWith:Hn,endsWith:Un,matches:Wn,has:Jn,doesNotHave:Kn};var Yn=Object.freeze({__proto__:null,AndExpression:gn,NotExpression:bn,OrExpression:vn,andExpression:Rn,containsExpression:Fn,createAndExpression:wn,createNotExpression:En,createOrExpression:kn,doesNotContainExpression:zn,doesNotExistExpression:Bn,doesNotHaveExpression:Kn,endsWithExpression:Un,equalsExpression:Sn,existsExpression:Dn,greaterThanExpression:In,greaterThanOrEqualExpression:jn,hasExpression:Jn,isEmptyExpression:Mn,isNotEmptyExpression:Vn,lessThanExpression:Pn,lessThanOrEqualExpression:Nn,logicalExpressions:Zn,matchesExpression:Wn,noExpression:$n,notEqualsExpression:Ln,notExpression:_n,orExpression:qn,startsWithExpression:Hn,strictEqualsExpression:Tn,strictNotEqualsExpression:On});function Gn(e,t,r,n,s="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:s,message:r,code:t,suggestions:n}}}function Xn(e,t){return{success:!0,value:e,type:t}}function Qn(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const es={Array:(e,t)=>{try{return Array.isArray(e)?Xn(e,"array"):e instanceof NodeList?Xn(Array.from(e),"array"):Xn(null==e?[]:[e],"array")}catch(e){return Gn("Array","ARRAY_CONVERSION_FAILED",Qn("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?Xn("","string"):Wt(e)?Xn(e,"string"):Zt(e)?Xn(JSON.stringify(e),"string"):Xn(e+"","string")}catch(e){return Gn("String","STRING_CONVERSION_FAILED",Qn("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 Xn(e,"boolean");if(null==e)return Xn(!1,"boolean");if(Wt(e)){const t=e.toLowerCase().trim();return Xn("false"!==t&&"0"!==t&&""!==t,"boolean")}return Jt(e)?Xn(0!==e&&!isNaN(e),"boolean"):Xn(!!e,"boolean")}catch(e){return Gn("Boolean","BOOLEAN_CONVERSION_FAILED",Qn("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Jt(e))return Xn(e,"number");if(null==e)return Xn(0,"number");const t=Number(e);return isNaN(t)?Gn("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Xn(t,"number")}catch(e){return Gn("Number","NUMBER_CONVERSION_FAILED",Qn("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=es.Number(e,t);return r.success?Xn(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=es.Number(e,t);return r.success?Xn(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return Xn(e,"object");if(null==e)return Xn(new Date(""),"object");if(Wt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return Xn(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?Gn("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"):Xn(t,"object")}catch(e){return Gn("Date","DATE_CONVERSION_FAILED",Qn("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return Xn(JSON.stringify(e),"string")}catch(e){return Gn("JSON","JSON_STRINGIFY_FAILED",Qn("Failed to convert value to JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(Zt(e))return Xn(e,"object");if(Wt(e))try{return Xn(JSON.parse(e),"object")}catch(e){return Gn("Object","JSON_PARSE_FAILED",Qn("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Xn({},"object")}catch(e){return Gn("Object","OBJECT_CONVERSION_FAILED",Qn("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 Xn(is(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{const t=e;if(t.name){const e=as(t);void 0!==e&&(r[t.name]=e)}}),Xn(r,"object")}return Xn({},"object")}catch(e){return Gn("FormValues","FORM_VALUES_EXTRACTION_FAILED",Qn("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},ts=Lr({value:Nr(),type:Ar().min(1)});class rs extends jr{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=ts,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=t;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),a=n?parseInt(n[1],10):2,o=es.Number(s,e);if(!o.success)return o;const l={success:!0,value:o.value.toFixed(a),type:"string"};return this.trackPerformance(e,t,l,r),l}let a=es[i];if(a){const n=a(s,e);return this.trackPerformance(e,t,n,r),n}const o={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[i.toLowerCase()];if(o&&(a=es[o],a)){const n=a(s,e);return this.trackPerformance(e,t,n,r),n}const l={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,l,r),l}catch(n){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}}const ns=Lr({value:Nr(),type:Ar().min(1)});new rs,new class extends jr{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=ns,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=t,a=i.toLowerCase();let o;switch(a){case"null":o=null===s;break;case"undefined":o=void 0===s;break;case"string":o=Wt(s);break;case"number":o=Jt(s)&&!isNaN(s);break;case"boolean":o=Kt(s);break;case"object":o=Zt(s);break;case"array":o=Array.isArray(s);break;case"function":o=Yt(s);break;case"date":o=s instanceof Date;break;case"element":o=s instanceof Element;break;case"node":o=s instanceof Node;break;case"node-list":o=s instanceof NodeList;break;case"empty":o=null==s||""===s||Array.isArray(s)&&0===s.length||Zt(s)&&0===Object.keys(s).length;break;default:o=s?.constructor?.name?.toLowerCase()===a}const l=this.success(o,"boolean");return this.trackPerformance(e,t,l,r),l}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const ss={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Wt(e)?e:Zt(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Kt(e))return e;if(null==e)return!1;if(Wt(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Jt(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(Jt(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Jt(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(!Jt(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=ss.Number(e);return Math.trunc(t)},Float:e=>{const t=ss.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Wt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)}return new Date(e)},JSON:e=>{try{return JSON.stringify(e)}catch(e){return"{}"}},Object:e=>{if(Zt(e))return e;if(Wt(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{Wt(e)||(e=ss.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>Wt(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:ss.String(e)).join(""):e instanceof Element?e.outerHTML:ss.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return is(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=as(e))}),r}return{}},"Values:Form":(e,t)=>{const r=ss.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=ss.Values(e,t);return JSON.stringify(r)}};function is(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=as(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}function as(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}function os(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}const ls={name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:e}=os(n);return ss.Number(r).toFixed(e||2)}let s=ss[n];if(s)return s(r,e);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(s=ss[i],s)?s(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>pr(e,2,"as","value, type")??hr(e,1,"as","conversion type")},cs={name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!Wt(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return Wt(r);case"number":return Jt(r)&&!isNaN(r);case"boolean":return Kt(r);case"object":return Zt(r);case"array":return Array.isArray(r);case"function":return Yt(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||Zt(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>pr(e,2,"is","value, type")??hr(e,1,"is","type")},us={name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>pr(e,1,"async","expression")},ds={as:ls,is:cs,async:us};var ms=Object.freeze({__proto__:null,AsExpression:rs,asExpression:ls,asyncExpression:us,conversionExpressions:ds,createAsExpression:function(){return new rs},defaultConversions:ss,getFormValues:function(e){const t=new FormData(e),r={};for(const[e,n]of t.entries())void 0!==r[e]?(Array.isArray(r[e])||(r[e]=[r[e]]),r[e].push(n)):r[e]=n;return r},getFormValuesProcessed:is,getInputValue:as,isExpression:cs,parseFixedPrecision:os});const ps={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"},hs=Lr({collection:Pr().describe("Collection to operate on (array, NodeList, or string)")}).strict(),fs=Lr({collection:Pr().describe("Collection to access"),index:Sr().describe("Index position to access")}).strict(),ys=Lr({collection:Pr().describe("Collection to select random item from")}).strict();class gs extends jr{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=hs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,a={success:!0,value:i,type:ps[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class vs extends jr{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=hs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,a={success:!0,value:i,type:ps[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function bs(){return new gs}function ws(){return new vs}bs(),ws(),new class extends jr{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=fs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=this.normalizeIndex(t.index,s.length),a=i>=0&&s.length>i?s[i]:void 0,o={success:!0,value:a,type:ps[this.inferEvaluationType(a)]};return this.trackPerformance(e,t,o,r),o}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid at input: "+e.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return 0>e?t+e:e}},new class extends jr{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 r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],a={success:!0,value:i,type:ps[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid random input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}};const ks={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const r=void 0!==t?t:e.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:Wt(r)?r.length>0?r[0]:null:Zt(r)&&"length"in r&&Jt(r.length)&&r.length>0?r[0]:null},validate:e=>vr(e,1,"first","collection")},Es={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const e=r.children;return e.length>0?e[e.length-1]:null}return Wt(r)?r.length>0?r[r.length-1]:null:Zt(r)&&"length"in r&&Jt(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>vr(e,1,"last","collection")},xs={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!Jt(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>s?e.length+s:s;return t>=0&&e.length>t?e[t]:null}if(Wt(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(Zt(i)&&"length"in i&&Jt(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>br(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)},Cs={name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[r,n]=t,s=n||e.me;return s&&s instanceof Element?r?Ss(s,r):s.nextElementSibling:null},validate:e=>vr(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")},As={name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[r,n]=t,s=n||e.me;return s&&s instanceof Element?r?Ts(s,r):s.previousElementSibling:null},validate:e=>vr(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")};function Ss(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;const e=r.querySelector(t);if(e)return e;r=r.nextElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Ss(n,t):null}function Ts(e,t){let r=e.previousElementSibling;for(;r;){const e=Array.from(r.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(r.matches(t))return r;r=r.previousElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Ts(n,t):null}const Ls={name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const a=i.closest(n);return a?Ps(i,r,a):null},validate:e=>br(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")},Os={name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const a=i.closest(n);return a?Ns(i,r,a):null},validate:e=>br(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 Ps(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=Is(e);for(const e of n)if(Is(e)>s)return e;return null}function Ns(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=Is(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(s>Is(t))return t}return null}function Is(e){let t=0,r=e;for(;r&&r.parentElement;)t+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,t+=1e3;return t}const js={first:ks,last:Es,at:xs,next:Cs,previous:As,nextWithin:Ls,previousWithin:Os};var Rs=Object.freeze({__proto__:null,FirstExpression:gs,LastExpression:vs,atExpression:xs,createFirstExpression:bs,createLastExpression:ws,findNextElementInDOM:Ss,findNextElementWithinContainer:Ps,findPreviousElementInDOM:Ts,findPreviousElementWithinContainer:Ns,firstExpression:ks,getElementPosition:Is,lastExpression:Es,nextExpression:Cs,nextWithinExpression:Ls,positionalExpressions:js,previousExpression:As,previousWithinExpression:Os});const qs=new Set(["__proto__","constructor","prototype"]),_s={name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[r,n]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return rr(r,n);if(Zt(r)){if(qs.has(n))return;return r[n]}return r[n]}},validate:e=>pr(e,2,"possessive","element, property")??hr(e,1,"possessive","property name")},Ms={name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[r]=t;if(e.me){if("string"!=typeof r)throw Error("Property name must be a string");if(e.me instanceof Element)return rr(e.me,r);if(Zt(e.me)){if(qs.has(r))return;return e.me[r]}return e.me[r]}},validate:e=>fr(e,"my","property")},$s={name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[r]=t;if(null==e.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=e.it;if(n instanceof Element)return rr(n,r);if(Zt(n)){if(qs.has(r))return;return n[r]}return n[r]},validate:e=>fr(e,"its","property")},Vs={name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[r]=t;if(e.you){if("string"!=typeof r)throw Error("Property name must be a string");if(e.you instanceof Element)return rr(e.you,r);if(Zt(e.you)){if(qs.has(r))return;return e.you[r]}return e.you[r]}},validate:e=>fr(e,"your","property")},Ds={name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[r,n]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return rr(n,r);if(Zt(n)){if(qs.has(r))return;return n[r]}return n[r]}},validate:e=>pr(e,2,"of","property, object")??hr(e,0,"of","property name")},Bs={name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||e.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:e=>br(e,1,2,"attribute","attributeName, optional element")??hr(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},Fs={name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[r,n,s]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(r)===n},validate:e=>br(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??hr(e,0,"attributeWithValue","attribute name")??hr(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},zs={name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:e=>fr(e,"classReference","className")},Hs={name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:e=>fr(e,"idReference","idValue")},Us={possessive:_s,my:Ms,its:$s,your:Vs,of:Ds,attribute:Bs,attributeWithValue:Fs,classReference:zs,idReference:Hs};var Ws=Object.freeze({__proto__:null,attributeExpression:Bs,attributeWithValueExpression:Fs,classReferenceExpression:zs,getElementProperty:rr,idReferenceExpression:Hs,isAriaAttribute:function(e){return e.startsWith("aria-")||"aria"===e},isDataAttribute:function(e){return e.startsWith("data-")||"data"===e},itsExpression:$s,myExpression:Ms,ofExpression:Ds,possessiveExpression:_s,propertiesExpressions:Us,yourExpression:Vs});const Js=Lr({value:Ar().describe("String literal value")}).strict(),Ks=Lr({value:Sr().describe("Number literal value")}).strict(),Zs=Lr({value:Tr().describe("Boolean literal value")}).strict(),Ys=Lr({left:Pr().describe("Left operand"),right:Pr().describe("Right operand")}).strict();class Gs extends jr{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=Js,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid){const t=this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(e,r,!1),t}let s=t.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,e));const i=this.success(s,"string");return this.trackSimple(e,r,!0,s),i}catch(t){return this.trackSimple(e,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let r=e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=this.resolveExpression(r.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,r)=>{try{const e=this.resolveVariable(r,t);return void 0!==e?e+"":""}catch(e){return""}}),r}resolveExpression(e,t){if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):void 0}}class Xs extends jr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Ks,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?Number.isFinite(t.value)?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?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"])}}}class Qs extends jr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Zs,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class ei extends jr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Ys,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=un(t.left,"left operand")+un(t.right,"right operand");return this.trackSimple(e,r,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class ti extends jr{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=Ys,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,r,!0,s),this.success(s,"string")}catch(t){return this.trackSimple(e,r,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=Ys.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(Wt(e))return e;if(Jt(e))return""+e;if(Kt(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}class ri extends jr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Ys,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=un(t.left,"left operand")*un(t.right,"right operand");return this.trackSimple(e,r,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function ni(){return new Gs}function si(){return new Xs}function ii(){return new Qs}function ai(){return new ei}function oi(){return new ti}function li(){return new ri}const ci={stringLiteral:ni(),numberLiteral:si(),booleanLiteral:ii(),addition:ai(),stringConcatenation:oi(),multiplication:li()};var ui=Object.freeze({__proto__:null,AdditionExpression:ei,BooleanLiteralExpression:Qs,MultiplicationExpression:ri,NumberLiteralExpression:Xs,StringConcatenationExpression:ti,StringLiteralExpression:Gs,createAdditionExpression:ai,createBooleanLiteralExpression:ii,createMultiplicationExpression:li,createNumberLiteralExpression:si,createStringConcatenationExpression:oi,createStringLiteralExpression:ni,specialExpressions:ci});class di extends dr{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(rn),this.registerCategory(Zn),this.registerCategory(ds),this.registerCategory(js),this.registerCategory(Us),this.registerCategory(ci)}}class mi{static toTyped(e){return{me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class pi{constructor(e,t,r){this.impl=e,this.expressionEvaluator=t??new di,this.hookRegistry=r??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,r={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:r,event:e.event??void 0,executionContext:e}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(e,...t){const r=t[0],n=this.createHookContext(e,t,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(de(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void de(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const s=mi.toTyped(e);let i,a;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(de(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers,n=t?.when||t?.where;if(n&&!await this.expressionEvaluator.evaluate(n,e))return void de(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:t||{},commandName:r.commandName},this.expressionEvaluator,e)}else i=t;else de(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return de("CommandAdapterV2: Calling execute with parsed input:",i),a=2===this.impl.execute.length?await this.impl.execute(i,s):await this.impl.execute(s,...i),de("CommandAdapterV2: Command result:",a),Object.assign(e,mi.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,a),a}catch(e){if(bi(e)||de(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(n,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class hi{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);fe(`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 r=t.toLowerCase();fe(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,e);const n=new pi(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),k.add(r);const s=e.metadata?.aliases;if(s&&Array.isArray(s))for(const t of s){const r=t.toLowerCase();this.implementations.set(r,e),this.adapters.set(r,n),k.add(r)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const r=this.getAdapter(e);return r?r.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let fi=null;function yi(){return fi||(fi=function(e){const t=e?.commands??new hi,r=e?.eventSources??new zt,n=e?.context??new Ht,s=new Set,i={commands:t,eventSources:r,context:n,use(e){if(s.has(e.name))console.warn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const r of e.commands)t.register(r);if(e.eventSources)for(const t of e.eventSources)r.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:r,options:s}of e.contextProviders)n.register(t,r,s);e.setup?.(i),s.add(e.name)}},reset(){s.clear()}};return i}()),fi}class gi{constructor(e={}){this.contextCache=new WeakMap;const t=yi();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,fe(`[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),fe(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return fe("[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 fe(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return fe(`[RegistryIntegration] Found event source '${r}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(e,t,r);if(!n)throw Error(`Failed to subscribe to event source '${e}'`);return fe(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,fe("[RegistryIntegration] Destroyed")}}function vi(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 bi(e){return e instanceof Error&&(null!==qt(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function wi(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 ki(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const Ei=new WeakMap;class xi{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.expressionEvaluator=e.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=Dt,this.hookRegistry=new Rt,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Vt,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new gi("object"==typeof e.registryIntegration?e.registryIntegration:{}),fe("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,r)=>await this.installBehaviorOnElement(e,t,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const r of e)for(const e of r.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&&fe(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),fe("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){fe(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,r)=>this.execute(e,r||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return fe("⚠️ 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 r=await this.processCommandWithResult(e,t);if(!$t(r))throw vi(r.error);return r.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const r={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(r,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=e,n=await this.executeCommandSequenceWithResult(r.commands||[],t);if(!$t(n))throw vi(n.error);return n.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(e,t);if(!$t(r))throw vi(r.error);return r.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:r,args:n,modifiers:s}=e,i=r.toLowerCase();if(de(`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:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(e){throw bi(e)||console.error(`Error executing command '${i}':`,e),e}}const a=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(a),Error(a)}toSignal(e){const t=qt(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:r,args:n,modifiers:s}=e,i=r.toLowerCase();if(de(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(e),Error(e)}const a=await this.registry.getAdapter(i);if(!a)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return _t(await a.execute(t,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return Mt(t);throw console.error(`Error executing command '${i}':`,e),e}}async executeCommandSequenceWithResult(e,t){let r;for(const n of e){if(this.hasErrorDiagnostics(n)){const e=n.diagnostics?.[0];fe("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===n.type){const e=await this.processCommandWithResult(n,t);if(!$t(e)){const r=e.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==r.returnValue&&Object.assign(t,{it:r.returnValue,result:r.returnValue}),_t(r.returnValue)}}r=e.value}else{const e=await this.evaluateExpressionWithResult(n,t);if(!$t(e))return e;r=e.value}}return _t(r)}async evaluateExpression(e,t){const r=await this.expressionEvaluator.evaluate(e,t);return ki(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const r=await this.expressionEvaluator.evaluateWithResult(e,t);if(!$t(r))return r;const n=r.value;if(ki(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},t);try{return _t(await this.executeCommandFromPattern(n.command,n.selector,t))}catch(e){const t=this.toSignal(e);if(t)return Mt(t);throw e}}return _t(n)}async executeCommandFromPattern(e,t,r){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},r)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let r;const n=[],s=[],i=[];for(const t of e.statements)"eventHandler"===t.type?n.push(t):"initBlock"===t.type?s.push(t):i.push(t);for(const e of n)try{await this.execute(e,t)}catch(e){if(bi(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{r=await this.execute(e,t)}catch(e){if(bi(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(bi(e)&&(e.isHalt||e.isExit))break;throw e}return r}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const r of e.commands)try{await this.execute(r,t)}catch(e){if(bi(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let r;for(const n of e.commands)try{r=await this.execute(n,t)}catch(e){if(bi(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 r}async executeObjectLiteral(e,t){const r={};if(!e.properties)return r;for(const n of e.properties){let e;e="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,t)+"";const s=await this.execute(n.value,t);r[e]=s}return r}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:r,parameters:n,eventHandlers:s,initBlock:i}=e,a=e.imperativeInstaller;"function"==typeof a?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:a}),fe(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),fe(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(e,t,r){fe("BEHAVIOR: installBehaviorOnElement called: "+e);let n=this.behaviorRegistry.get(e);if(!n&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(n=this.behaviorRegistry.get(e)),!n))throw Error(`Behavior "${e}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return fe(`BEHAVIOR: Installing imperative behavior '${e}'`),n.install(t,r),void fe(`BEHAVIOR: Finished installing imperative behavior '${e}'`);fe("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(n.parameters)for(const e of n.parameters)i.locals.set(e,e in r?r[e]:void 0);for(const[e,t]of Object.entries(r))n.parameters?.includes(e)||i.locals.set(e,t);if(n.initBlock){fe("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),fe("BEHAVIOR: Init block completed for "+e)}catch(t){if(fe(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&bi(t)))throw t}}if(fe(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers){const t=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}fe("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:r,events:n,commands:s,target:i,args:a,selector:o,attributeName:l,watchTarget:c,modifiers:u}=e,d=n&&n.length>0?n:[r];fe(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let m=[],p=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)p=window;else if("document"===e||"the document"===e||"body"===e)p=document;else if("me"===e||"myself"===e)m=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);fe(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(e)}`),this.isElement(e)?m=[e]:Array.isArray(e)?m=e.filter(e=>this.isElement(e)):"string"==typeof e&&(m=this.queryElements(e,t))}else fe(`BEHAVIOR: Target resolution: querying for '${i}'`),m=this.queryElements(i,t)}else m=t.me?[t.me]:[];if(0===m.length&&!p)return void fe(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&l)return void this.setupMutationObserver(m,l,s,t);if("change"===r&&c)return void this.setupChangeObserver(c,s,t);const h=e.customEventSource;if(h&&this.registryIntegration){fe(`BEHAVIOR: executeEventHandler - Using custom event source '${h}' for event '${r}'`);const e=async e=>{const n=new Map(t.locals),i={...t,locals:n,it:e,event:e},a=this.enhanceContext(i);fe(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},a)}catch(e){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,e)}};try{const n=this.registryIntegration.subscribeToEventSource(h,{event:r,handler:e,target:i,selector:o},t);fe(`BEHAVIOR: Subscribed to custom event source '${h}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${h}' subscription ${n.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${h}':`,e)}return}const f=xi.createEventHandler(this,s,t,o,a);let y,g=null;if(u){let e=f;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>e(n),t)},g=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const t=u.throttle;let r=0;y=n=>{const s=Date.now();t>s-r||(r=s,e(n))}}else y=e}else y=f;const v=u?.once?{once:!0}:void 0;if(p){for(const e of d)p.addEventListener(e,y,v),m.length>0?this.cleanupRegistry.registerListener(m[0],p,e,y):this.cleanupRegistry.registerGlobal(()=>p.removeEventListener(e,y),"listener",`Global ${e} listener`);g&&(m.length>0?this.cleanupRegistry.registerCustom(m[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const e of m){for(const t of d)e.addEventListener(t,y,v),this.cleanupRegistry.registerListener(e,e,t,y);g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,r,n,s){return async i=>{const a=Ei.get(i)??0;if(a>=100)return;if(Ei.set(i,a+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{fe(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const o=new Map(r.locals),l={...r,locals:o,it:i,event:i};o.has("target")||l.locals.set("target",i.target);const c=e.enhanceContext(l);if(s&&s.length>0){const e=i,t=e.detail;for(const r of s)c.locals.set(r,e[r]??t?.[r]??null)}for(const r of t)try{const t=wi(await e.execute(r,c));void 0!==t&&Object.assign(c,{it:t,result:t})}catch(e){if(bi(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(c,{it:e.returnValue,result:e.returnValue});break}}throw console.error("COMMAND FAILED:",e),e}}}setupMutationObserver(e,t,r,n){fe(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const s of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){me(`MUTATION DETECTED: attribute '${t}' changed on`,s);const e={...n,me:s,it:i,locals:new Map(n.locals)},a=i.oldValue,o=s.getAttribute(t);e.locals.set("oldValue",a),e.locals.set("newValue",o);const l=this.enhanceContext(e);for(const e of r)try{await this.execute(e,l)}catch(e){if(bi(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing mutation handler command:",e)}}});e.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),fe("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){fe("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(e,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(e=>this.isElement(e))),fe(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const e of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){me("CONTENT CHANGE DETECTED on",e,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",e);const i=s.oldValue,a=e.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",a);const o=this.enhanceContext(n);for(const e of t)try{await this.execute(e,o)}catch(e){if(bi(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing change handler command:",e)}}});n.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),fe("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=e;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return fe(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}const Ci={core:["references","logical","special"],common:["properties","conversion"],optional:["positional"]};class Ai extends dr{constructor(e={}){super(),this.loadedCategories=new Set,this.loadPromises=new Map,this.options={preload:"core",...e},"none"!==this.options.preload&&this.preloadExpressions()}async preloadExpressions(){if(this.options.categories)await Promise.all(this.options.categories.map(e=>this.loadCategory(e)));else switch(this.options.preload){case"all":await this.preloadTier("core"),await this.preloadTier("common"),await this.preloadTier("optional");break;case"common":await this.preloadTier("core"),await this.preloadTier("common");break;case"core":await this.preloadTier("core")}}async preloadTier(e){const t=Ci[e];await Promise.all(t.map(e=>this.loadCategory(e)))}async loadCategory(e){if(this.loadedCategories.has(e))return;if(this.loadPromises.has(e))return this.loadPromises.get(e);const t=this._loadCategoryImpl(e);this.loadPromises.set(e,t);try{await t,this.loadedCategories.add(e),he("✅ Loaded expression category: "+e)}finally{this.loadPromises.delete(e)}}async _loadCategoryImpl(e){try{let t;switch(he("📦 Loading expression category: "+e),e){case"references":t=await Promise.resolve().then(function(){return nn});break;case"logical":t=await Promise.resolve().then(function(){return Yn});break;case"special":t=await Promise.resolve().then(function(){return ui});break;case"properties":t=await Promise.resolve().then(function(){return Ws});break;case"conversion":t=await Promise.resolve().then(function(){return ms});break;case"positional":t=await Promise.resolve().then(function(){return Rs});break;default:return void console.warn("Unknown expression category: "+e)}const r=t[e+"Expressions"]||t.default;if(!r)return void console.warn("No expressions found in category: "+e);this.registerCategory(r),he(` ✓ Registered ${Object.keys(r).length} expressions from ${e}`)}catch(t){throw console.error("Failed to load expression category: "+e,t),t}}getCategoryForNodeType(e){return{identifier:"references",selector:"references",dollarExpression:"references",binaryExpression:"logical",unaryExpression:"logical",comparison:"logical",literal:"special",string:"special",numberLiteral:"special",stringLiteral:"special",booleanLiteral:"special",arrayLiteral:"special",objectLiteral:"special",templateLiteral:"special",memberExpression:"properties",possessiveExpression:"properties",propertyAccess:"properties",propertyOfExpression:"properties",asExpression:"conversion",positional:"positional",callExpression:"references"}[e]||null}async evaluate(e,t){if(!e)return he("LAZY EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("LAZY EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));const r=this.getCategoryForNodeType(e.type);return r&&!this.loadedCategories.has(r)&&(he(`🔄 Auto-loading category for node type: ${e.type} → ${r}`),await this.loadCategory(r)),super.evaluate(e,t)}async warmupExpressions(e){he("🔥 Warming up expression categories: "+e.join(", ")),await Promise.all(e.map(e=>this.loadCategory(e)))}getLoadedCategories(){return Array.from(this.loadedCategories)}}function Si(e,t,r,n,s,i){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,l=n.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=!t&&e?n.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),m=!1,p=r.length-1;p>=0;p--){var h={};for(var f in n)h[f]="access"===f?{}:n[f];for(var f in n.access)h.access[f]=n.access[f];h.addInitializer=function(e){if(m)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(e||null))};var y=(0,r[p])("accessor"===l?{get:d.get,set:d.set}:d[c],h);if("accessor"===l){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(o=a(y.get))&&(d.get=o),(o=a(y.set))&&(d.set=o),(o=a(y.init))&&s.unshift(o)}else(o=a(y))&&("field"===l?s.unshift(o):d[c]=o)}u&&Object.defineProperty(u,n.name,d),m=!0}function Ti(e,t,r){for(var n=arguments.length>2,s=0;t.length>s;s++)r=n?t[s].call(e,r):t[s].call(e);return n?r:void 0}function Li(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}"function"==typeof SuppressedError&&SuppressedError;const Oi=Symbol("command:name"),Pi=Symbol("command:category"),Ni=Symbol("command:metadata");function Ii(e){return function(t,r){const n=t;n[Oi]=e.name,n[Pi]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function ji(e){return function(t,r){const n=t,s=n[Pi];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const i={description:e.description,syntax:e.syntax,examples:e.examples,category:s,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};n[Ni]=i,Object.defineProperty(t,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function Ri(e){return()=>new e}function qi(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function _i(e,t){if(qi(e))return e;if(!e){const e=t.me;if(!e)throw Error("No target element - provide explicit target or ensure context.me is set");return $i(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return $i(t.me)}if("it"===r){if(!qi(t.it))throw Error('Context reference "it" is not an HTMLElement');return t.it}if("you"===r){if(!t.you)throw Error('Context reference "you" is not available');return $i(t.you)}const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelector(r);if(!s)throw Error("Element not found with selector: "+r);if(!qi(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof e)}function Mi(e,t){if(Array.isArray(e))return e.filter(qi);if(e instanceof NodeList)return Array.from(e).filter(qi);if(qi(e))return[e];if(!e){const e=t.me;return e&&qi(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&qi(t.me)?[t.me]:[];if("it"===r)return qi(t.it)?[t.it]:[];if("you"===r)return t.you&&qi(t.you)?[t.you]:[];const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let e=r;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.querySelectorAll(e);return Array.from(t).filter(qi)}}return[]}function $i(e){if(qi(e))return e;throw Error("Value is not an HTMLElement")}function Vi(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!qi(t.me))throw Error("context.me is not an HTMLElement");return t.me;case"its":case"it":if(!t.it)throw Error('No "it" value in context');if(!qi(t.it))throw Error("context.it is not an HTMLElement");return t.it;case"your":case"you":if(!t.you)throw Error('No "you" element in context');if(!qi(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const Di=["on","from","to","in","with","at"];async function Bi(e,t,r,n,s={},i){let a=e;if(s.filterPrepositions&&e&&(a=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Di.includes(t.name.toLowerCase())})),(!a||0===a.length)&&s.fallbackModifierKey&&i){const e=i[s.fallbackModifierKey];e&&(a=[e])}if(!a||0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!qi(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const o=[];for(const e of a){const s=await t.evaluate(e,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(qi(s))o.push(s);else if(s instanceof NodeList){const e=Array.from(s).filter(qi);o.push(...e)}else if(Array.isArray(s)){const e=s.filter(qi);o.push(...e)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let e=s;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const n=t.querySelectorAll(e),i=Array.from(n).filter(qi);o.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!qi(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return o}class Fi{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await Bi(e.args,t,r,n)}}(e,t,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>qi(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const r=e.dataset.originalDisplay;void 0!==r?(e.style.display=r||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let zi=(()=>{let e,t,r=[ji({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Ii({name:"hide",category:"dom"})],n=[],s=Fi;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=>qi(e))}},Li(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const Hi=Ri(zi);let Ui=(()=>{let e,t,r=[ji({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Ii({name:"show",category:"dom"})],n=[],s=Fi;return t=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const r=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,r)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>qi(e))&&"string"==typeof t.defaultDisplay}},Li(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const Wi=Ri(Ui);function Ji(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function Ki(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),r=e.indexOf("=");if(-1===r)return{name:e.trim()};const n=e.slice(0,r).trim();let s=e.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function Zi(e,t){for(const r of e)t(r);return e}function Yi(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function Gi(e,t,r){const n=e.hasAttribute(t);void 0!==r?n&&e.getAttribute(t)===r?e.removeAttribute(t):e.setAttribute(t,r):n?e.removeAttribute(t):e.setAttribute(t,"")}function Xi(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&&ea(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&&ea(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&ea(r)?[r]:[]}function Qi(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function ea(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Qi(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function ta(e,t){return e.map(e=>{if(Qi(e)){const r=function(e){const t=e.trim(),r=t.match(/^\{(.+)\}$/);return r?r[1].trim():t}(e),n=t.locals.get(r)??t.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return e}).filter(e=>e.length>0)}function ra(e){return"string"==typeof e&&e.trim().startsWith("*")}function na(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const r=t.substring(1).trim();return r?{property:r}:null}(e);if(!t)return null;const r=t.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function sa(e,t,r){e.style.setProperty(t,r)}const ia=["dialog","details","summary","select"];function aa(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 oa(e,t,r){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const r=aa(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const r=aa(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:aa(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=aa(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(n=e,"attributeAccess"===n.type?"@"+n.attributeName:aa(n)),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1};var n}class la{async resolveTargets(e,t,r,n){return Bi(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return oa(e,t,r)}parseClassNames(e){return Xi(e)}isAttribute(e){return Ji(e.trim())}isCSSProperty(e){return ra(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>qi(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 ca=(()=>{let e,t,r=[ji({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"]}),Ii({name:"add",category:"dom"})],n=[],s=la;return t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(e){const t=Ki(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const i=await t.evaluate(e.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,r,e.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const r=ta(e.classes,t);r.length>0&&Yi(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,Zi(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":!function(e,t){Yi(e,Object.entries(t),(e,[t,r])=>{e.style.setProperty(t,r)})}(e.targets,e.styles)}var r,n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const r=t.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(e=>"string"==typeof e))return!1}return!0}},Li(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const ua=Ri(ca);function da(e){return!!e.parentNode&&(e.remove(),!0)}let ma=(()=>{let e,t,r=[ji({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"]}),Ii({name:"remove",category:"dom"})],n=[],s=la;return t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if(qi(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&qi(n[0]))return{type:"element",targets:n.filter(e=>qi(e))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:Ki(s).name,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const r=ta(e.classes,t);r.length>0&&Yi(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,Zi(e.targets,e=>{e.removeAttribute(r)});break;case"styles":!function(e,t){Yi(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)da(t)}var r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}},Li(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const pa=Ri(ma);function ha(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function fa(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=ha(e);return r?r.milliseconds:t}return t}function ya(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=ha(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function ga(e){return e&&"none"!==e?e.split(",").map(e=>{const t=parseFloat(e.trim());return isNaN(t)?0:e.includes("s")&&!e.includes("ms")?1e3*t:t}):[0]}function va(e,t){let r=0;for(let n=0;e.length>n;n++)r=Math.max(r,(e[n]||0)+(t[n]||0));return r}function ba(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function wa(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&Gi(e,r)}}function ka(e,t,r,n){const s=wa(e,t,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Ea(e,t,r,n){const s=wa(e,t,r),i=()=>{s(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function xa(e,t,r){if(t.startsWith("@")){const n=t.substring(1);return void(!1===r?e.removeAttribute(n):e.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(t){case"textContent":return void(e.textContent=n);case"innerHTML":return void(e.innerHTML=n);case"innerText":return void(e.innerText=n);case"id":return void(e.id=n);case"className":return void(e.className=n);case"value":return void("value"in e&&(e.value=n));case"checked":return void("checked"in e&&(e.checked=!!r))}if(t.includes(".")){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++)if(s=s[n[e]],null==s)return;return void(s[n[n.length-1]]=r)}if(t.includes("-")||t in e.style)e.style.setProperty(t,n);else try{e[t]=r}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function Ca(e){return null==e||""===e}const Aa=/^the\s+(.+?)\s+of\s+(.+)$/i,Sa=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 Ta(e){return"string"==typeof e&&Aa.test(e)}function La(e,t){const r=e.match(Aa);if(!r)return null;try{return{element:_i(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function Oa(e,t,r){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,r){const n=e.property?.name;if(!n)return null;let s=await t.evaluate(e.target,r);return Array.isArray(s)&&(s=s[0]),qi(s)?{element:s,property:n}:null}(e,t,r);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,r){const n="string"==typeof e.property?e.property:e.property?.name;if(!n)return null;let s=await t.evaluate(e.object,r);return Array.isArray(s)&&(s=s[0]),qi(s)?{element:s,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const e=n.object,s=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!qi(i))return null;const a=s?.name||s?.value;return a&&(a.startsWith("@")||a.startsWith("*"))?{element:i,property:a}:null}return null}function Pa(e,t){const{element:r,property:n}=e;n.startsWith("*")?sa(r,n.substring(1),t+""):xa(r,n,t)}async function Na(e,t,r){let n,s;if(e?.for){const s=await t.evaluate(e.for,r);n="number"==typeof s?s:"string"==typeof s?fa(s):void 0}if(e?.until){const n=await t.evaluate(e.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}function Ia(e,t){const r=t?.name,n=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return ia.includes(t)}(t)}(t);if(qi(e)||Array.isArray(e)&&e.every(e=>qi(e)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return ia.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const ja=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"toggle",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("toggle command requires an argument");const n=e.args[0],s=n?.name;if("between"===s&&e.args.length>=4){const{duration:n,untilEvent:s}=await Na(e.modifiers,t,r),i=await t.evaluate(e.args[1],r),a=await t.evaluate(e.args[3],r),o=[];for(let t=4;e.args.length>t;t++){const r=e.args[t]?.name;"on"!==r&&"from"!==r&&o.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},c=await Bi(o,t,r,"toggle",l,e.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:c,duration:n,untilEvent:s}}const i=await Oa(n,t,r);if(i)return{type:"property",target:i};if("selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("*")){let s=n.value,i=1;if("*"===s&&e.args.length>1&&"identifier"===e.args[1].type&&(s="*"+e.args[1].name,i=2),"*"===s&&e.modifiers?.on){const n=e.modifiers.on?.name;if(n&&["display","visibility","opacity"].includes(n)){s="*"+n;const{duration:i,untilEvent:a}=await Na(e.modifiers,t,r),o=na(s);if(o){const e=r.me;return{type:"css-property",property:o,targets:e?[e]:[],duration:i,untilEvent:a}}}}const a=na(s);if(a){const{duration:n,untilEvent:s}=await Na(e.modifiers,t,r),o={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:a,targets:await Bi(e.args.slice(i),t,r,"toggle",o,e.modifiers),duration:n,untilEvent:s}}}const{duration:a,untilEvent:o}=await Na(e.modifiers,t,r),{value:l}=await oa(n,t,r);if(Ta(l)){const e=La(l,r);if(e)return{type:"property",target:e}}const{type:c,expression:u}=Ia(l,n),d={filterPrepositions:!0,fallbackModifierKey:"on"};switch(c){case"attribute":{const{name:n,value:s}=Ki(u);return{type:"attribute",name:n,value:s,targets:await Bi(e.args.slice(1),t,r,"toggle",d,e.modifiers),duration:a,untilEvent:o}}case"css-property":{const n=na(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await Bi(e.args.slice(1),t,r,"toggle",d,e.modifiers)}}case"element":{let s;if(qi(l))s=[l];else if(Array.isArray(l)&&l.every(e=>qi(e)))s=l;else if(u){const e=document.querySelectorAll(u);s=Array.from(e).filter(e=>qi(e))}else s=await Bi([n],t,r,"toggle",d,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(e,t,r,n){if(t?.as){const e=await r.evaluate(t.as,n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await r.evaluate(e[1],n);if("string"==typeof t){const s=t.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&e.length>=3){const t=await r.evaluate(e[2],n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:ba(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:Xi(u),targets:s,duration:a,untilEvent:o}}default:{const n=Xi(u||l);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Bi(e.args.slice(1),t,r,"toggle",d,e.modifiers),duration:a,untilEvent:o}}}}async execute(e,t){switch(e.type){case"classes":{const r=ta(e.classes,t);if(0===r.length)return[...e.targets];if(Yi(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&ka(t,"class",r[0],e.duration),e.untilEvent&&Ea(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,Zi(e.targets,e=>{Gi(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&ka(t,"attribute",e.name,e.duration),e.untilEvent&&Ea(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return Zi(e.targets,t=>function(e,t){const r=window.getComputedStyle(e);switch(t){case"display":"none"===r.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=r.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:r}=e;return r.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,r.substring(1)):rr(t,r)}(e),r=e.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof t||Sa.has(n)||Sa.has(n.toLowerCase())){const r=!t;return Pa(e,r),r}if("number"==typeof t){const r=0===t?1:0;return Pa(e,r),r}if("string"==typeof t){const n="__ht_"+r,s=e.element[n];return""===t&&void 0!==s?(Pa(e,s),s):(e.element[n]=t,Pa(e,""),"")}Pa(e,!t)}(e.target),[e.target.element];case"dialog":return Zi(e.targets,t=>{return n=e.mode,void((r=t).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return Zi(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return Zi(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const r=t.classList.contains(e.classA),n=t.classList.contains(e.classB);r?(t.classList.remove(e.classA),t.classList.add(e.classB)):n?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&ka(t,"class",e.classA,e.duration),e.untilEvent&&Ea(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},Li(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());const Ra=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"put",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("put requires arguments");const n=e=>e?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,a=null;for(let t=0;e.args.length>t;t++){const r=e.args[t],o=n(r),l="literal"===o?r.value:r.name;if(("literal"===o||"identifier"===o)&&s.includes(l)){i=t,a=l;break}}let o=null,l=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";o=e.args[0],a=t,l=e.modifiers[t]}else if(3>e.args.length){if(2>e.args.length)throw Error("put requires content and position");o=e.args[0],a=e.args[1]?.value||e.args[1]?.name||"into"}else o=e.args[0],a=e.args[1]?.value||e.args[1]?.name||null,l=e.args[2];else o=e.args.slice(0,i)[0]||null,l=e.args.slice(i+1)[0]||null;if(!o)throw Error("put requires content");if(!a)throw Error("put requires position keyword");const c=await t.evaluate(o,r),u=this.mapPosition(a);let d,m,p=null;if(l){const e=n(l),s=await Oa(l,t,r);if(s)return{value:c,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===e){const e=l.object,n=l.property;if("selector"===e?.type)p=e.value;else if("identifier"===e?.type){const s=e.name;if("my"===s||"me"===s||"I"===s){if(r.me&&n?.name)return{value:c,targets:[r.me],position:"replace",memberPath:n.name}}else if("its"===s||"it"===s){const e=await t.evaluate(l,r);"string"==typeof e&&(p=e)}else p=s}if(p&&n?.name)d=n.name;else if(!p&&!d){const e=await t.evaluate(l,r);"string"==typeof e&&(p=e)}}else if("identifier"===e&&"me"===l.name)p=null;else if("selector"===e||"cssSelector"===e)p=l.value||l.selector;else if("literal"===e){const e=l.value;if("string"==typeof e&&Ta(e)){const t=La(e,r);if(t)return{value:c,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?p=e:m=e+""}else if("identifier"===e){const e=l.name;if(this.looksLikeCss(e))p=e;else{const n=await t.evaluate(l,r),s=this.resolveEvaluatedAsElements(n);if(s)return{value:c,targets:s,position:u,memberPath:d};m=e}}else{const e=await t.evaluate(l,r),n=this.resolveEvaluatedAsElements(e);if(n)return{value:c,targets:n,position:u,memberPath:d};"string"==typeof e&&(this.looksLikeCss(e)?p=e:m=e)}}return m?{value:c,targets:[],position:u,memberPath:d,variableName:m}:{value:c,targets:await this.resolveTargets(p,r),position:u,memberPath:d}}async execute(e,t){const{value:r,targets:n,position:s,memberPath:i,variableName:a}=e;if(a)return t.locals&&t.locals.set(a,r),t[a]=r,void Object.assign(t,{it:r});if(i)for(const e of n)this.setProperty(e,i,r);else for(const e of n){const t=this.parseValue(r);this.insertContent(e,t,s)}return n}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!qi(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>qi(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return qi(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(qi(t)){const n=t;switch(r){case"beforebegin":e.parentElement?.insertBefore(n,e);break;case"afterbegin":e.insertBefore(n,e.firstChild);break;case"beforeend":e.appendChild(n);break;case"afterend":e.parentElement?.insertBefore(n,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t);else qi(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(qi(e))return[e];if(Array.isArray(e)){const t=e.filter(qi);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(qi);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,r){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++){if(!s[n[e]])throw Error(`Property path "${t}" does not exist`);s=s[n[e]]}s[n[n.length-1]]=r}},Li(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());function qa(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 _a(e,t,r){return"global"===r&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==r&&t.locals&&t.locals.has(e)?t.locals.get(e):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===r&&t.locals&&t.locals.has(e)?t.locals.get(e):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function Ma(e,t,r,n){if("global"===n)return r.globals.set(e,t),void("undefined"!=typeof window&&(window[e]=t));if(r.locals&&r.locals.has(e))r.locals.set(e,t);else{if(r.globals&&r.globals.has(e))return r.globals.set(e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(!r.variables||!r.variables.has(e))return"undefined"!=typeof window&&e in window?(window[e]=t,void r.globals.set(e,t)):void r.locals.set(e,t);r.variables.set(e,t)}}function $a(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:_a(e,t)}let Va=(()=>{let e,t,r=[ji({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"]}),Ii({name:"make",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){const n=e.args.length>0?await t.evaluate(e.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const s=void 0!==e.modifiers.an?"an":"a",i=await async function(e,t,r){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const n=[];for(const s of e.args)n.push(await t.evaluate(s,r));return n}const n=await t.evaluate(e,r);return Array.isArray(n)?n:[n]}(e.modifiers.from,t,r),a=await async function(e,t,r){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const n=await t.evaluate(e,r);return"string"==typeof n?n:n+""}(e.modifiers.called,t,r);return{article:s,expression:n,constructorArgs:i,variableName:a}}async execute(e,t){const{expression:r,constructorArgs:n=[],variableName:s}=e,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(e){const t=e.slice(1,-2);let r="div",n=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(r=s[1],n=t.slice(s[0].length));const i=document.createElement(r),a=n.split(/(?=[.#])/);for(const e of a)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(r):function(e,t,r){if(qi(e))return e;const n=e+"";let s;if("undefined"!=typeof window&&(s=window[n]),s||"undefined"==typeof global||(s=global[n]),!s&&r.variables?.has(n)&&(s=r.variables.get(n)),!s||"function"!=typeof s)throw Error(`Constructor '${n}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(r,n,t);return Object.assign(t,{it:i}),s&&Ma(s,i,t),i}},Li(t,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})();const Da=Ri(Va);function Ba(e,t,r){return e?new Promise(r=>{const n=za(()=>{e.removeEventListener(t,s)},r),s=e=>{n({event:e,timedOut:!1,cancelled:!1})};e.addEventListener(t,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function Fa(e){return new Promise(t=>setTimeout(t,e))}function za(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}const Ha=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"wait",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,r);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r);const n=e.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,e.args[1],t,r):this.parseTimeWait(e.args[0],t,r)}async execute(e,t){const r=Date.now();if("time"===e.type)return await Fa(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,s=(await Ba(n,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const r of e.destructure)r in s&&t.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in n&&t.locals.set(e,n[e]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(e,t,r){return{type:"time",milliseconds:ya(await t.evaluate(e,r))}}async parseEventWait(e,t,r,n){const s=await r.evaluate(e,n);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),a=i?i[1]:s,o=i?i[2].split(",").map(e=>e.trim()):void 0;let l;if(t){const e=await r.evaluate(t,n);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");l=e}else l=n.me??void 0;return{type:"event",eventName:a,target:l,destructure:o}}async parseEventArrayWait(e,t,r,n){const s=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",r=[];for(const n of e.properties){const e=n.key?.name||n.key?.value;"name"===e&&n.value?t=n.value.value||"":"args"===e&&n.value?.elements&&(r=n.value.elements.map(e=>e.value||e.name||""))}t&&s.push({name:t,params:r})}}let i;if(t){const e=await r.evaluate(t,n);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=n.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,r){const n=[];e.modifiers.for?n.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r)):e.args[0]&&n.push(await this.parseTimeWait(e.args[0],t,r));const s=await t.evaluate(e.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const e of i)try{n.push({type:"time",milliseconds:ya(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);n.push(t?{type:"event",eventName:t[1],target:r.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(e,t){const r=e.map(e=>"time"===e.type?Fa(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Ba(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},Li(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),Ua=new Map;const Wa=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"fetch",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("fetch requires a URL");return{url:await this.parseURL(e.args[0],t,r),responseType:this.parseResponseType(e.modifiers.as),options:await this.parseRequestOptions(e.modifiers.with,t,r)}}async execute(e,t){const r=Date.now(),{url:n,responseType:s,options:i}=e,a=new AbortController;let o;t.me&&(o=()=>a.abort(),t.me.addEventListener("fetch:abort",o,{once:!0}));const l={...i,signal:a.signal},c=Ua.get(s);if(c?.accept){const e=new Headers(l.headers);e.has("Accept")||e.set("Accept",c.accept),l.headers=e}if(t.me){const e={...l,sender:t.me,headers:l.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),l.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>a.abort(),i.timeout));try{let e=await fetch(n,l);if(t.me){const r={response:e};this.dispatchEvent(t.me,"fetch:afterResponse",r),e=r.response}const i=await this.handleResponse(e,s,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:i});const a={status:e.status,statusText:e.statusText,headers:e.headers,data:i,url:e.url,duration:Date.now()-r};return Object.assign(t,{it:i}),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 "+n);throw Error(`Fetch failed for ${n}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&o&&t.me.removeEventListener("fetch:abort",o)}}async parseURL(e,t,r){const n=await t.evaluate(e,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(Ua.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,r){if(!e)return{};const n=await t.evaluate(e,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const s={};return"method"in n&&(s.method=(n.method+"").toUpperCase()),"headers"in n&&(s.headers=this.parseHeaders(n.headers)),"body"in n&&(s.body=this.parseBody(n.body)),"credentials"in n&&(s.credentials=n.credentials),"mode"in n&&(s.mode=n.mode),"cache"in n&&(s.cache=n.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[r,n]of Object.entries(e))t.set(r,n+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,r){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 n=Ua.get(t);return n?n.handler(e,r):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),r=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),1===r.childNodes.length&&qi(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},Li(t,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),Ja=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"set",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("set command requires a target");const n=e.args[0],s=n?.name||n?.value,i=await Oa(n,t,r);if(i){const n=await this.extractValue(e,t,r);if(i.property.startsWith("*")){const e=i.property.substring(1);return{type:"style",element:i.element,property:e,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,e,t,r);if(s)return s}let a;if(a="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await t.evaluate(n,r):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(qi(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,r)};if(Ta(a)){const n=La(a,r);if(n){const s=await this.extractValue(e,t,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(a,e,t,r)}if("string"==typeof a&&ra(a)){const n=a.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,r),property:n,value:s+""}}if("string"==typeof a&&Ji(a)){const n=a.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,r),name:n,value:s}}if("string"==typeof a){const n=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=Vi(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:s,property:n[2],value:i}}}if(qi(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(a)&&a.length>0&&qi(a[0])){const n=await this.extractValue(e,t,r);return{type:"property",element:a[0],property:"textContent",value:n}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===n?.type||"propertyAccess"===n?.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,r)}}async execute(e,t){switch(e.type){case"variable":return t.locals.set(e.name,e.value),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":return e.element.setAttribute(e.name,e.value+""),Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return xa(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return sa(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[r,n]of Object.entries(e.properties))xa(t,r,n);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"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,r,n){const s=e.object,i=e.property;if(s?.name&&i?.name){const e=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const s=Vi(e,n),a=await this.extractValue(t,r,n);return{type:"property",element:s,property:i.name,value:a}}}const a=e.object,o=e.computed;if(a){const s=await r.evaluate(a,n);if(null!=s&&"object"==typeof s){const a=o?await r.evaluate(e.property,n)+"":i?.name||"";if(a)return{type:"member-assignment",container:s,property:a,value:await this.extractValue(t,r,n)}}}return null}async extractValue(e,t,r){if(e.modifiers.to)return t.evaluate(e.modifiers.to,r);const n=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(n>=0&&e.args.length>n+1)return t.evaluate(e.args[n+1],r);if(e.args.length>=2)return t.evaluate(e.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,r){return _i(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return Mi(e?await t.evaluate(e,r):void 0,r)}async parseTheXofY(e,t,r,n){const s=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,a]=s,o=_i(a,n),l=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.trim(),value:l}}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&&qi(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&qi(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&qi(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}}},Li(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());let Ka=(()=>{let e,t,r=[ji({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"]}),Ii({name:"increment",category:"data"})],n=[];return t=class{async parseInput(e,t,r){const n="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,r,n){if(!e.args||0===e.args.length)throw Error(n+" command requires a target");const s=e.args[0];let i,a;const o=(l=s)&&"object"==typeof l&&l.type||"unknown";var l;if("identifier"===o)i=s.name,s.scope&&(a=s.scope);else if("literal"===o)i=s.value;else{const e=await t.evaluate(s,r);i=Array.isArray(e)&&e.length>0?e[0]:e}let c=1,u=a;for(let n=1;e.args.length>n;n++){const s=e.args[n];if(s&&"literal"===s.type){const e=s.value;"global"===e?u="global":"number"==typeof e&&(c=e)}else if(s&&"literal"!==s.type){const e=await t.evaluate(s,r);"number"==typeof e&&(c=e)}}return{target:i,amount:c,...u&&{scope:u}}}(e,t,r,n);return{...s,operation:n}}async execute(e,t){const{target:r,property:n,scope:s,amount:i=1,operation:a="increment"}=e,o=function(e,t,r,n){if("number"==typeof e)return e;if(qi(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?qa(r.getAttribute(t)):qa(r[t]):qa(r.value||r.textContent)}return"string"==typeof e?"global"===r?qa(_a(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],s=$a(r[0],t);return s?qa(s[n]):0}(e,n):qa("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:_a(e,n)):qa(e)}(r,n,s,t);let l;if(isNaN(o))l=NaN;else{const e=isFinite(i)?i:1;l="increment"===a?o+e:o-e}return function(e,t,r,n,s){if(qi(e)){const r=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?r.setAttribute(t,n+""):r[t]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof e){if("global"===r)return void Ma(e,n,s,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),s=n[1],i=$a(n[0],r);i&&(i[s]=t)}(e,n,s);if("me"===e&&s.me)return void(s.me.value=n);if("it"===e)return void Object.assign(s,{it:n});if("you"===e&&s.you)return void(s.you.value=n);Ma(e,n,s)}}(r,n,s,l,t),Object.assign(t,{it:l}),l}},Li(t,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})();const Za=Ri(Ka),Ya=Ri(Ka),Ga=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"log",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{values:[]}}async execute(e,t){const r="undefined"!=typeof window?window.console:console;0===e.values.length?r.log():r.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},Li(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());function Xa(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 Qa=(()=>{let e,t,r=[ji({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"]}),Ii({name:"trigger",category:"event"})],n=[];return t=class{async parseInput(e,t,r){const n="send"===e.commandName?.toLowerCase()?"send":"trigger",s=n;if(!e.args?.length)throw Error(s+" command requires an event name");const i=e=>e?.type||"unknown",a=e.args[0];let o,l,c;if("functionCall"===i(a)||"callExpression"===i(a)){o=a.name||a.callee?.name;const e=a.args||a.arguments;e?.length&&(l=await this.parseEventDetail(e,t,r))}else if("identifier"===i(a)||"keyword"===i(a))o=a.name;else{const e=await t.evaluate(a,r);o="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)c=await this.resolveTargets([u],t,r,s);else{const n=e.args.findIndex((e,t)=>{if(0===t)return!1;const r=e.name||e.value;return"on"===r||"to"===r});if(-1!==n&&e.args.length-1>n){const i=e.args.slice(n+1),a=i.findIndex(e=>"with"===(e.name||e.value)),o=-1===a?i:i.slice(0,a);c=await this.resolveTargets(o,t,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");c=[r.me]}}return{eventName:o,detail:l,targets:c,options:await this.parseEventOptions(e.args,t,r),mode:n}}async execute(e,t){const r=function(e,t,r={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(r);t.it=r}async resolveTargets(e,t,r,n){const s=[];for(const n of e){const e=await t.evaluate(n,r);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&r.me)s.push(r.me);else if("you"===e&&r.you)s.push(r.you);else if("it"===e&&r.it)s.push(r.it);else if(qi(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(qi));else if(Array.isArray(e))s.push(...e.filter(qi));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(qi));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);s.push(e)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(e,t,r){if(!e?.length)return;if(1===e.length){const n=e[0];if("objectLiteral"!==n?.type)return await t.evaluate(n,r)}const n={};for(const s of e){const e=await t.evaluate(s,r);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,r]=e.split(":",2);n[t.trim()]=Xa(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:!0,cancelable:!0,composed:!1},s=e.findIndex(e=>"with"===(e.name||e.value));if(-1===s)return n;for(const i of e.slice(s+1)){const e=await t.evaluate(i,r);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?n.bubbles=!0:"nobubbles"===t?n.bubbles=!1:"cancelable"===t?n.cancelable=!0:"nocancelable"===t?n.cancelable=!1:"composed"===t&&(n.composed=!0)}}return n}},Li(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})();const eo=Ri(Qa),to=Ri(Qa),ro=Ri((()=>{let e,t,r=[ji({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"]}),Ii({name:"go",category:"navigation"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{args:[]}}async execute(e,t){const{args:r}=e;if(0===r.length)throw Error("Go command requires arguments");return"string"==typeof r[0]&&"back"===r[0].toLowerCase()?(await this.goBack(),{result:"back",type:"back"}):this.isUrlNavigation(r)?{result:await this.navigateToUrl(r,t),type:"url"}:{result:await this.scrollToElement(r,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const r=e.findIndex(e=>"url"===e),n=e[r+1];if(!n)throw Error('URL is required after "url" keyword');const s="string"==typeof n?n:n+"",i=e.includes("new")&&e.includes("window");if(!this.isValidUrl(s))throw Error(`Invalid URL: "${s}"`);if(i){if("undefined"!=typeof window&&window.open){const e=window.open(s,"_blank");e?.focus&&e.focus()}}else s.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=s):"undefined"!=typeof window&&(window.location.assign?.(s)??(window.location.href=s));return s}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const r=this.parseScrollPosition(e),n=this.parseScrollTarget(e),s=this.parseScrollOffset(e),i=!e.includes("instantly"),a=this.resolveScrollTarget(n,t);if(!a)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==s){a.scrollIntoView?.({behavior:e,block:t,inline:n});const{x:i,y:o}=this.calculateScrollPosition(a,r,s);window.scrollTo?.({left:i,top:o,behavior:e})}else a.scrollIntoView?.({behavior:e,block:t,inline:n})}return a}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let s=!1,i=!1;for(const a of e)"string"==typeof a&&(r.includes(a)?(t.vertical=a,s=!0):n.includes(a)&&(t.horizontal=a,i=!0));return i&&!s&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let r=e[t+1];return"the"===r&&e.length>t+2&&(r=e[t+2]),r}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!r.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const r=e[t];if("string"==typeof r){const e=r.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===r||"-"===r)&&e.length>t+1){const n=e[t+1],s="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(s))return"-"===r?-s:s}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const r="string"==typeof e?e:e+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&qi(t.me))return t.me;if("it"===r&&qi(t.it))return t.it;if("you"===r&&qi(t.you))return t.you;const n=_a(r,t);if(qi(n))return n;if("undefined"!=typeof document)try{const e=document.querySelector(r);if(e)return e}catch{try{const e=document.getElementsByTagName(r);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,r){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const n=e.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,a=window.innerWidth||800,o=window.innerHeight||600;let l=s,c=i;switch(t.horizontal){case"left":l=n.left+s;break;case"center":l=n.left+s+n.width/2-a/2;break;case"right":l=n.right+s-a}switch(t.vertical){case"top":c=n.top+i+r;break;case"middle":c=n.top+i+n.height/2-o/2+r;break;case"bottom":c=n.bottom+i-o+r}return{x:Math.max(0,l),y:Math.max(0,c)}}},Li(t,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());function no(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const r=_a(e,t);return void 0!==r?!!r:!!e}return!!e}const so=Ri((()=>{let e,t,r=[ji({description:"Conditional execution based on boolean expressions",syntax:["if <condition> then <commands>","if <condition> then <commands> else <commands>","unless <condition> <commands>"],examples:["if x > 5 then add .active","if user.isAdmin then show #adminPanel else hide #adminPanel","unless user.isLoggedIn showLoginForm"],sideEffects:["conditional-execution"],aliases:["unless"]}),Ii({name:"if",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){const n="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(n+" command requires a condition to evaluate");let s,i;if("unless"===n){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");s=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(s=e.args[1],i=3>e.args.length?void 0:e.args[2]):e.modifiers?.then&&(s=e.modifiers.then,i=e.modifiers.else),!s)throw Error('if command requires "then" branch with commands');return{mode:n,condition:await t.evaluate(e.args[0],r),thenCommands:s,elseCommands:i}}async execute(e,t){const{mode:r,condition:n,thenCommands:s,elseCommands:i}=e,a=no(n,t);let o,l;return("unless"===r?!a:a)?(o="then",l=await this.executeCommandsOrBlock(s,t),"unless"===r&&Object.assign(t,{it:l})):i&&"if"===r?(o="else",l=await this.executeCommandsOrBlock(i,t)):o="none",{mode:r,conditionResult:a,executedBranch:o,result:l}}async executeCommandsOrBlock(e,t){return"block"===e?.type?this.executeBlock(e,t):Array.isArray(e)?this.executeCommands(e,t):e}async executeBlock(e,t){const r=t.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let n;if(e.commands?.length)for(const s of e.commands)n=await r(s,t);return n}async executeCommands(e,t){let r;for(const n of e)r=n?.execute?await n.execute(t):"function"==typeof n?await n():n;return r}},Li(t,"ConditionalCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),io=so,ao=so;let oo=(()=>{let e,t,r=[ji({description:"Iteration in hyperscript - for-in, counted, conditional, event-driven, and infinite loops",syntax:["repeat for <var> in <collection> { <commands> }","repeat <count> times { <commands> }","repeat while <condition> { <commands> }","repeat until <condition> { <commands> }","repeat forever { <commands> }"],examples:["repeat for item in items { log item }",'repeat 5 times { log "hello" }'],sideEffects:["iteration","conditional-execution"]}),Ii({name:"repeat",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){let n;if(e.modifiers?.index){const s=await t.evaluate(e.modifiers.index,r);"string"==typeof s&&(n=s)}let s=e.modifiers?.block||e.modifiers?.commands;if(!s)for(let t=e.args.length-1;t>=0;t--){const r=e.args[t];if("block"===r?.type&&r.commands){s=r;break}}const i=e.args[0],a="identifier"===i?.type?i.name:null;if("for"===a||e.modifiers?.for){const i=e.args[1],a=i?.value||i?.name,o=e.args[2]?await t.evaluate(e.args[2],r):void 0;if(!a||void 0===o)throw Error("for loops require variable and collection");return{type:"for",variable:a,collection:Array.isArray(o)?o:[o],indexVariable:n,commands:s}}if("times"===a||e.modifiers?.times){const i=e.args[1],a=i?await t.evaluate(i,r):void 0,o="number"==typeof a?a:parseInt(a+"",10);if(isNaN(o))throw Error("times loops require a count number");return{type:"times",count:o,indexVariable:n,commands:s}}if("while"===a||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw Error("while loops require a condition");return{type:"while",condition:t,indexVariable:n,commands:s}}if("until"===a&&e.modifiers?.from||"until-event"===a){const i=e.args[1],a=i?.value||i?.name;if(!a)throw Error("until-event loops require an event name");let o=r.me;if(e.args[2]){const n=await t.evaluate(e.args[2],r);n instanceof EventTarget?o=n:"document"===n&&(o=document)}return{type:"until-event",eventName:a,eventTarget:o,indexVariable:n,commands:s}}if("until"===a||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw Error("until loops require a condition");return{type:"until",condition:t,indexVariable:n,commands:s}}if("forever"===a||e.modifiers?.forever)return{type:"forever",indexVariable:n,commands:s};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:r,variable:n,collection:s,condition:i,count:a,indexVariable:o,commands:l,eventName:c,eventTarget:u}=e;let d,m;switch(r){case"for":({config:d,iterCtx:m}=function(e,t,r){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:r}}}(s,n,o));break;case"times":({config:d,iterCtx:m}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(a,o));break;case"while":({config:d,iterCtx:m}=function(e,t,r,n){return{config:{type:"while",shouldContinue:()=>t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,no,t,o));break;case"until":({config:d,iterCtx:m}=function(e,t,r,n){return{config:{type:"until",shouldContinue:()=>!t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,no,t,o));break;case"until-event":({config:d,iterCtx:m}=function(e,t,r){const n={index:0,eventFired:!1,indexVariable:r};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{n.eventFired=!0}}},iterCtx:n}}(c,u,o));break;case"forever":({config:d,iterCtx:m}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(o));break;default:throw Error("Unknown repeat type: "+r)}try{const e=await async function(e,t,r,n,s){const i=e.maxIterations??1e4;let a,o=0,l=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>o&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,r),n.indexVariable&&r.locals&&r.locals.set(n.indexVariable,o);try{a=await s(t,r)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){l=!0;break}if(t.message.includes("CONTINUE")){o++,n.index=o,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}o++,n.index=o,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:o,lastResult:a,interrupted:l}}(d,l,t,m,this.executeCommands.bind(this));return Object.assign(t,{it:e.lastResult}),{type:r,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:r,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const r=e,n=t.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let s;if(r.commands)for(const e of r.commands)s=await n(e,t);return s}if(Array.isArray(e)){let r;for(const n of e)r="function"==typeof n?await n(t):n&&"function"==typeof n.execute?await n.execute(t):n;return r}return"function"==typeof e?await e(t):e}},Li(t,"RepeatCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})();const lo=Ri(oo);class co{async parseInput(e,t,r){return{signalType:this.signalType}}async execute(e,t){const r=Error(this.errorMessage);throw r[this.errorFlag]=!0,"exit"===this.signalType&&(r.returnValue=void 0,r.timestamp=Date.now()),r}}let uo=(()=>{let e,t,r=[ji({description:"Exit from the current loop (repeat, for, while, until)",syntax:["break"],examples:["break","if found then break","repeat for item in items { if item == target then break }"],sideEffects:["control-flow"]}),Ii({name:"break",category:"control-flow"})],n=[],s=co;return t=class extends s{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},Li(t,"BreakCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const mo=Ri(uo);let po=(()=>{let e,t,r=[ji({description:"Skip to the next iteration of the current loop",syntax:["continue"],examples:["continue","if item.isInvalid then continue","repeat for item in items { if item.skip then continue; process item }"],sideEffects:["control-flow"]}),Ii({name:"continue",category:"control-flow"})],n=[],s=co;return t=class extends s{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},Li(t,"ContinueCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const ho=Ri(po),fo=Ri((()=>{let e,t,r=[ji({description:"Stop command execution or prevent event defaults",syntax:["halt","halt the event"],examples:["halt","halt the event","if error then halt",'on click halt the event then log "clicked"'],sideEffects:["control-flow","event-prevention"]}),Ii({name:"halt",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(e.args&&e.args.length>0){const n=e.args[0],s=e.args.length>1?e.args[1]:null;return"identifier"===n.type&&"the"===n.name&&s&&"identifier"===s.type&&"event"===s.name?{target:r.event}:{target:await t.evaluate(e.args[0],r)}}return{}}async execute(e,t){let r=e.target;if(("the"===r&&t.event||"object"==typeof r&&null!==r&&"the"===r.target&&t.event)&&(r=t.event),this.isEvent(r)){const e=r;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in t&&(t.halted=!0);const n=Error("HALT_EXECUTION");throw n.isHalt=!0,n}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},Li(t,"HaltCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),yo=Ri((()=>{let e,t,r=[ji({description:"Return a value from a command sequence or function, terminating execution",syntax:["return","return <value>"],examples:["return","return 42","return user.name","if found then return result"],sideEffects:["control-flow","context-mutation"]}),Ii({name:"return",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{value:await t.evaluate(e.args[0],r)}:{value:void 0}}async execute(e,t){const{value:r}=e;"returnValue"in t&&(t.returnValue=r),Object.assign(t,{it:r});const n=Error("RETURN_VALUE");throw n.isReturn=!0,n.returnValue=r,n}},Li(t,"ReturnCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());let go=(()=>{let e,t,r=[ji({description:"Immediately terminate execution of the current event handler or behavior",syntax:["exit"],examples:["exit","if no draggedItem exit","on click if disabled exit"],sideEffects:["control-flow"]}),Ii({name:"exit",category:"control-flow"})],n=[],s=co;return t=class extends s{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},Li(t,"ExitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ti(t,n)})(),t})();const vo=Ri(go),bo=Ri((()=>{let e,t,r=[ji({description:"Evaluate an expression and store the result in the it variable",syntax:["call <expression>"],examples:["call myFunction()",'call fetch("/api/data")',"call element.focus()"],sideEffects:["function-execution","context-mutation"]}),Ii({name:"call",category:"execution"})],n=[];return t=class{parseInput(e,t,r){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:r}=e,n=t.locals?.get("__evaluator");if(!n)throw Error("[CALL.execute] No evaluator available in context");const s=await n.evaluate(r,t);let i,a,o=!1;return"function"==typeof s?(a="function",i=s(),i instanceof Promise&&(o=!0,i=await i)):s instanceof Promise?(a="promise",o=!0,i=await s):(a="value",i=s),Object.assign(t,{it:i,result:i}),{result:i,wasAsync:o,expressionType:a}}},Li(t,"CallCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),wo=Ri((()=>{let e,t,r=[ji({description:"Add content to the end of a string, array, or HTML element",syntax:["append <content>","append <content> to <target>"],examples:['append "Hello"','append "World" to greeting',"append item to myArray",'append "<p>New</p>" to #content'],sideEffects:["data-mutation","dom-mutation"]}),Ii({name:"append",category:"content"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("append requires content");const n=await t.evaluate(e.args[0],r);let s;return e.modifiers?.to?s=await t.evaluate(e.modifiers.to,r):e.target&&(s=e.target),{content:n,target:s}}async execute(e,t){const{content:r,target:n}=e,s=r+"";if(!n)return Object.assign(t,void 0===t.it?{it:s}:{it:t.it+""+s}),{result:t.it,targetType:"result"};if("string"==typeof n){if(n.startsWith("#")||n.startsWith(".")||n.includes("[")){const e=this.resolveDOMElement(n);return e.innerHTML+=s,{result:e,targetType:"element",target:e}}if("me"===n||"it"===n||"you"===n){const e=this.resolveContextRef(n,t);if(qi(e))return e.innerHTML+=s,{result:e,targetType:"element",target:e}}const e=_a(n,t);if(void 0!==e){if(Array.isArray(e))return e.push(r),{result:e,targetType:"array",target:n};const i=(null==e?"":e+"")+s;return Ma(n,i,t),{result:i,targetType:"variable",target:n}}return Ma(n,s,t),{result:s,targetType:"variable",target:n}}if(Array.isArray(n))return n.push(r),{result:n,targetType:"array"};if(qi(n))return n.innerHTML+=s,{result:n,targetType:"element",target:n};{const e=n+""+s;return Object.assign(t,{it:e}),{result:e,targetType:"string"}}}resolveDOMElement(e){if("undefined"==typeof document)throw Error("DOM not available");const t=document.querySelector(e);if(!t)throw Error("Element not found: "+e);return t}resolveContextRef(e,t){switch(e){case"me":return t.me;case"it":return t.it;case"you":return t.you;default:throw Error("Unknown context ref: "+e)}}},Li(t,"AppendCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),ko=Ri((()=>{let e,t,r=[ji({description:"Animate CSS properties using CSS transitions",syntax:"transition <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"]}),Ii({name:"transition",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("transition requires property and value");let n,s;const i=await t.evaluate(e.args[0],r);if(qi(i)||"string"==typeof i&&/^[#.]|^(?:me|it|you)$/.test(i)?(s=i,n=await t.evaluate(e.args[1],r)+""):n=i+"",!n)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let a=await t.evaluate(e.modifiers.to,r);void 0===a&&"identifier"===e.modifiers.to.type&&(a=e.modifiers.to.name);const o={property:n,value:a};return void 0!==s&&(o.target=s),e.modifiers?.over&&(o.duration=await t.evaluate(e.modifiers.over,r)),e.modifiers?.with&&(o.timingFunction=await t.evaluate(e.modifiers.with,r)+""),o}async execute(e,t){let{property:r}=e;const{target:n,value:s,duration:i,timingFunction:a}=e;r.startsWith("*")&&(r=r.substring(1)),r=r.replace(/([A-Z])/g,"-$1").toLowerCase();const o=_i(n,t),l=fa(i,300),c=getComputedStyle(o).getPropertyValue(r),u=o.style.transition,d=`${r} ${l}ms ${a||"ease"}`;o.style.transition=u?`${u}, ${d}`:d;let m=s+"",p=!1;if("initial"===m||"inherit"===m||"unset"===m||"revert"===m){const e=o.style.getPropertyValue(r);o.style.removeProperty(r),m=getComputedStyle(o).getPropertyValue(r),e&&o.style.setProperty(r,e),p=!0}o.style.setProperty(r,m);const h=await function(e,t,r){return new Promise(n=>{const s=r=>{r.target===e&&r.propertyName===t&&a({completed:!0,cancelled:!1})},i=r=>{r.target===e&&r.propertyName===t&&a({completed:!1,cancelled:!0})},a=za(()=>{e.removeEventListener("transitionend",s),e.removeEventListener("transitioncancel",i),clearTimeout(o)},n);e.addEventListener("transitionend",s),e.addEventListener("transitioncancel",i);const o=setTimeout(()=>{a({completed:!0,cancelled:!1})},r+50)})}(o,r,l);return o.style.transition=u,p&&o.style.removeProperty(r),Object.assign(t,{it:o}),{element:o,property:r,fromValue:c,toValue:m,duration:l,completed:h.completed}}},Li(t,"TransitionCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),Eo=Ri((()=>{let e,t,r=[ji({description:"Measure DOM element dimensions, positions, and properties",syntax:["measure","measure <property>","measure <target> <property>"],examples:["measure","measure width","measure #element height","measure x and set dragX"],sideEffects:["data-mutation"]}),Ii({name:"measure",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,s,i;if(e.args?.length){const i=e.args[0];if("identifier"===i.type&&i.name){const a=i.name.toLowerCase();if("me"===a||"it"===a||"you"===a){const a=await t.evaluate(i,r);if(qi(a)&&(n=a,e.args.length>1)){const n=e.args[1];s="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else s=i.name}else{const a=await t.evaluate(i,r);if(qi(a)||"string"==typeof a&&/^[#.]/.test(a)){if(n=a,e.args.length>1){const n=e.args[1];s="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else"string"==typeof a&&(s=a)}}e.modifiers?.set&&(i=await t.evaluate(e.modifiers.set,r)+"");const a={};return void 0!==n&&(a.target=n),void 0!==s&&(a.property=s),void 0!==i&&(a.variable=i),a}async execute(e,t){const r=_i(e.target,t),n=e.property||"width",s=this.getMeasurement(r,n);return e.variable&&t.locals&&t.locals.set(e.variable,s.value),Object.assign(t,{it:s.value}),{result:s.value,wasAsync:!1,element:r,property:n,value:s.value,unit:s.unit,stored:!!e.variable}}getMeasurement(e,t){const r=getComputedStyle(e);if(t.startsWith("*")){const e=r.getPropertyValue(t.substring(1)),n=parseFloat(e);if(!isNaN(n)){const t=e.match(/([a-zA-Z%]+)$/);return{value:n,unit:t?t[1]:""}}return{value:e,unit:""}}const n=t.toLowerCase(),s=e.getBoundingClientRect(),i={width:()=>s.width,height:()=>s.height,top:()=>s.top,left:()=>s.left,right:()=>s.right,bottom:()=>s.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(i[n])return{value:i[n](),unit:"px"};const a=r.getPropertyValue(t),o=parseFloat(a);if(!isNaN(o)){const e=a.match(/([a-zA-Z%]+)$/);return{value:o,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},Li(t,"MeasureCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),xo=Ri((()=>{let e,t,r=[ji({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),Ii({name:"settle",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,s;if(e.args&&e.args.length>0){const s=await t.evaluate(e.args[0],r);(qi(s)||"string"==typeof s&&(s.startsWith("#")||s.startsWith(".")||"me"===s||"it"===s||"you"===s))&&(n=s)}e.modifiers?.for&&(s=await t.evaluate(e.modifiers.for,r));const i={};return void 0!==n&&(i.target=n),void 0!==s&&(i.timeout=s),i}async execute(e,t){const{target:r,timeout:n}=e,s=_i(r,t),i=fa(n,5e3),a=Date.now(),o=getComputedStyle(s),l=ga(o.transitionDuration),c=ga(o.transitionDelay),u=ga(o.animationDuration),d=ga(o.animationDelay),m=va(l,c),p=va(u,d),h=Math.max(m,p),f=await(y=s,g=h,v=i,g>0?new Promise(e=>{const t=e=>{e.target===y&&n({completed:!0,type:"transition"})},r=e=>{e.target===y&&n({completed:!0,type:"animation"})},n=za(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",r),clearTimeout(s),clearTimeout(i)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",r);const s=setTimeout(()=>{n({completed:!0,type:"timeout"})},g+50),i=setTimeout(()=>{n({completed:!1,type:"timeout"})},v)}):Promise.resolve({completed:!0,type:"timeout"}));var y,g,v;const b=Date.now()-a;return Object.assign(t,{it:s}),{element:s,settled:f.completed,timeout:i,duration:b}}},Li(t,"SettleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),Co=Ri((()=>{let e,t,r=[ji({description:"Execute inline JavaScript code with access to hyperscript context",syntax:["js <code> end","js(param1, param2) <code> end"],examples:['js console.log("Hello") end',"js(x, y) return x + y end",'js me.style.color = "red" end'],sideEffects:["code-execution","data-mutation"]}),Ii({name:"js",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){let n,s;if(0===e.args.length)throw Error("js command requires JavaScript code");const i=e.args[0],a=e.args[1];if(i&&"literal"===i.type&&"string"==typeof i.value)n=i.value;else{if(!i||void 0===i.value)throw Error("js command requires JavaScript code");n=i.value+""}a&&"arrayLiteral"===a.type&&Array.isArray(a.elements)&&(s=a.elements.map(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const o={code:n};return s&&s.length>0&&(o.parameters=s),o}async execute(e,t){const{code:r,parameters:n=[]}=e;if(!r.trim())return{result:void 0,executed:!1,codeLength:r.length,parameters:n,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,n),s=Function(...Object.keys(e),r),i=await s(...Object.values(e));return void 0!==i&&Object.assign(t,{it:i}),{result:i,executed:!0,codeLength:r.length,parameters:n,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,r)=>{let n=e.locals?.get(r);return void 0===n&&(n=e.variables?.get(r)),void 0===n&&(n=e[r]),t[r]=n,t},{})}}},Li(t,"JsCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),Ao=Ri((()=>{let e,t,r=[ji({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),Ii({name:"async",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:r}=e,n=Date.now();try{const e=await this.executeCommandsAsync(t,r),s=Date.now()-n;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:r.length,results:e,executed:!0,duration:s}}catch(e){throw Error("Async command execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}async executeCommandsAsync(e,t){const r=[];for(let n=0;t.length>n;n++){const s=t[n];try{const t=await this.executeCommand(s,e);r.push(t),Object.assign(e,{it:t})}catch(e){const r=this.getCommandName(s);throw Error(`Command '${r}' (${n+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return r}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},Li(t,"AsyncCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),So=Ri((()=>{let e,t,r=[ji({description:"Set a value only if it doesn't already exist",syntax:["default <expression> to <expression>"],examples:['default myVar to "fallback"','default @data-theme to "light"','default my innerHTML to "No content"'],sideEffects:["data-mutation","dom-mutation"]}),Ii({name:"default",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("default command requires a target");const n=await t.evaluate(e.args[0],r);let s;if(e.modifiers?.to)s=await t.evaluate(e.modifiers.to,r);else{if(2>e.args.length)throw Error('default command requires a value (use "to <value>")');s=await t.evaluate(e.args[1],r)}return{target:n,value:s}}async execute(e,t){const{target:r,value:n}=e;if("string"==typeof r){if(r.startsWith("@"))return this.defaultAttribute(t,r.substring(1),n);const e=r.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,r,s]=e;return this.defaultElementProperty(t,r,s,n)}return this.defaultVariable(t,r,n)}if(qi(r))return this.defaultElementValue(t,r,n);throw Error("Invalid target type: "+typeof r)}defaultVariable(e,t,r){const n=_a(t,e);return void 0!==n?{target:t,value:r,wasSet:!1,existingValue:n,targetType:"variable"}:(Ma(t,r,e),Object.assign(e,{it:r}),{target:t,value:r,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,r){if(!e.me)throw Error("No element context available for attribute default");const n=e.me.getAttribute(t);return null!==n?{target:"@"+t,value:r,wasSet:!1,existingValue:n,targetType:"attribute"}:(e.me.setAttribute(t,r+""),Object.assign(e,{it:r}),{target:"@"+t,value:r,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,r,n){const s=Vi(t,e),i=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const r=t.split(".");let n=e;for(const e of r){if(null==n)break;n=n[e]}return n}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(s,r),a=`${t} ${r}`;return Ca(i)?(xa(s,r,n),Object.assign(e,{it:n}),{target:a,value:n,wasSet:!0,targetType:"property"}):{target:a,value:n,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(e,t,r){const n=function(e){return"value"in e?e.value:e.textContent}(t);return Ca(n)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,r),Object.assign(e,{it:r}),{target:"element",value:r,wasSet:!0,targetType:"element"}):{target:"element",value:r,wasSet:!1,existingValue:n,targetType:"element"}}},Li(t,"DefaultCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());class To{constructor(){this.name="pseudo-command"}get metadata(){return To.metadata}async parseInput(e,t,r){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const n=e.args[0].properties||[];let s,i,a="",o=[];for(const e of n){const n=e.value;switch(e.key?.name||e.key?.value){case"methodName":a=n?.value||await t.evaluate(n,r)+"";break;case"methodArgs":"arrayLiteral"===n?.type&&n.elements?o=await Promise.all(n.elements.map(e=>t.evaluate(e,r))):"literal"===n?.type&&Array.isArray(n.value)&&(o=await Promise.all(n.value.map(e=>t.evaluate(e,r))));break;case"preposition":const e=n?.value;e&&"null"!==e&&(s=e);break;case"target":case"targetExpression":i=await t.evaluate(n,r)}}if(!a)throw Error("pseudo-command requires method name");if(null==i)throw Error("pseudo-command requires a target expression");return{methodName:a,methodArgs:o,preposition:s,targetExpression:i}}if(2>e.args.length)throw Error("pseudo-command requires method name and target expression");const n=await t.evaluate(e.args[0],r)+"",s=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,r))):[];let i,a;const o=["from","on","with","into","at","to"];for(const n of o)if(e.modifiers?.[n]){a=n,i=await t.evaluate(e.modifiers[n],r);break}if(i||3>e.args.length||(i=await t.evaluate(e.args[2],r)),!i)throw Error("pseudo-command requires a target expression");return{methodName:n,methodArgs:s,preposition:a,targetExpression:i}}async execute(e,t){const{methodName:r,methodArgs:n,targetExpression:s}=e;try{const e=await this.resolveTarget(s,t);if(null==e)throw Error("Target expression resolved to "+e);const i=this.resolveMethod(e,r);if(!i)throw Error(`Method "${r}" not found on target object`);if("function"!=typeof i)throw Error(`"${r}" is not a function (it's a ${typeof i})`);const a=await this.executeMethod(i,e,n);return t.locals.set("result",a),Object.assign(t,{it:a}),{result:a,methodName:r,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const r=e.split(".");let n="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(r[0])?(n=t.locals.get(r[0]),r.shift()):t.variables?.has(r[0])?(n=t.variables.get(r[0]),r.shift()):t.globals.has(r[0])&&(n=t.globals.get(r[0]),r.shift());for(const e of r){if(null==n)return null;n=n[e]}return n}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const r=t.split(".");let n=e;for(let e=0;r.length>e;e++){const t=r[e];if(null==n)return null;if(!(t in n))return null;if(n=n[t],e===r.length-1&&"function"==typeof n)return n}return null}async executeMethod(e,t,r){try{const n=e.apply(t,r);return n&&"object"==typeof n&&"then"in n?await n:n}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}function Lo(){return new To}To.metadata={description:"Treat a method on an object as a top-level command",syntax:["<method>(<args>) [(to|on|with|into|from|at)] <expression>"],examples:['getElementById("d1") from the document',"reload() the location of the window",'setAttribute("foo", "bar") on me',"foo() on me"],category:"execution",sideEffects:["method-execution"]};const Oo=Ri((()=>{let e,t,r=[ji({description:"Execute commands in the context of target elements",syntax:["tell <target> <command> [<command> ...]"],examples:["tell #sidebar hide","tell .buttons add .disabled","tell closest <form/> submit"],sideEffects:["context-switching","command-execution"]}),Ii({name:"tell",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],r),commands:e.args.slice(1)}}async execute(e,t){const{target:r,commands:n}=e,s=Mi(r,t);if(0===s.length)throw Error("tell command found no target elements");const i=t.locals.get("_runtimeExecute"),a=[];for(const e of s){const r={...t,me:e,you:e};for(const e of n)try{const t=await this.executeCommand(e,r,i);a.push(t),Object.assign(r,{it:t})}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}}return{targetElements:s,commandResults:a,executionCount:s.length*n.length}}async executeCommand(e,t,r){if(e&&"object"==typeof e&&"command"===e.type&&r)return await r(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}},Li(t,"TellCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());let Po=(()=>{let e,t,r=[ji({description:"Copy text or element content to the clipboard",syntax:["copy <source>","copy <source> to clipboard"],examples:['copy "Hello World"',"copy #code-snippet","copy my textContent"],sideEffects:["clipboard-write","custom-events"]}),Ii({name:"copy",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("copy command requires a source (text or element)");const n=await t.evaluate(e.args[0],r);let s="text";if(e.modifiers?.format){const n=await t.evaluate(e.modifiers.format,r);"html"!==n&&"text"!==n||(s=n)}return{source:n,format:s}}async execute(e,t){const{source:r,format:n="text"}=e,s=this.extractText(r,n,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(s),this.dispatchCopyEvent(t,"copy:success",{text:s,method:"clipboard-api"}),{success:!0,text:s,format:n,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(s))return this.dispatchCopyEvent(t,"copy:success",{text:s,method:"execCommand"}),{success:!0,text:s,format:n,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:s,error:"All copy methods failed"}),{success:!1,text:s,format:n,method:"fallback"}}extractText(e,t,r){if("string"==typeof e)return e;if(qi(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&qi(r.me)){const e=r.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,r){if(qi(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Li(t,"CopyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})();const No=Ri(Po),Io=Ri((()=>{let e,t,r=[ji({description:"Select a random element from a collection",syntax:["pick <item1>, <item2>, ...","pick from <array>"],examples:['pick "red", "green", "blue"',"pick from colors","pick 1, 2, 3, 4, 5"],sideEffects:["random-selection"]}),Ii({name:"pick",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(e.modifiers?.from){const n=await t.evaluate(e.modifiers.from,r);if(!Array.isArray(n))throw Error("pick from requires an array");if(0===n.length)throw Error("Cannot pick from empty array");return{array:n}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{items:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const{items:r,array:n}=e,s=r||n,i=r?"items":"array",a=Math.floor(Math.random()*s.length),o=s[a];return Object.assign(t,{it:o}),{selectedItem:o,selectedIndex:a,sourceLength:s.length,sourceType:i}}},Li(t,"PickCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})()),jo=Ri((()=>{let e,t,r=[ji({description:"Throw an error with a specified message",syntax:["throw <message>"],examples:['throw "Invalid input"','if not valid then throw "Validation failed"'],sideEffects:["error-throwing","execution-termination"]}),Ii({name:"throw",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],r)}}async execute(e,t){const{message:r}=e;let n;throw n=r instanceof Error?r:Error("string"==typeof r?r:r+""),n}},Li(t,"ThrowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());const Ro=Ri((()=>{let e,t,r=[ji({description:"Debug output for expressions with type information",syntax:["beep!","beep! <expression>","beep! <expression>, <expression>, ..."],examples:["beep!","beep! myValue","beep! me.id, me.className"],sideEffects:["console-output","debugging"]}),Ii({name:"beep",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return 0===e.args.length?{expressions:[]}:{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.expressions||[];if(0===r.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const n=[];console.group("🔔 beep! Debug Output");for(const e of r){const t=this.debugExpression(e);n.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:r.length,debugged:!0,outputs:n}}debugContext(e){console.group("🔔 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":qi(e)?"HTMLElement":e instanceof Element?"Element":e instanceof Node?"Node":e instanceof Error?"Error":e instanceof Date?"Date":e instanceof RegExp?"RegExp":typeof e}getRepresentation(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Array.isArray(e))return`Array(${e.length}) [${e.slice(0,3).map(e=>this.getRepresentation(e)).join(", ")}${e.length>3?"...":""}]`;if(qi(e)){const t=e;return`<${t.tagName.toLowerCase()}${t.id?"#"+t.id:""}${t.className?"."+t.className.split(" ").join("."):""}/>`}if(e instanceof Error)return"Error: "+e.message;if("string"==typeof e)return e.length>50?`"${e.substring(0,47)}..."`:`"${e}"`;if("object"==typeof e)try{const t=Object.keys(e);return`Object {${t.slice(0,3).join(", ")}${t.length>3?"...":""}}`}catch{return"[Object]"}return e+""}},Li(t,"BeepCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());class qo{constructor(){this.name="install"}get metadata(){return qo.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("install command requires a behavior name");const n=e.args[0];let s,i,a;if(s="identifier"===n?.type&&"string"==typeof n.name?n.name:await t.evaluate(n,r)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(s))throw Error(`Behavior name must be PascalCase (start with uppercase): "${s}"`);if(e.args.length>=2){const n=await t.evaluate(e.args[1],r);if(n&&"object"==typeof n&&!Array.isArray(n)){i=n;for(const e of Object.keys(i))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(a=await t.evaluate(e.modifiers.on,r)),{behaviorName:s,parameters:i,target:a}}async execute(e,t){const{behaviorName:r,parameters:n={},target:s}=e;try{const e=this.resolveTarget(s,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(r,t))throw Error(`Behavior "${r}" is not defined. Define it using the 'behavior' keyword before installing.`);const i=[];for(const s of e){const e=await this.installBehavior(r,s,n,t);i.push(e)}return{success:!0,behaviorName:r,installedCount:i.length,instances:i}}catch(e){throw Error(`Failed to install behavior "${r}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(qi(e))return[e];throw Error('No target specified and "me" is not available in context')}if(qi(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>qi(e));if(0===t.length)throw Error("Target array contains no valid HTMLElements");return t}if("string"==typeof e){if("me"===e){const e=t.me||t.locals.get("me");if(qi(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),r=Array.from(t).filter(e=>qi(e));if(0===r.length)throw Error(`No elements found matching selector: "${e}"`);return r}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>qi(e));if(0===t.length)throw Error("Target collection contains no valid HTMLElements");return t}if("object"==typeof e&&"element"in e){const t=e.element;if(qi(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+e)}behaviorExists(e,t){const r=t.locals.get("_behaviors");if(r&&"object"==typeof r){const t=r;if(t.has(e))return!0;if(t.resolve&&t.resolve(e))return!0}if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors){if(t.behaviors.has(e))return!0;if(t.behaviors.resolve&&t.behaviors.resolve(e))return!0}}return!1}async installBehavior(e,t,r,n){const s=n.locals.get("_behaviors");if(s&&"object"==typeof s){const n=s;if(n.install&&"function"==typeof n.install)return await n.install(e,t,r)}if("undefined"!=typeof globalThis){const n=globalThis._hyperscript;if(n?.behaviors?.install)return await n.behaviors.install(e,t,r)}throw Error("Behavior system not available in context")}}function _o(){return new qo}qo.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};const Mo=Ri((()=>{let e,t,r=[ji({description:"Move classes, attributes, and properties from one element to another",syntax:["take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"]}),Ii({name:"take",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(3>e.args.length)throw Error('take requires property, "from", and source');const n=await t.evaluate(e.args[0],r)+"";if("from"!==await t.evaluate(e.args[1],r))throw Error("take syntax: take <property> from <source>");const s=await t.evaluate(e.args[2],r);let i;if(8>e.args.length)e.args.length>3&&(i=await t.evaluate(e.args[3],r));else{const n=await Promise.all([3,4,5,6].map(n=>t.evaluate(e.args[n],r)));"and"===n[0]&&"put"===n[1]&&"it"===n[2]&&"on"===n[3]&&e.args[7]&&(i=await t.evaluate(e.args[7],r))}return!i&&e.modifiers?.on&&(i=await t.evaluate(e.modifiers.on,r)),{property:n,source:s,target:i}}async execute(e,t){const r=_i(e.source,t),n=_i(e.target?e.target:void 0,t),s=this.takeProperty(r,e.property);return this.putProperty(n,e.property,s),{targetElement:n,property:e.property,value:s}}takeProperty(e,t){const r=t.trim(),n=r.toLowerCase();if("class"===n||"classes"===n){const t=Array.from(e.classList);return e.className="",t}if(r.startsWith(".")){const t=r.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(r.startsWith("@")){const t=r.substring(1),n=e.getAttribute(t);return e.removeAttribute(t),n}if(r.startsWith("data-")){const t=e.getAttribute(r);return e.removeAttribute(r),t}if("id"===n){const t=e.id;return e.id="",t}if("title"===n){const t=e.title;return e.title="",t}if("value"===n&&"value"in e){const t=e.value;return e.value="",t}const s=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(r.includes("-")||s in e.style||r in e.style){let t;return s in e.style?(t=e.style[s],e.style[s]=""):r in e.style?(t=e.style[r],e.style[r]=""):(t=e.style.getPropertyValue(r),e.style.removeProperty(r)),t}const i=e.getAttribute(t);return null!==i?(e.removeAttribute(t),i):null}putProperty(e,t,r){if(null==r)return;const n=t.trim(),s=n.toLowerCase();if("class"===s||"classes"===s)return void(Array.isArray(r)?r.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof r&&(e.className=r));if(n.startsWith("."))return void(r&&e.classList.add(n.substring(1)));if(n.startsWith("@"))return void e.setAttribute(n.substring(1),r+"");if(n.startsWith("data-"))return void e.setAttribute(n,r+"");if("id"===s)return void(e.id=r+"");if("title"===s)return void(e.title=r+"");if("value"===s&&"value"in e)return void(e.value=r+"");const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());n.includes("-")||i in e.style||n in e.style?i in e.style?e.style[i]=r+"":n in e.style?e.style[n]=r+"":e.style.setProperty(n,r+""):e.setAttribute(t,r+"")}},Li(t,"TakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());class $o{constructor(){this.name="render"}get metadata(){return $o.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("render command requires a template");const n=await t.evaluate(e.args[0],r);let s;if(e.args.length>=3&&"with"===await t.evaluate(e.args[1],r)){const n=await t.evaluate(e.args[2],r);n&&"object"==typeof n&&(s=n)}if(!s&&e.modifiers?.with){const n=await t.evaluate(e.modifiers.with,r);n&&"object"==typeof n&&(s=n)}return{template:n,variables:s}}async execute(e,t){const{template:r,variables:n={}}=e,s=this.extractTemplateContent(r,t),i=this.createTemplateContext(t,n),a=[],o=await this.processTemplate(s,i,a),l=this.createDOMElement(o);return Object.assign(t,{it:l}),{element:l,rendered:o,directivesProcessed:a}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let r=e;if(!r.includes("<")&&!r.includes("$")){const e=this.resolveVariable(r,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(r=e)}const n=r.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return n?n[1]:r}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,r){const n=e.split("\n"),s=[];let i=0;for(;n.length>i;){const e=n[i].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:a}=await this.processRepeatDirective(n,i,t);s.push(a),i=e,r.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:a}=await this.processIfDirective(n,i,t,r);s.push(a),i=e,r.push("@if")}else if("@else"===e||"@end"===e)i++;else{const r=this.processVariableInterpolation(e,t);s.push(r),i++}}return s.join("\n")}async processRepeatDirective(e,t,r){const n=e[t].trim(),s=n.match(/^@repeat\s+in\s+(.+)$/);if(!s)throw Error("Invalid @repeat syntax: "+n);const i=this.evaluateExpression(s[1],r),{endIndex:a,blockContent:o}=this.extractDirectiveBlock(e,t+1),l=[];if(Array.isArray(i))for(const e of i){const t={...r,locals:new Map([...r.locals.entries(),["it",e]])},n=await this.processTemplate(o.join("\n"),t,[]);l.push(n)}return{nextIndex:a+1,rendered:l.join("\n")}}async processIfDirective(e,t,r,n){const s=e[t].trim(),i=s.match(/^@if\s+(.+)$/);if(!i)throw Error("Invalid @if syntax: "+s);const a=!!this.evaluateExpression(i[1],r),{endIndex:o,blockContent:l,elseContent:c}=this.extractIfElseBlock(e,t+1);let u="";return a?u=await this.processTemplate(l.join("\n"),r,[]):c.length>0&&(u=await this.processTemplate(c.join("\n"),r,[]),n.push("@else")),{nextIndex:o+1,rendered:u}}extractDirectiveBlock(e,t){const r=[];let n=1,s=t;for(;e.length>s&&n>0;){const t=e[s].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(n++,r.push(e[s])):"@end"===t?(n--,n>0&&r.push(e[s])):r.push(e[s]),s++}return{endIndex:s-1,blockContent:r}}extractIfElseBlock(e,t){const r=[],n=[];let s=1,i=t,a=!1;for(;e.length>i&&s>0;){const t=e[i].trim();if(t.startsWith("@if "))s++;else{if("@else"===t&&1===s){a=!0,i++;continue}if("@end"===t&&(s--,0===s))break}a?n.push(e[i]):r.push(e[i]),i++}return{endIndex:i,blockContent:r,elseContent:n}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=r.trim();if(e.startsWith("unescaped ")){const r=e.substring(10).trim();return(this.evaluateExpression(r,t)||"")+""}const n=this.evaluateExpression(e,t);return this.escapeHtml((n||"")+"")}catch(t){return console.warn(`Template interpolation error for ${r}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const r=Number(e);if(!isNaN(r)&&""!==e.trim())return r;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++){if("object"!=typeof n||null===n)return;n=n[r[e]]}return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}function Vo(){return new $o}$o.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};class Do extends xi{constructor(e={}){const t=e.registry||new hi;let r;e.registry||(t.register(Hi()),t.register(Wi()),t.register(ua()),t.register(pa()),t.register(ja()),t.register(Ra()),t.register(Da()),t.register(Ha()),t.register(Wa()),t.register(Ja()),t.register(Za()),t.register(Ya()),t.register(Ga()),t.register(eo()),t.register(to()),t.register(ro()),t.register(io()),t.register(lo()),t.register(mo()),t.register(ho()),t.register(fo()),t.register(yo()),t.register(vo()),t.register(bo()),t.register(wo()),t.register(ko()),t.register(Eo()),t.register(xo()),t.register(Co()),t.register(Ao()),t.register(ao()),t.register(So()),t.register(Lo()),t.register(Oo()),t.register(No()),t.register(Io()),t.register(jo()),t.register(Ro()),t.register(_o()),t.register(Mo()),t.register(Vo()),console.log("RuntimeExperimental: Registered 43 V2 commands (Phase 6 COMPLETE - All commands migrated)")),r=e.expressionEvaluator?e.expressionEvaluator:e.lazyLoad?new Ai({preload:e.expressionPreload||"core"}):new di;const n={registry:t,expressionEvaluator:r};void 0!==e.enableAsyncCommands&&(n.enableAsyncCommands=e.enableAsyncCommands),void 0!==e.commandTimeout&&(n.commandTimeout=e.commandTimeout),void 0!==e.enableErrorReporting&&(n.enableErrorReporting=e.enableErrorReporting),super(n)}}const Bo=Ri((()=>{let e,t,r=[ji({description:"Evaluate an expression and store the result in it",syntax:"get <expression>",examples:["get #my-dialog","get <button/>","get me.parentElement"],sideEffects:["context-mutation"]}),Ii({name:"get",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const n=e.args[0],s=await t.evaluate(n,r);return s instanceof NodeList&&1===s.length||Array.isArray(s)&&1===s.length?{value:s[0]}:{value:s}}execute(e,t){return t.it=e.value,Object.assign(t,{result:e.value}),{value:e.value}}validate(e){return"object"==typeof e&&null!==e&&"value"in e}},Li(t,"GetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Si(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ti(t,n)})(),t})());var Fo={to:"destination",into:"destination",from:"source",with:"style",by:"quantity",as:"method",on:"event",over:"duration",for:"duration"},zo=new Set(["to","from","into","with","at","in","of","as","by","before","after","without"]),Ho=new Set(["add","append","async","beep","break","call","continue","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),Uo=new Set(["then","else","end","and","or","not","if","unless","for","while","until","forever","times","each","index","in","to","from","into","with","without","of","at","by","as","matches","contains","is","exists","on","when","every","event","init","def","behavior","global","local","the","a","an","first","last","start","before","after"]),Wo=new Set(["click","dblclick","mousedown","mouseup","mouseenter","mouseleave","mouseover","mouseout","mousemove","keydown","keyup","keypress","focus","blur","change","input","submit","reset","load","unload","resize","scroll","touchstart","touchend","touchmove","touchcancel","dragstart","dragend","dragenter","dragleave","dragover","drop","contextmenu","wheel","pointerdown","pointerup","pointermove","ms","s"]),Jo=new Set(["and","or","not","is","exists","matches","contains","then","else"]),Ko=new Set(["true","false","null","undefined","it","me","my","result"]),Zo=new Set(["first","last","next","previous","prev","at","random","closest","parent","children","within","no","empty","some","starts with","ends with"]),Yo=new Set(["if","unless","when","where","もし","時に","ときに","どこで","如果","当","إذا","عندما","حيث","si","cuando","donde","wenn","wann","wo","quand","lorsque","où","quando","onde","eğer","zaman","nerede","ketika","saat","dimana","때","어디서","maypi","wakati","wapi"]),Go=new Set(["then","それから","那么","ثم","entonces","alors","dann","sonra","lalu","chayqa","kisha"]);function Xo(e,t,r={}){const{allowEnglishFallback:n=!0}=r,s=new Map,i=new Map,a=new Map,o=new Map,l=new Map,c=new Map,u=new Map,d=new Map,m=new Map,p=new Map;function h(e,t,r=!1){for(const[n,s]of Object.entries(e)){const e=s.toLowerCase();t.set(e,n.toLowerCase()),!r&&m.has(e)||m.set(e,n.toLowerCase()),p.set(n.toLowerCase(),s.toLowerCase())}}e.commands&&h(e.commands,s,!0),e.logical&&h(e.logical,o,!0),e.events&&h(e.events,a),e.values&&h(e.values,c),e.temporal&&h(e.temporal,l),e.modifiers&&h(e.modifiers,i),e.attributes&&h(e.attributes,u),e.expressions&&h(e.expressions,d);const f=new Set(s.keys()),y=new Set(m.keys());if(n){for(const e of Ho)f.add(e);for(const e of Uo)y.add(e);for(const e of Wo)y.add(e)}return{locale:t,resolve(e){const t=e.toLowerCase(),r=m.get(t);if(void 0!==r)return r;if(n){if(Ho.has(t)||Uo.has(t))return t;if(Wo.has(t))return t}},isCommand(e){const t=e.toLowerCase();return!!s.has(t)||!(!n||!Ho.has(t))},isKeyword(e){const t=e.toLowerCase();return!!(i.has(t)||o.has(t)||l.has(t)||c.has(t))||!(!n||!Uo.has(t))},isEvent(e){const t=e.toLowerCase();return!!a.has(t)||!!Wo.has(t)},isModifier(e){const t=e.toLowerCase();return i.has(t)||n&&zo.has(t)},isLogical(e){const t=e.toLowerCase();return o.has(t)||n&&Jo.has(t)},isValue(e){const t=e.toLowerCase();return c.has(t)||n&&Ko.has(t)},isExpression(e){const t=e.toLowerCase();return d.has(t)||n&&Zo.has(t)},getCommands:()=>Array.from(f),getKeywords:()=>Array.from(y),toLocale:e=>p.get(e.toLowerCase())}}function Qo(){return{locale:"en",resolve(e){const t=e.toLowerCase();if(Ho.has(t)||Uo.has(t)||Wo.has(t))return t},isCommand:e=>Ho.has(e.toLowerCase()),isKeyword:e=>Uo.has(e.toLowerCase()),isEvent:e=>Wo.has(e.toLowerCase()),isModifier:e=>zo.has(e.toLowerCase()),isLogical:e=>Jo.has(e.toLowerCase()),isValue:e=>Ko.has(e.toLowerCase()),isExpression:e=>Zo.has(e.toLowerCase()),getCommands:()=>Array.from(Ho),getKeywords:()=>Array.from(Uo),toLocale:e=>e.toLowerCase()}}var el={commands:{on:"en",tell:"decir",trigger:"disparar",send:"enviar",take:"tomar",put:"poner",set:"establecer",get:"obtener",add:"agregar",remove:"quitar",toggle:"alternar",hide:"ocultar",show:"mostrar",if:"si",unless:"menos",repeat:"repetir",for:"para",while:"mientras",until:"hasta",continue:"continuar",break:"romper",halt:"detener",wait:"esperar",fetch:"buscar",call:"llamar",return:"retornar",make:"hacer",log:"registrar",throw:"lanzar",catch:"atrapar",measure:"medir",transition:"transición",increment:"incrementar",decrement:"decrementar",default:"predeterminar",go:"ir",pushUrl:"pushUrl",replaceUrl:"reemplazarUrl",copy:"copiar",pick:"escoger",beep:"pitido",js:"js",async:"asíncrono",render:"renderizar",swap:"intercambiar",morph:"transformar",settle:"estabilizar",append:"añadir",exit:"salir",install:"instalar"},modifiers:{to:"a",from:"de",into:"en",with:"con",at:"en",in:"en",of:"de",as:"como",by:"por",before:"antes",after:"después",over:"sobre",under:"bajo",between:"entre",through:"través",without:"sin"},events:{click:"clic",dblclick:"dobleclic",mousedown:"ratónabajo",mouseup:"ratónarriba",mouseenter:"ratónentrar",mouseleave:"ratónsalir",mouseover:"ratónencima",mouseout:"ratónfuera",mousemove:"ratónmover",keydown:"teclaabajo",keyup:"teclaarriba",keypress:"teclapresar",focus:"enfocar",blur:"desenfocar",change:"cambiar",input:"entrada",submit:"enviar",reset:"reiniciar",load:"cargar",unload:"descargar",resize:"redimensionar",scroll:"desplazar",touchstart:"toqueempezar",touchend:"toqueterminar",touchmove:"toquemover",touchcancel:"toquecancelar"},logical:{when:"cuando",where:"donde",and:"y",or:"o",not:"no",is:"es",exists:"existe",matches:"coincide",contains:"contiene",includes:"incluye",equals:"iguala",has:"tiene",have:"tengo",then:"entonces",else:"sino",otherwise:"delocontrario",end:"fin"},temporal:{seconds:"segundos",second:"segundo",milliseconds:"milisegundos",millisecond:"milisegundo",minutes:"minutos",minute:"minuto",hours:"horas",hour:"hora",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"verdadero",false:"falso",null:"nulo",undefined:"indefinido",it:"ello",its:"su",me:"yo",my:"mi",you:"tu",your:"tu",yourself:"ti mismo",myself:"yo mismo",element:"elemento",target:"objetivo",detail:"detalle",event:"evento",window:"ventana",document:"documento",body:"cuerpo",result:"resultado",value:"valor"},attributes:{class:"clase",classes:"clases",style:"estilo",styles:"estilos",attribute:"atributo",attributes:"atributos",property:"propiedad",properties:"propiedades"},expressions:{first:"primero",last:"último",next:"siguiente",previous:"anterior",prev:"ant",at:"en",random:"aleatorio",closest:"máscercano",parent:"padre",children:"hijos",within:"dentro",no:"ningún",empty:"vacío",some:"algún","starts with":"empieza con","ends with":"termina con"}},tl=Xo(el,"es",{allowEnglishFallback:!0}),rl={commands:{on:"で",tell:"伝える",trigger:"引き金",send:"送る",take:"取る",put:"置く",set:"設定",get:"取得",add:"追加",remove:"削除",toggle:"切り替え",hide:"隠す",show:"表示",if:"もし",unless:"でなければ",repeat:"繰り返し",for:"ために",while:"の間",until:"まで",continue:"続ける",break:"中断",halt:"停止",wait:"待つ",fetch:"取得",call:"呼び出し",return:"戻る",make:"作る",log:"記録",throw:"投げる",catch:"捕まえる",measure:"測定",transition:"遷移",increment:"増加",decrement:"減少",default:"既定",go:"移動",pushUrl:"URLプッシュ",replaceUrl:"URL置換",copy:"コピー",pick:"選択",beep:"ビープ",js:"JS実行",async:"非同期",render:"描画",swap:"交換",morph:"変形",settle:"安定",append:"末尾追加",exit:"終了",install:"インストール"},modifiers:{to:"に",from:"から",into:"へ",with:"と",at:"で",in:"の中",of:"の",as:"として",by:"によって",before:"前に",after:"後に",over:"上に",under:"下に",between:"間に",through:"通して",without:"なしで"},events:{click:"クリック",dblclick:"ダブルクリック",mousedown:"マウス押下",mouseup:"マウス解放",mouseenter:"マウス入る",mouseleave:"マウス離れる",mouseover:"マウス上",mouseout:"マウス外",mousemove:"マウス移動",keydown:"キー押下",keyup:"キー解放",keypress:"キー押す",focus:"フォーカス",blur:"ぼかし",change:"変更",input:"入力",submit:"送信",reset:"リセット",load:"読み込み",unload:"読み込み解除",resize:"サイズ変更",scroll:"スクロール",touchstart:"タッチ開始",touchend:"タッチ終了",touchmove:"タッチ移動",touchcancel:"タッチキャンセル"},logical:{when:"とき",where:"どこ",and:"そして",or:"または",not:"ではない",is:"である",exists:"存在する",matches:"一致する",contains:"含む",includes:"含める",equals:"等しい",has:"ある",have:"ある",then:"それから",else:"そうでなければ",otherwise:"そうでなければ",end:"終わり"},temporal:{seconds:"秒",second:"秒",milliseconds:"ミリ秒",millisecond:"ミリ秒",minutes:"分",minute:"分",hours:"時間",hour:"時間",ms:"ms",s:"秒",min:"分",h:"時"},values:{true:"真",false:"偽",null:"null",undefined:"未定義",it:"それ",its:"その",me:"私",my:"私の",you:"あなた",your:"あなたの",yourself:"あなた自身",myself:"私自身",element:"要素",target:"対象",detail:"詳細",event:"イベント",window:"ウィンドウ",document:"ドキュメント",body:"ボディ",result:"結果",value:"値"},attributes:{class:"クラス",classes:"クラス群",style:"スタイル",styles:"スタイル群",attribute:"属性",attributes:"属性群",property:"プロパティ",properties:"プロパティ群"},expressions:{first:"最初",last:"最後",next:"次",previous:"前",prev:"前",at:"で",random:"ランダム",closest:"最も近い",parent:"親",children:"子",within:"以内",no:"ない",empty:"空",some:"いくつか","starts with":"で始まる","ends with":"で終わる"}},nl=Xo(rl,"ja",{allowEnglishFallback:!0}),sl={commands:{on:"sur",tell:"dire",trigger:"déclencher",send:"envoyer",take:"prendre",put:"mettre",set:"définir",get:"obtenir",add:"ajouter",remove:"supprimer",toggle:"basculer",hide:"cacher",show:"montrer",if:"si",unless:"saufsi",repeat:"répéter",for:"pour",while:"tantque",until:"jusquà",continue:"continuer",break:"arrêter",halt:"stopper",wait:"attendre",fetch:"récupérer",call:"appeler",return:"retourner",make:"créer",log:"enregistrer",throw:"lancer",catch:"attraper",measure:"mesurer",transition:"transition",increment:"incrémenter",decrement:"décrémenter",default:"défaut",go:"aller",pushUrl:"pousserUrl",replaceUrl:"remplacerUrl",copy:"copier",pick:"choisir",beep:"bip",js:"js",async:"asynchrone",render:"rendu",swap:"échanger",morph:"transformer",settle:"stabiliser",append:"ajouter",exit:"sortir",install:"installer"},modifiers:{to:"à",from:"de",into:"dans",with:"avec",at:"à",in:"en",of:"de",as:"comme",by:"par",before:"avant",after:"après",over:"sur",under:"sous",between:"entre",through:"à travers",without:"sans"},events:{click:"clic",dblclick:"doubleclic",mousedown:"sourisappuyée",mouseup:"sourisrelâchée",mouseenter:"sourisentrer",mouseleave:"sourissortir",mouseover:"sourissur",mouseout:"sourisdehors",mousemove:"sourisbouger",keydown:"toucheappuyée",keyup:"toucherelâchée",keypress:"touchepressée",focus:"focus",blur:"flou",change:"changer",input:"saisie",submit:"soumettre",reset:"réinitialiser",load:"charger",unload:"décharger",resize:"redimensionner",scroll:"défiler",touchstart:"touchercommencer",touchend:"toucherfin",touchmove:"toucherbouger",touchcancel:"toucherannuler"},logical:{when:"quand",where:"où",and:"et",or:"ou",not:"non",is:"est",exists:"existe",matches:"correspond",contains:"contient",includes:"inclut",equals:"égale",has:"a",have:"ai",then:"alors",else:"sinon",otherwise:"autrement",end:"fin"},temporal:{seconds:"secondes",second:"seconde",milliseconds:"millisecondes",millisecond:"milliseconde",minutes:"minutes",minute:"minute",hours:"heures",hour:"heure",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"vrai",false:"faux",null:"nul",undefined:"indéfini",it:"ça",its:"son",me:"moi",my:"mon",you:"tu",your:"ton",yourself:"toi-même",myself:"moi-même",element:"élément",target:"cible",detail:"détail",event:"événement",window:"fenêtre",document:"document",body:"corps",result:"résultat",value:"valeur"},attributes:{class:"classe",classes:"classes",style:"style",styles:"styles",attribute:"attribut",attributes:"attributs",property:"propriété",properties:"propriétés"},expressions:{first:"premier",last:"dernier",next:"suivant",previous:"précédent",prev:"préc",at:"à",random:"aléatoire",closest:"plusproche",parent:"parent",children:"enfants",within:"dans",no:"aucun",empty:"vide",some:"quelques","starts with":"commence par","ends with":"finit par"}},il=Xo(sl,"fr",{allowEnglishFallback:!0}),al={commands:{on:"bei",tell:"sagen",trigger:"auslösen",send:"senden",take:"nehmen",put:"setzen",set:"festlegen",get:"erhalten",add:"hinzufügen",remove:"entfernen",toggle:"umschalten",hide:"verstecken",show:"zeigen",if:"wenn",unless:"wennnicht",repeat:"wiederholen",for:"für",while:"während",until:"bis",continue:"weiter",break:"unterbrechen",halt:"anhalten",wait:"warten",fetch:"holen",call:"aufrufen",return:"zurückgeben",make:"erstellen",log:"protokollieren",throw:"werfen",catch:"fangen",measure:"messen",transition:"übergang",increment:"erhöhen",decrement:"verringern",default:"standard",go:"gehen",pushUrl:"urlHinzufügen",replaceUrl:"urlErsetzen",copy:"kopieren",pick:"auswählen",beep:"piepton",js:"js",async:"asynchron",render:"rendern",swap:"tauschen",morph:"verwandeln",settle:"stabilisieren",append:"anhängen",exit:"beenden",install:"installieren"},modifiers:{to:"zu",from:"von",into:"in",with:"mit",at:"bei",in:"in",of:"von",as:"als",by:"durch",before:"vor",after:"nach",over:"über",under:"unter",between:"zwischen",through:"durch",without:"ohne"},events:{click:"klick",dblclick:"doppelklick",mousedown:"mausunten",mouseup:"mausoben",mouseenter:"mauseintreten",mouseleave:"mausverlassen",mouseover:"mausüber",mouseout:"maushinaus",mousemove:"mausbewegen",keydown:"tasteunten",keyup:"tasteoben",keypress:"tastedrücken",focus:"fokus",blur:"unscharf",change:"ändern",input:"eingabe",submit:"absenden",reset:"zurücksetzen",load:"laden",unload:"entladen",resize:"größeändern",scroll:"scrollen",touchstart:"berührungstart",touchend:"berührungend",touchmove:"berührungbewegen",touchcancel:"berührungabbrechen"},logical:{when:"wenn",where:"wo",and:"und",or:"oder",not:"nicht",is:"ist",exists:"existiert",matches:"passt",contains:"enthält",includes:"beinhaltet",equals:"gleicht",has:"hat",have:"habe",then:"dann",else:"sonst",otherwise:"andernfalls",end:"ende"},temporal:{seconds:"sekunden",second:"sekunde",milliseconds:"millisekunden",millisecond:"millisekunde",minutes:"minuten",minute:"minute",hours:"stunden",hour:"stunde",ms:"ms",s:"s",min:"min",h:"std"},values:{true:"wahr",false:"falsch",null:"null",undefined:"undefiniert",it:"es",its:"sein",me:"ich",my:"mein",you:"du",your:"dein",yourself:"dich selbst",myself:"ich selbst",element:"element",target:"ziel",detail:"detail",event:"ereignis",window:"fenster",document:"dokument",body:"körper",result:"ergebnis",value:"wert"},attributes:{class:"klasse",classes:"klassen",style:"stil",styles:"stile",attribute:"attribut",attributes:"attribute",property:"eigenschaft",properties:"eigenschaften"},expressions:{first:"erste",last:"letzte",next:"nächste",previous:"vorherige",prev:"vorh",at:"bei",random:"zufällig",closest:"nächste",parent:"elternteil",children:"kinder",within:"innerhalb",no:"kein",empty:"leer",some:"einige","starts with":"beginnt mit","ends with":"endet mit"}},ol=Xo(al,"de",{allowEnglishFallback:!0}),ll={commands:{on:"على",tell:"أخبر",trigger:"تشغيل",send:"أرسل",take:"خذ",put:"ضع",set:"اضبط",get:"احصل",add:"أضف",remove:"احذف",toggle:"بدل",hide:"اخف",show:"اظهر",if:"إذا",unless:"إلا إذا",repeat:"كرر",for:"لكل",while:"بينما",until:"حتى",continue:"واصل",break:"توقف",halt:"أوقف",wait:"انتظر",fetch:"احضر",call:"استدع",return:"ارجع",make:"اصنع",log:"سجل",throw:"ارم",catch:"التقط",measure:"قس",transition:"انتقال",increment:"زِد",decrement:"أنقص",default:"افتراضي",go:"اذهب",pushUrl:"ادفع رابط",replaceUrl:"استبدل رابط",copy:"انسخ",pick:"اختر",beep:"صفّر",js:"جافاسكربت",async:"متزامن",render:"ارسم",swap:"بدّل",morph:"حوّل",settle:"استقر",append:"ألحق",exit:"اخرج",install:"ثبّت"},modifiers:{to:"إلى",from:"من",into:"في",with:"مع",at:"عند",in:"في",of:"من",as:"كـ",by:"بواسطة",before:"قبل",after:"بعد",over:"فوق",under:"تحت",between:"بين",through:"عبر",without:"بدون"},events:{click:"نقر",dblclick:"نقر مزدوج",mousedown:"فأرة أسفل",mouseup:"فأرة أعلى",mouseenter:"فأرة دخول",mouseleave:"فأرة خروج",mouseover:"فأرة فوق",mouseout:"فأرة خارج",mousemove:"فأرة تحرك",keydown:"مفتاح أسفل",keyup:"مفتاح أعلى",keypress:"مفتاح ضغط",focus:"تركيز",blur:"ضبابية",change:"تغيير",input:"إدخال",submit:"إرسال",reset:"إعادة تعيين",load:"تحميل",unload:"إلغاء تحميل",resize:"تغيير حجم",scroll:"تمرير",touchstart:"بداية لمس",touchend:"نهاية لمس",touchmove:"تحرك لمس",touchcancel:"إلغاء لمس"},logical:{when:"عندما",where:"أين",and:"و",or:"أو",not:"ليس",is:"هو",exists:"موجود",matches:"يطابق",contains:"يحتوي",includes:"يشمل",equals:"يساوي",has:"لديه",have:"لدي",then:"ثم",else:"وإلا",otherwise:"خلاف ذلك",end:"النهاية"},temporal:{seconds:"ثوانِ",second:"ثانية",milliseconds:"ميلي ثانية",millisecond:"ميلي ثانية",minutes:"دقائق",minute:"دقيقة",hours:"ساعات",hour:"ساعة",ms:"م.ث",s:"ث",min:"د",h:"س"},values:{true:"صحيح",false:"خطأ",null:"فارغ",undefined:"غير معرف",it:"هو",its:"له",me:"أنا",my:"لي",myself:"نفسي",you:"أنت",your:"لك",yourself:"نفسك",element:"عنصر",target:"هدف",detail:"تفاصيل",event:"حدث",window:"نافذة",document:"وثيقة",body:"جسم",result:"نتيجة",value:"قيمة"},attributes:{class:"فئة",classes:"فئات",style:"أسلوب",styles:"أساليب",attribute:"خاصية",attributes:"خصائص",property:"خاصية",properties:"خصائص"},expressions:{first:"أول",last:"آخر",next:"التالي",previous:"السابق",prev:"سابق",at:"عند",random:"عشوائي",closest:"الأقرب",parent:"والد",children:"أطفال",within:"داخل",no:"لا يوجد",empty:"فارغ",some:"بعض","starts with":"يبدأ بـ","ends with":"ينتهي بـ"}},cl=Xo(ll,"ar",{allowEnglishFallback:!0}),ul={commands:{on:"에",tell:"말하다",trigger:"트리거",send:"보내다",take:"가져오다",put:"넣다",set:"설정",get:"얻다",add:"추가",remove:"제거",toggle:"토글",hide:"숨기다",show:"보이다",if:"만약",unless:"아니면",repeat:"반복",for:"동안",while:"동안",until:"까지",continue:"계속",break:"중단",halt:"정지",wait:"대기",fetch:"가져오기",call:"호출",return:"반환",make:"만들다",log:"로그",throw:"던지다",catch:"잡다",measure:"측정",transition:"전환",increment:"증가",decrement:"감소",default:"기본값",go:"이동",pushUrl:"URL푸시",replaceUrl:"URL교체",copy:"복사",pick:"선택",beep:"비프",js:"JS실행",async:"비동기",render:"렌더링",swap:"교환",morph:"변형",settle:"안정",append:"추가",exit:"종료",install:"설치"},modifiers:{to:"에",from:"에서",into:"으로",with:"와",at:"에",in:"안에",of:"의",as:"로",by:"에의해",before:"전에",after:"후에",over:"위에",under:"아래",between:"사이",through:"통해",without:"없이"},events:{click:"클릭",dblclick:"더블클릭",mousedown:"마우스다운",mouseup:"마우스업",mouseenter:"마우스엔터",mouseleave:"마우스리브",mouseover:"마우스오버",mouseout:"마우스아웃",mousemove:"마우스무브",keydown:"키다운",keyup:"키업",keypress:"키프레스",focus:"포커스",blur:"블러",change:"변경",input:"입력",submit:"제출",reset:"리셋",load:"로드",unload:"언로드",resize:"리사이즈",scroll:"스크롤",touchstart:"터치시작",touchend:"터치종료",touchmove:"터치이동",touchcancel:"터치취소"},logical:{when:"때",where:"어디",and:"그리고",or:"또는",not:"아니",is:"이다",exists:"존재",matches:"일치",contains:"포함",includes:"포함하다",equals:"같다",has:"있다",have:"있다",then:"그러면",else:"아니면",otherwise:"그렇지않으면",end:"끝"},temporal:{seconds:"초",second:"초",milliseconds:"밀리초",millisecond:"밀리초",minutes:"분",minute:"분",hours:"시간",hour:"시간",ms:"ms",s:"초",min:"분",h:"시"},values:{true:"참",false:"거짓",null:"널",undefined:"정의안됨",it:"그것",its:"그것의",me:"나",my:"내",myself:"나자신",you:"너",your:"네",yourself:"너자신",element:"요소",target:"대상",detail:"세부",event:"이벤트",window:"창",document:"문서",body:"바디",result:"결과",value:"값"},attributes:{class:"클래스",classes:"클래스들",style:"스타일",styles:"스타일들",attribute:"속성",attributes:"속성들",property:"프로퍼티",properties:"프로퍼티들"},expressions:{first:"첫번째",last:"마지막",next:"다음",previous:"이전",prev:"이전",at:"에서",random:"무작위",closest:"가장가까운",parent:"부모",children:"자식",within:"이내",no:"없음",empty:"비어있는",some:"일부","starts with":"로시작","ends with":"로끝나는"}},dl=Xo(ul,"ko",{allowEnglishFallback:!0}),ml={commands:{on:"当",tell:"告诉",trigger:"触发",send:"发送",take:"获取",put:"放置",set:"设置",get:"获得",add:"添加",remove:"移除",toggle:"切换",hide:"隐藏",show:"显示",if:"如果",unless:"除非",repeat:"重复",for:"为",while:"当",until:"直到",continue:"继续",break:"中断",halt:"停止",wait:"等待",fetch:"获取",call:"调用",return:"返回",make:"制作",log:"日志",throw:"抛出",catch:"捕获",measure:"测量",transition:"过渡",increment:"增加",decrement:"减少",default:"默认",go:"前往",pushUrl:"推送网址",replaceUrl:"替换网址",copy:"复制",pick:"选取",beep:"蜂鸣",js:"JS执行",async:"异步",render:"渲染",swap:"交换",morph:"变形",settle:"稳定",append:"追加",exit:"退出",install:"安装"},modifiers:{to:"到",from:"从",into:"进入",with:"与",at:"在",in:"在",of:"的",as:"作为",by:"通过",before:"之前",after:"之后",over:"在上",under:"在下",between:"之间",through:"通过",without:"没有"},events:{click:"点击",dblclick:"双击",mousedown:"鼠标按下",mouseup:"鼠标抬起",mouseenter:"鼠标进入",mouseleave:"鼠标离开",mouseover:"鼠标悬停",mouseout:"鼠标移出",mousemove:"鼠标移动",keydown:"按键按下",keyup:"按键抬起",keypress:"按键",focus:"聚焦",blur:"失焦",change:"改变",input:"输入",submit:"提交",reset:"重置",load:"加载",unload:"卸载",resize:"调整大小",scroll:"滚动",touchstart:"触摸开始",touchend:"触摸结束",touchmove:"触摸移动",touchcancel:"触摸取消"},logical:{when:"当",where:"哪里",and:"和",or:"或",not:"非",is:"是",exists:"存在",matches:"匹配",contains:"包含",includes:"包括",equals:"等于",has:"有",have:"有",then:"那么",else:"否则",otherwise:"要不然",end:"结束"},temporal:{seconds:"秒",second:"秒",milliseconds:"毫秒",millisecond:"毫秒",minutes:"分钟",minute:"分钟",hours:"小时",hour:"小时",ms:"毫秒",s:"秒",min:"分",h:"时"},values:{true:"真",false:"假",null:"空",undefined:"未定义",it:"它",its:"它的",me:"我",my:"我的",myself:"我自己",you:"你",your:"你的",yourself:"你自己",element:"元素",target:"目标",detail:"详情",event:"事件",window:"窗口",document:"文档",body:"主体",result:"结果",value:"值"},attributes:{class:"类",classes:"类别",style:"样式",styles:"样式集",attribute:"属性",attributes:"属性集",property:"特性",properties:"特性集"},expressions:{first:"第一个",last:"最后一个",next:"下一个",previous:"上一个",prev:"上个",at:"在",random:"随机",closest:"最近的",parent:"父级",children:"子级",within:"之内",no:"没有",empty:"空的",some:"一些","starts with":"以开头","ends with":"以结尾"}},pl=Xo(ml,"zh",{allowEnglishFallback:!0}),hl={commands:{on:"üzerinde",tell:"söyle",trigger:"tetikle",send:"gönder",take:"al",put:"koy",set:"ayarla",get:"al",add:"ekle",remove:"kaldır",toggle:"değiştir",hide:"gizle",show:"göster",if:"eğer",unless:"değilse",repeat:"tekrarla",for:"için",while:"iken",until:"kadar",continue:"devam",break:"dur",halt:"durdur",wait:"bekle",fetch:"getir",call:"çağır",return:"dön",make:"yap",log:"kaydet",throw:"fırlat",catch:"yakala",measure:"ölç",transition:"geçiş",increment:"artır",decrement:"azalt",default:"varsayılan",go:"git",pushUrl:"urlEkle",replaceUrl:"urlDeğiştir",copy:"kopyala",pick:"seç",beep:"bip",js:"js",async:"asenkron",render:"render",swap:"takas",morph:"dönüştür",settle:"sabitlen",append:"ekle",exit:"çık",install:"kur"},modifiers:{to:"e",from:"den",into:"içine",with:"ile",at:"de",in:"içinde",of:"nin",as:"olarak",by:"tarafından",before:"önce",after:"sonra",over:"üzerinde",under:"altında",between:"arasında",through:"boyunca",without:"olmadan"},events:{click:"tıklama",dblclick:"çift_tıklama",mousedown:"fare_bas",mouseup:"fare_bırak",mouseenter:"fare_gir",mouseleave:"fare_çık",mouseover:"fare_üstü",mouseout:"fare_dışı",mousemove:"fare_hareket",keydown:"tuş_bas",keyup:"tuş_bırak",keypress:"tuş_basım",focus:"odak",blur:"bulanık",change:"değişim",input:"giriş",submit:"gönder",reset:"sıfırla",load:"yükle",unload:"yükle_kaldır",resize:"boyut_değiştir",scroll:"kaydır",touchstart:"dokunma_başla",touchend:"dokunma_bitir",touchmove:"dokunma_hareket",touchcancel:"dokunma_iptal"},logical:{when:"iken",where:"nerede",and:"ve",or:"veya",not:"değil",is:"dir",exists:"var",matches:"eşleşir",contains:"içerir",includes:"dahil",equals:"eşittir",has:"var",have:"var",then:"sonra",else:"yoksa",otherwise:"aksi_halde",end:"son"},temporal:{seconds:"saniye",second:"saniye",milliseconds:"milisaniye",millisecond:"milisaniye",minutes:"dakika",minute:"dakika",hours:"saat",hour:"saat",ms:"ms",s:"s",min:"dk",h:"sa"},values:{true:"doğru",false:"yanlış",null:"boş",undefined:"tanımsız",it:"o",its:"onun",me:"ben",my:"benim",myself:"kendim",you:"sen",your:"senin",yourself:"kendin",element:"öğe",target:"hedef",detail:"detay",event:"olay",window:"pencere",document:"belge",body:"gövde",result:"sonuç",value:"değer"},attributes:{class:"sınıf",classes:"sınıflar",style:"stil",styles:"stiller",attribute:"özellik",attributes:"özellikler",property:"özellik",properties:"özellikler"},expressions:{first:"ilk",last:"son",next:"sonraki",previous:"önceki",prev:"önc",at:"de",random:"rastgele",closest:"en_yakın",parent:"ebeveyn",children:"çocuklar",within:"içinde",no:"yok",empty:"boş",some:"bazı","starts with":"ile başlar","ends with":"ile biter"}},fl=Xo(hl,"tr",{allowEnglishFallback:!0}),yl={commands:{on:"pada",tell:"katakan",trigger:"picu",send:"kirim",take:"ambil",put:"taruh",set:"atur",get:"dapatkan",add:"tambah",remove:"hapus",toggle:"ganti",hide:"sembunyikan",show:"tampilkan",if:"jika",unless:"kecuali",repeat:"ulangi",for:"untuk",while:"selama",until:"sampai",continue:"lanjutkan",break:"hentikan",halt:"berhenti",wait:"tunggu",fetch:"ambil",call:"panggil",return:"kembali",make:"buat",log:"catat",throw:"lempar",catch:"tangkap",measure:"ukur",transition:"transisi",increment:"tambahkan",decrement:"kurangi",default:"bawaan",go:"pergi",pushUrl:"tambahUrl",replaceUrl:"gantiUrl",copy:"salin",pick:"pilih",beep:"bunyi",js:"js",async:"asinkron",render:"tampilkan",swap:"tukar",morph:"ubah_bentuk",settle:"stabil",append:"tambah_akhir",exit:"keluar",install:"pasang"},modifiers:{to:"ke",from:"dari",into:"ke_dalam",with:"dengan",at:"di",in:"dalam",of:"dari",as:"sebagai",by:"oleh",before:"sebelum",after:"setelah",over:"di_atas",under:"di_bawah",between:"antara",through:"melalui",without:"tanpa"},events:{click:"klik",dblclick:"klik_ganda",mousedown:"tekan_mouse",mouseup:"lepas_mouse",mouseenter:"mouse_masuk",mouseleave:"mouse_keluar",mouseover:"mouse_atas",mouseout:"mouse_luar",mousemove:"gerak_mouse",keydown:"tekan_tombol",keyup:"lepas_tombol",keypress:"pencet_tombol",focus:"fokus",blur:"blur",change:"ubah",input:"masukan",submit:"kirim",reset:"reset",load:"muat",unload:"bongkar",resize:"ubah_ukuran",scroll:"gulir",touchstart:"mulai_sentuh",touchend:"akhir_sentuh",touchmove:"gerak_sentuh",touchcancel:"batal_sentuh"},logical:{when:"ketika",where:"di_mana",and:"dan",or:"atau",not:"bukan",is:"adalah",exists:"ada",matches:"cocok",contains:"berisi",includes:"termasuk",equals:"sama",has:"punya",have:"punya",then:"lalu",else:"lainnya",otherwise:"sebaliknya",end:"akhir"},temporal:{seconds:"detik",second:"detik",milliseconds:"milidetik",millisecond:"milidetik",minutes:"menit",minute:"menit",hours:"jam",hour:"jam",ms:"ms",s:"d",min:"mnt",h:"j"},values:{true:"benar",false:"salah",null:"kosong",undefined:"tidak_terdefinisi",it:"itu",its:"miliknya",me:"saya",my:"saya punya",myself:"saya sendiri",you:"kamu",your:"kamu punya",yourself:"kamu sendiri",element:"elemen",target:"target",detail:"detail",event:"peristiwa",window:"jendela",document:"dokumen",body:"badan",result:"hasil",value:"nilai"},attributes:{class:"kelas",classes:"kelas_kelas",style:"gaya",styles:"gaya_gaya",attribute:"atribut",attributes:"atribut_atribut",property:"properti",properties:"properti_properti"},expressions:{first:"pertama",last:"terakhir",next:"berikutnya",previous:"sebelumnya",prev:"sblm",at:"di",random:"acak",closest:"terdekat",parent:"induk",children:"anak_anak",within:"dalam",no:"tidak_ada",empty:"kosong",some:"beberapa","starts with":"dimulai dengan","ends with":"diakhiri dengan"}},gl=Xo(yl,"id",{allowEnglishFallback:!0}),vl={commands:{on:"kaqpi",tell:"niy",trigger:"kichay",send:"kachay",take:"hurquy",put:"churay",set:"churay",get:"chaskiy",add:"yapay",remove:"qichuy",toggle:"tikray",hide:"pakay",show:"rikuchiy",if:"sichus",unless:"mana_sichus",repeat:"kutichiy",for:"rayku",while:"kay_kaq",until:"hayk_akama",continue:"purichiy",break:"p_akiy",halt:"sayay",wait:"suyay",fetch:"apamuy",call:"qayay",return:"kutimuy",make:"ruray",log:"qillqay",throw:"wikchuy",catch:"hapsiy",measure:"tupuy",transition:"tikray",increment:"yapay",decrement:"pisiyachiy",default:"ñawpaq_kaq",go:"riy",pushUrl:"url_tanqay",replaceUrl:"url_tikray",copy:"qillqay",pick:"akllay",beep:"waqay",js:"js",async:"mana_suyaspa",render:"rikuchiy",swap:"rantin_tikray",morph:"tikrachiy",settle:"tiyay",append:"qhipaman_yapay",exit:"lluqsiy",install:"churay"},modifiers:{to:"man",from:"manta",into:"ukupi",with:"wan",at:"pi",in:"ukupi",of:"pa",as:"hina",by:"rayku",before:"ñawpaqpi",after:"qhepapi",over:"hawapi",under:"urapi",between:"chawpipi",through:"pasaspa",without:"mana"},events:{click:"ñitiy",dblclick:"iskay_ñitiy",mousedown:"rat_ñitiy",mouseup:"rat_huqariy",mouseenter:"rat_yaykuy",mouseleave:"rat_lluqsiy",mouseover:"rat_hawapi",mouseout:"rat_hawamanta",mousemove:"rat_kuyuy",keydown:"yupana_ñitiy",keyup:"yupana_huqariy",keypress:"yupana_ñitana",focus:"qhaway",blur:"paqariy",change:"tikray",input:"yaykuchiy",submit:"kachay",reset:"qallariy",load:"apakuy",unload:"urmay",resize:"hatun_kay",scroll:"kunray",touchstart:"llamiy_qallay",touchend:"llamiy_tukuy",touchmove:"llamiy_kuyuy",touchcancel:"llamiy_hark_ay"},logical:{when:"maykama",where:"maypi",and:"chaymanta",or:"utaq",not:"mana",is:"kanqa",exists:"tiyan",matches:"tupan",contains:"ukupi_kan",includes:"churasqa",equals:"kikin",has:"kachkan",have:"kachkani",then:"chayqa",else:"mana_chayqa",otherwise:"huk_kaqpi",end:"tukuy"},temporal:{seconds:"sikundukuna",second:"sikundu",milliseconds:"iskay_paqta_sikundukuna",millisecond:"iskay_paqta_sikundu",minutes:"minutukuna",minute:"minutu",hours:"horakuna",hour:"hora",ms:"ms",s:"s",min:"m",h:"h"},values:{true:"cheqaq",false:"llulla",null:"ch_usaq",undefined:"mana_riqsisqa",it:"chay",its:"chaypaq",me:"noqa",my:"noqaq",myself:"noqa killa",you:"qam",your:"qampaq",yourself:"qam killa",element:"raku",target:"punta",detail:"sut_iy",event:"ruway",window:"k_iri",document:"qillqa",body:"kurku",result:"lluqsiy",value:"chanin"},attributes:{class:"ayllu",classes:"ayllukuna",style:"sami",styles:"samikuna",attribute:"kaq",attributes:"kaqkuna",property:"kanay",properties:"kanaykuna"},expressions:{first:"ñawpaq",last:"qhipa",next:"qhipantin",previous:"ñawpaqnin",prev:"ñawpaq",at:"pi",random:"imaymanata",closest:"aswan_kaylla",parent:"mama_tayta",children:"wawakuna",within:"ukupi",no:"mana_kanchu",empty:"ch_usaq",some:"wakin","starts with":"qallarisqa wan","ends with":"tukusqa wan"}},bl=Xo(vl,"qu",{allowEnglishFallback:!0}),wl={commands:{on:"kwenye",tell:"ambia",trigger:"chochea",send:"tuma",take:"chukua",put:"weka",set:"weka",get:"pata",add:"ongeza",remove:"ondoa",toggle:"badilisha",hide:"ficha",show:"onyesha",if:"kama",unless:"isipokuwa",repeat:"rudia",for:"kwa",while:"wakati",until:"hadi",continue:"endelea",break:"vunja",halt:"simama",wait:"ngoja",fetch:"leta",call:"ita",return:"rudi",make:"fanya",log:"andika",throw:"tupa",catch:"shika",measure:"pima",transition:"mpito",increment:"ongeza",decrement:"punguza",default:"msingi",go:"nenda",pushUrl:"sukumaUrl",replaceUrl:"badilishaUrl",copy:"nakili",pick:"chagua",beep:"lia",js:"js",async:"sainkroni",render:"chora",swap:"badilishana",morph:"badilishaUmbo",settle:"tulia",append:"ongezaMwisho",exit:"toka",install:"sakinisha"},modifiers:{to:"kwa",from:"kutoka",into:"ndani",with:"na",at:"katika",in:"ndani",of:"ya",as:"kama",by:"na",before:"kabla",after:"baada",over:"juu",under:"chini",between:"kati",through:"kupitia",without:"bila"},events:{click:"bonyeza",dblclick:"bonyeza_mara_mbili",mousedown:"panya_shuka",mouseup:"panya_juu",mouseenter:"panya_ingia",mouseleave:"panya_toka",mouseover:"panya_juu",mouseout:"panya_nje",mousemove:"panya_sogea",keydown:"kitufe_shuka",keyup:"kitufe_juu",keypress:"kitufe_bonyeza",focus:"zingatia",blur:"poteza_macho",change:"badilisha",input:"ingizo",submit:"wasilisha",reset:"weka_upya",load:"pakia",unload:"shuka",resize:"badilisha_ukubwa",scroll:"sogeza",touchstart:"gusa_anza",touchend:"gusa_mwisho",touchmove:"gusa_sogea",touchcancel:"gusa_ghairi"},logical:{when:"wakati",where:"wapi",and:"na",or:"au",not:"si",is:"ni",exists:"ipo",matches:"inafanana",contains:"ina",includes:"pamoja",equals:"sawa",has:"ana",have:"nina",then:"kisha",else:"sivyo",otherwise:"vinginevyo",end:"mwisho"},temporal:{seconds:"sekunde",second:"sekunde",milliseconds:"millisekunde",millisecond:"millisekunde",minutes:"dakika",minute:"dakika",hours:"masaa",hour:"saa",ms:"ms",s:"s",min:"dk",h:"sa"},values:{true:"kweli",false:"uongo",null:"tupu",undefined:"haijafafanuliwa",it:"hiyo",its:"yake",me:"mimi",my:"yangu",myself:"mimi mwenyewe",you:"wewe",your:"yako",yourself:"wewe mwenyewe",element:"kipengele",target:"lengo",detail:"maelezo",event:"tukio",window:"dirisha",document:"hati",body:"mwili",result:"matokeo",value:"thamani"},attributes:{class:"darasa",classes:"madarasa",style:"mtindo",styles:"mitindo",attribute:"sifa",attributes:"sifa",property:"mali",properties:"mali"},expressions:{first:"kwanza",last:"mwisho",next:"ijayo",previous:"iliyopita",prev:"awali",at:"katika",random:"nasibu",closest:"karibu_zaidi",parent:"mzazi",children:"watoto",within:"ndani_ya",no:"hakuna",empty:"tupu",some:"baadhi","starts with":"huanza na","ends with":"huisha na"}},kl=Xo(wl,"sw",{allowEnglishFallback:!0}),El={commands:{on:"em",tell:"dizer",trigger:"disparar",send:"enviar",take:"pegar",put:"colocar",set:"definir",get:"obter",add:"adicionar",remove:"remover",toggle:"alternar",hide:"esconder",show:"mostrar",if:"se",unless:"a_menos",repeat:"repetir",for:"para",while:"enquanto",until:"até",continue:"continuar",break:"parar",halt:"interromper",wait:"esperar",fetch:"buscar",call:"chamar",return:"retornar",make:"fazer",log:"registrar",throw:"lançar",catch:"capturar",measure:"medir",transition:"transição",increment:"incrementar",decrement:"decrementar",default:"padrão",go:"ir",pushUrl:"pushUrl",replaceUrl:"substituirUrl",copy:"copiar",pick:"escolher",beep:"apitar",js:"js",async:"assíncrono",render:"renderizar",swap:"trocar",morph:"transformar",settle:"estabilizar",append:"anexar",exit:"sair",install:"instalar"},modifiers:{to:"para",from:"de",into:"em",with:"com",at:"em",in:"dentro",of:"de",as:"como",by:"por",before:"antes",after:"depois",over:"sobre",under:"sob",between:"entre",through:"através",without:"sem"},events:{click:"clique",dblclick:"duploClique",mousedown:"mouseBaixo",mouseup:"mouseCima",mouseenter:"mouseEntrar",mouseleave:"mouseSair",mouseover:"mouseSobre",mouseout:"mouseFora",mousemove:"mouseMover",keydown:"teclaBaixo",keyup:"teclaCima",keypress:"teclaPressionar",focus:"foco",blur:"desfoque",change:"mudança",input:"entrada",submit:"envio",reset:"reiniciar",load:"carregar",unload:"descarregar",resize:"redimensionar",scroll:"rolar",touchstart:"toqueInício",touchend:"toqueFim",touchmove:"toqueMover",touchcancel:"toqueCancelar"},logical:{when:"quando",where:"onde",and:"e",or:"ou",not:"não",is:"é",exists:"existe",matches:"corresponde",contains:"contém",includes:"inclui",equals:"igual",has:"tem",have:"tenho",then:"então",else:"senão",otherwise:"caso_contrário",end:"fim"},temporal:{seconds:"segundos",second:"segundo",milliseconds:"milissegundos",millisecond:"milissegundo",minutes:"minutos",minute:"minuto",hours:"horas",hour:"hora",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"verdadeiro",false:"falso",null:"nulo",undefined:"indefinido",it:"isso",its:"seu",me:"eu",my:"meu",myself:"eu mesmo",you:"você",your:"seu",yourself:"você mesmo",element:"elemento",target:"alvo",detail:"detalhe",event:"evento",window:"janela",document:"documento",body:"corpo",result:"resultado",value:"valor"},attributes:{class:"classe",classes:"classes",style:"estilo",styles:"estilos",attribute:"atributo",attributes:"atributos",property:"propriedade",properties:"propriedades"},expressions:{first:"primeiro",last:"último",next:"próximo",previous:"anterior",prev:"ant",at:"em",random:"aleatório",closest:"mais_próximo",parent:"pai",children:"filhos",within:"dentro",no:"nenhum",empty:"vazio",some:"algum","starts with":"começa com","ends with":"termina com"}},xl=Xo(El,"pt",{allowEnglishFallback:!0}),Cl={commands:{on:"su",tell:"dire",trigger:"scatenare",send:"inviare",take:"prendere",put:"mettere",set:"impostare",get:"ottenere",add:"aggiungere",remove:"rimuovere",toggle:"commutare",hide:"nascondere",show:"mostrare",if:"se",unless:"a meno che",repeat:"ripetere",for:"per",while:"mentre",until:"fino",continue:"continuare",break:"interrompere",halt:"fermare",wait:"aspettare",fetch:"recuperare",call:"chiamare",return:"ritornare",make:"fare",log:"registrare",throw:"lanciare",catch:"catturare",measure:"misurare",transition:"transizione",increment:"incrementare",decrement:"decrementare",default:"predefinito",go:"andare",pushUrl:"pushUrl",replaceUrl:"sostituireUrl",copy:"copiare",pick:"scegliere",beep:"beep",js:"js",async:"asincrono",render:"renderizzare",swap:"scambiare",morph:"trasformare",settle:"stabilizzare",append:"aggiungere",exit:"uscire",install:"installare"},modifiers:{to:"a",from:"da",into:"in",with:"con",at:"a",in:"in",of:"di",as:"come",by:"per",before:"prima",after:"dopo",over:"sopra",under:"sotto",between:"tra",through:"attraverso",without:"senza"},events:{click:"clic",dblclick:"doppioclic",mousedown:"mousegiù",mouseup:"mousesu",mouseenter:"mouseentra",mouseleave:"mouseesce",mouseover:"mousesopra",mouseout:"mousefuori",mousemove:"mousemuovi",keydown:"tastogiù",keyup:"tastosu",keypress:"tastopremi",focus:"fuoco",blur:"sfuocatura",change:"cambio",input:"input",submit:"invio",reset:"reset",load:"carica",unload:"scarica",resize:"ridimensiona",scroll:"scorrimento",touchstart:"toccoinizia",touchend:"toccofine",touchmove:"toccomuovi",touchcancel:"toccoannulla"},logical:{when:"quando",where:"dove",and:"e",or:"o",not:"non",is:"è",exists:"esiste",matches:"corrisponde",contains:"contiene",includes:"include",equals:"uguale",has:"ha",have:"ho",then:"allora",else:"altrimenti",otherwise:"altrimenti",end:"fine"},temporal:{seconds:"secondi",second:"secondo",milliseconds:"millisecondi",millisecond:"millisecondo",minutes:"minuti",minute:"minuto",hours:"ore",hour:"ora",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"vero",false:"falso",null:"nullo",undefined:"indefinito",it:"esso",its:"suo",me:"io",my:"mio",you:"tu",your:"tuo",yourself:"te stesso",myself:"me stesso",element:"elemento",target:"obiettivo",detail:"dettaglio",event:"evento",window:"finestra",document:"documento",body:"corpo",result:"risultato",value:"valore"},attributes:{class:"classe",classes:"classi",style:"stile",styles:"stili",attribute:"attributo",attributes:"attributi",property:"proprietà",properties:"proprietà"},expressions:{first:"primo",last:"ultimo",next:"prossimo",previous:"precedente",prev:"prec",at:"a",random:"casuale",closest:"piùvicino",parent:"genitore",children:"figli",within:"dentro",no:"nessun",empty:"vuoto",some:"qualche","starts with":"inizia con","ends with":"finisce con"}};Xo(Cl,"it",{allowEnglishFallback:!0});var Al={commands:{on:"khi",tell:"nói với",trigger:"kích hoạt",send:"gửi",take:"lấy",put:"đặt",set:"gán",get:"lấy giá trị",add:"thêm",remove:"xóa",toggle:"chuyển đổi",hide:"ẩn",show:"hiển thị",if:"nếu",unless:"trừ khi",repeat:"lặp lại",for:"với mỗi",while:"trong khi",until:"cho đến khi",continue:"tiếp tục",break:"dừng",halt:"dừng lại",wait:"chờ",fetch:"tải",call:"gọi",return:"trả về",make:"tạo",log:"in ra",throw:"ném",catch:"bắt",measure:"đo lường",transition:"chuyển tiếp",increment:"tăng",decrement:"giảm",default:"mặc định",go:"đi đến",pushUrl:"pushUrl",replaceUrl:"thayThếUrl",copy:"sao chép",pick:"chọn",beep:"beep",js:"js",async:"bất đồng bộ",render:"hiển thị",swap:"hoán đổi",morph:"biến đổi",settle:"ổn định",append:"nối",exit:"thoát",focus:"tập trung",blur:"mất tập trung",init:"khởi tạo",behavior:"hành vi",install:"cài đặt",clone:"sao chép",prepend:"thêm đầu",else:"không thì"},modifiers:{into:"vào",before:"trước",after:"sau",then:"rồi",end:"kết thúc",from:"từ",to:"đến",with:"với",as:"như",by:"bởi",on:"trên",in:"trong",at:"tại",of:"của",the:"",times:"lần"},events:{click:"nhấp",dblclick:"nhấp đúp",input:"nhập",change:"thay đổi",submit:"gửi",keydown:"phím xuống",keyup:"phím lên",keypress:"nhấn phím",mouseover:"chuột vào",mouseout:"chuột ra",mouseenter:"chuột vào",mouseleave:"chuột rời",focus:"tập trung",blur:"mất tập trung",load:"tải",scroll:"cuộn",resize:"đổi kích thước"},logical:{when:"khi",where:"ở_đâu",and:"và",or:"hoặc",not:"không",is:"là",equals:"bằng",contains:"chứa",matches:"khớp",exists:"tồn tại",has:"có",have:"có",empty:"trống",true:"đúng",false:"sai",null:"rỗng",else:"không thì",end:"kết thúc",then:"rồi"},temporal:{now:"bây giờ",today:"hôm nay",tomorrow:"ngày mai",yesterday:"hôm qua",always:"luôn luôn",never:"không bao giờ",sometimes:"đôi khi",once:"một lần",twice:"hai lần",forever:"mãi mãi"},values:{true:"đúng",false:"sai",null:"rỗng",undefined:"không xác định",none:"không có",all:"tất cả",any:"bất kỳ",some:"một số",each:"mỗi",every:"tất cả",body:"body",event:"sự kiện",it:"nó",its:"của nó",me:"tôi",my:"của tôi",result:"kết quả",target:"mục tiêu",you:"bạn",your:"của bạn"},attributes:{id:"id",class:"lớp",style:"kiểu",value:"giá trị",text:"văn bản",html:"html",src:"nguồn",href:"liên kết",disabled:"vô hiệu",hidden:"ẩn",checked:"được chọn",selected:"được chọn"},expressions:{me:"tôi",my:"của tôi",it:"nó",its:"của nó",result:"kết quả",event:"sự kiện",target:"mục tiêu",first:"đầu tiên",last:"cuối cùng",next:"tiếp theo",previous:"trước đó",parent:"cha",children:"con",closest:"gần nhất"}};Xo(Al,"vi",{allowEnglishFallback:!0});var Sl={commands:{on:"gdy",tell:"powiedz",trigger:"wywołaj",send:"wyślij",take:"weź",put:"umieść",set:"ustaw",get:"pobierz",add:"dodaj",remove:"usuń",toggle:"przełącz",hide:"ukryj",show:"pokaż",if:"jeśli",unless:"chyba",repeat:"powtórz",for:"dla",while:"dopóki",until:"aż",continue:"kontynuuj",break:"przerwij",halt:"zatrzymaj",wait:"czekaj",fetch:"pobierz",call:"wywołaj",return:"zwróć",make:"utwórz",log:"loguj",throw:"rzuć",catch:"złap",measure:"zmierz",transition:"animuj",increment:"zwiększ",decrement:"zmniejsz",default:"domyślnie",go:"idź",pushUrl:"dodajUrl",replaceUrl:"zamieńUrl",copy:"kopiuj",pick:"wybierz",beep:"sygnał",js:"js",async:"async",render:"renderuj",swap:"zamień",morph:"przekształć",settle:"ustabilizuj",append:"dołącz",exit:"wyjdź",install:"zainstaluj"},modifiers:{to:"do",from:"z",into:"do",with:"z",at:"przy",in:"w",of:"z",as:"jako",by:"przez",before:"przed",after:"po",over:"nad",under:"pod",between:"między",through:"przez",without:"bez"},events:{click:"kliknięcie",dblclick:"podwójnekliknięcie",mousedown:"myszdół",mouseup:"myszgóra",mouseenter:"myszwejście",mouseleave:"myszwyjście",mouseover:"mysznad",mouseout:"myszpoza",mousemove:"myszruch",keydown:"klawiszdół",keyup:"klawiszgóra",keypress:"klawisznaciśnięcie",focus:"fokus",blur:"rozmycie",change:"zmiana",input:"wejście",submit:"wyślij",reset:"resetuj",load:"załaduj",unload:"wyładuj",resize:"zmieńrozmiar",scroll:"przewiń",touchstart:"dotykstart",touchend:"dotykkoniec",touchmove:"dotykruch",touchcancel:"dotykanuluj"},logical:{when:"kiedy",where:"gdzie",and:"i",or:"lub",not:"nie",is:"jest",exists:"istnieje",matches:"pasuje",contains:"zawiera",includes:"obejmuje",equals:"równa się",has:"ma",have:"mam",then:"wtedy",else:"inaczej",otherwise:"wpp",end:"koniec"},temporal:{seconds:"sekundy",second:"sekunda",milliseconds:"milisekundy",millisecond:"milisekunda",minutes:"minuty",minute:"minuta",hours:"godziny",hour:"godzina",ms:"ms",s:"s",min:"min",h:"godz"},values:{true:"prawda",false:"fałsz",null:"null",undefined:"niezdefiniowane",it:"to",its:"jego",me:"ja",my:"mój",you:"ty",your:"twój",yourself:"ty sam",myself:"ja sam",element:"element",target:"cel",detail:"szczegół",event:"zdarzenie",window:"okno",document:"dokument",body:"body",result:"wynik",value:"wartość"},attributes:{class:"klasa",classes:"klasy",style:"styl",styles:"style",attribute:"atrybut",attributes:"atrybuty",property:"właściwość",properties:"właściwości"},expressions:{first:"pierwszy",last:"ostatni",next:"następny",previous:"poprzedni",prev:"poprz",at:"przy",random:"losowy",closest:"najbliższy",parent:"rodzic",children:"dzieci",within:"wewnątrz",no:"brak",empty:"pusty",some:"jakiś","starts with":"zaczyna się od","ends with":"kończy się na"}};Xo(Sl,"pl",{allowEnglishFallback:!0});var Tl={commands:{on:"при",tell:"сказать",trigger:"вызвать",send:"отправить",take:"взять",put:"положить",set:"установить",get:"получить",add:"добавить",remove:"удалить",toggle:"переключить",hide:"скрыть",show:"показать",if:"если",unless:"если_не",repeat:"повторить",for:"для",while:"пока",until:"до",continue:"продолжить",break:"прервать",halt:"остановить",wait:"ждать",fetch:"загрузить",call:"вызвать",return:"вернуть",make:"создать",log:"записать",throw:"бросить",catch:"поймать",measure:"измерить",transition:"анимировать",increment:"увеличить",decrement:"уменьшить",default:"по_умолчанию",go:"перейти",pushUrl:"добавить_url",replaceUrl:"заменить_url",copy:"копировать",pick:"выбрать",beep:"звук",js:"js",async:"асинхронно",render:"отобразить",swap:"поменять",morph:"трансформировать",settle:"стабилизировать",append:"добавить_в_конец",exit:"выйти",else:"иначе",install:"установить",init:"инициализировать",behavior:"поведение",focus:"сфокусировать",blur:"размыть",clone:"клонировать",prepend:"добавить_в_начало"},modifiers:{to:"к",from:"из",into:"в",with:"с",at:"у",in:"в",of:"из",as:"как",by:"на",before:"до",after:"после",over:"над",under:"под",between:"между",through:"через",without:"без",on:"на"},events:{click:"клик",dblclick:"двойной_клик",mousedown:"мышь_вниз",mouseup:"мышь_вверх",mouseenter:"мышь_вход",mouseleave:"мышь_выход",mouseover:"наведение",mouseout:"уход",mousemove:"движение_мыши",keydown:"клавиша_вниз",keyup:"клавиша_вверх",keypress:"нажатие_клавиши",focus:"фокус",blur:"потеря_фокуса",change:"изменение",input:"ввод",submit:"отправка",reset:"сброс",load:"загрузка",unload:"выгрузка",resize:"изменение_размера",scroll:"прокрутка",touchstart:"касание_начало",touchend:"касание_конец",touchmove:"касание_движение",touchcancel:"касание_отмена"},logical:{when:"когда",where:"где",and:"и",or:"или",not:"не",is:"есть",exists:"существует",matches:"соответствует",contains:"содержит",includes:"включает",equals:"равно",then:"затем",else:"иначе",otherwise:"в_противном_случае",end:"конец",has:"имеет",have:"имею",isNot:"не_есть",empty:"пустой"},temporal:{seconds:"секунд",second:"секунда",milliseconds:"миллисекунд",millisecond:"миллисекунда",minutes:"минут",minute:"минута",hours:"часов",hour:"час",ms:"мс",s:"с",min:"мин",h:"ч",forever:"всегда",once:"однажды",every:"каждый",until:"до"},values:{true:"истина",false:"ложь",null:"ничего",undefined:"неопределено",it:"это",its:"его",me:"я",my:"мой",you:"ты",your:"твой",yourself:"сам",myself:"я_сам",element:"элемент",target:"цель",detail:"детали",event:"событие",window:"окно",document:"документ",body:"тело",result:"результат",value:"значение",first:"первый",last:"последний",next:"следующий",previous:"предыдущий",closest:"ближайший",parent:"родитель"},attributes:{class:"класс",classes:"классы",style:"стиль",styles:"стили",attribute:"атрибут",attributes:"атрибуты",property:"свойство",properties:"свойства",disabled:"отключено",hidden:"скрыто",checked:"отмечено",selected:"выбрано",readonly:"только_чтение",required:"обязательно",text:"текст",html:"html"},expressions:{first:"первый",last:"последний",next:"следующий",previous:"предыдущий",prev:"пред",at:"в",random:"случайный",closest:"ближайший",parent:"родитель",children:"дети",within:"внутри",no:"нет",empty:"пустой",some:"некоторые","starts with":"начинается_с","ends with":"заканчивается_на"}};Xo(Tl,"ru",{allowEnglishFallback:!0});var Ll={commands:{on:"при",tell:"сказати",trigger:"викликати",send:"надіслати",take:"взяти",put:"покласти",set:"встановити",get:"отримати",add:"додати",remove:"видалити",toggle:"перемкнути",hide:"сховати",show:"показати",if:"якщо",unless:"якщо_не",repeat:"повторити",for:"для",while:"поки",until:"до",continue:"продовжити",break:"перервати",halt:"зупинити",wait:"чекати",fetch:"завантажити",call:"викликати",return:"повернути",make:"створити",log:"записати",throw:"кинути",catch:"зловити",measure:"виміряти",transition:"анімувати",increment:"збільшити",decrement:"зменшити",default:"за_замовчуванням",go:"перейти",pushUrl:"додати_url",replaceUrl:"замінити_url",copy:"копіювати",pick:"вибрати",beep:"звук",js:"js",async:"асинхронно",render:"відобразити",swap:"поміняти",morph:"трансформувати",settle:"стабілізувати",append:"додати_в_кінець",exit:"вийти",else:"інакше",install:"встановити",init:"ініціалізувати",behavior:"поведінка",focus:"сфокусувати",blur:"розфокусувати",clone:"клонувати",prepend:"додати_на_початок"},modifiers:{to:"до",from:"з",into:"в",with:"з",at:"в",in:"у",of:"з",as:"як",by:"на",before:"до",after:"після",over:"над",under:"під",between:"між",through:"через",without:"без",on:"на"},events:{click:"клік",dblclick:"подвійний_клік",mousedown:"миша_вниз",mouseup:"миша_вгору",mouseenter:"миша_вхід",mouseleave:"миша_вихід",mouseover:"наведення",mouseout:"відведення",mousemove:"рух_миші",keydown:"клавіша_вниз",keyup:"клавіша_вгору",keypress:"натискання_клавіші",focus:"фокус",blur:"розфокус",change:"зміна",input:"введення",submit:"надсилання",reset:"скидання",load:"завантаження",unload:"вивантаження",resize:"зміна_розміру",scroll:"прокрутка",touchstart:"дотик_початок",touchend:"дотик_кінець",touchmove:"дотик_рух",touchcancel:"дотик_скасування"},logical:{when:"коли",where:"де",and:"і",or:"або",not:"не",is:"є",exists:"існує",matches:"відповідає",contains:"містить",includes:"включає",equals:"дорівнює",then:"тоді",else:"інакше",otherwise:"в_іншому_випадку",end:"кінець",has:"має",have:"маю",isNot:"не_є",empty:"порожній"},temporal:{seconds:"секунд",second:"секунда",milliseconds:"мілісекунд",millisecond:"мілісекунда",minutes:"хвилин",minute:"хвилина",hours:"годин",hour:"година",ms:"мс",s:"с",min:"хв",h:"год",forever:"завжди",once:"один_раз",every:"кожний",until:"до"},values:{true:"істина",false:"хибність",null:"нічого",undefined:"невизначено",it:"це",its:"його",me:"я",my:"мій",you:"ти",your:"твій",yourself:"сам",myself:"я_сам",element:"елемент",target:"ціль",detail:"деталі",event:"подія",window:"вікно",document:"документ",body:"тіло",result:"результат",value:"значення",first:"перший",last:"останній",next:"наступний",previous:"попередній",closest:"найближчий",parent:"батьківський"},attributes:{class:"клас",classes:"класи",style:"стиль",styles:"стилі",attribute:"атрибут",attributes:"атрибути",property:"властивість",properties:"властивості",disabled:"вимкнено",hidden:"приховано",checked:"позначено",selected:"вибрано",readonly:"лише_читання",required:"обов'язково",text:"текст",html:"html"},expressions:{first:"перший",last:"останній",next:"наступний",previous:"попередній",prev:"попер",at:"в",random:"випадковий",closest:"найближчий",parent:"батьківський",children:"діти",within:"всередині",no:"ні",empty:"порожній",some:"деякі","starts with":"починається_з","ends with":"закінчується_на"}};Xo(Ll,"uk",{allowEnglishFallback:!0});var Ol={commands:{on:"पर",tell:"बताएं",trigger:"ट्रिगर",send:"भेजें",take:"लें",put:"रखें",set:"सेट",get:"प्राप्त",add:"जोड़ें",remove:"हटाएं",toggle:"टॉगल",hide:"छिपाएं",show:"दिखाएं",if:"अगर",unless:"जब_तक_नहीं",repeat:"दोहराएं",for:"के_लिए",while:"जब_तक",until:"तक",continue:"जारी",break:"रोकें",halt:"रोकें",wait:"प्रतीक्षा",fetch:"लाएं",call:"कॉल",return:"लौटाएं",make:"बनाएं",log:"लॉग",throw:"फेंकें",catch:"पकड़ें",measure:"मापें",transition:"संक्रमण",increment:"बढ़ाएं",decrement:"घटाएं",default:"डिफ़ॉल्ट",go:"जाएं",pushUrl:"url_जोड़ें",replaceUrl:"url_बदलें",copy:"कॉपी",pick:"चुनें",beep:"बीप",js:"जेएस",async:"असिंक",render:"रेंडर",swap:"बदलें",morph:"रूपांतर",settle:"स्थिर",append:"जोड़ें_अंत",exit:"बाहर",else:"वरना",install:"इंस्टॉल",init:"प्रारंभ",behavior:"व्यवहार",focus:"फोकस",blur:"धुंधला",clone:"कॉपी",prepend:"जोड़ें_शुरू"},modifiers:{to:"को",from:"से",into:"में",with:"के_साथ",at:"पर",in:"में",of:"का",as:"के_रूप_में",by:"द्वारा",before:"से_पहले",after:"के_बाद",over:"के_ऊपर",under:"के_नीचे",between:"के_बीच",through:"के_माध्यम_से",without:"के_बिना",on:"पर"},events:{click:"क्लिक",dblclick:"डबल_क्लिक",mousedown:"माउस_नीचे",mouseup:"माउस_ऊपर",mouseenter:"माउस_प्रवेश",mouseleave:"माउस_बाहर",mouseover:"माउस_ओवर",mouseout:"माउस_आउट",mousemove:"माउस_मूव",keydown:"की_नीचे",keyup:"की_ऊपर",keypress:"की_प्रेस",focus:"फोकस",blur:"धुंधला",change:"परिवर्तन",input:"इनपुट",submit:"जमा",reset:"रीसेट",load:"लोड",unload:"अनलोड",resize:"आकार_बदलें",scroll:"स्क्रॉल",touchstart:"टच_शुरू",touchend:"टच_समाप्त",touchmove:"टच_मूव",touchcancel:"टच_रद्द"},logical:{when:"जब",where:"कहाँ",and:"और",or:"या",not:"नहीं",is:"है",exists:"मौजूद",matches:"मेल_खाता",contains:"शामिल",includes:"में_है",equals:"बराबर",then:"फिर",else:"वरना",otherwise:"अन्यथा",end:"समाप्त",has:"है",have:"है",isNot:"नहीं_है",empty:"खाली"},temporal:{seconds:"सेकंड",second:"सेकंड",milliseconds:"मिलीसेकंड",millisecond:"मिलीसेकंड",minutes:"मिनट",minute:"मिनट",hours:"घंटे",hour:"घंटा",ms:"मिसे",s:"से",min:"मि",h:"घं",forever:"हमेशा",once:"एक_बार",every:"हर",until:"तक"},values:{true:"सच",false:"झूठ",null:"खाली",undefined:"अपरिभाषित",it:"यह",its:"इसका",me:"मैं",my:"मेरा",you:"आप",your:"आपका",yourself:"स्वयं",myself:"मैं_स्वयं",element:"तत्व",target:"लक्ष्य",detail:"विवरण",event:"घटना",window:"विंडो",document:"दस्तावेज़",body:"बॉडी",result:"परिणाम",value:"मान",first:"पहला",last:"अंतिम",next:"अगला",previous:"पिछला",closest:"निकटतम",parent:"मूल"},attributes:{class:"क्लास",classes:"क्लासेस",style:"स्टाइल",styles:"स्टाइल्स",attribute:"गुण",attributes:"गुण",property:"संपत्ति",properties:"संपत्तियाँ",disabled:"अक्षम",hidden:"छिपा",checked:"चेक",selected:"चयनित",readonly:"केवल_पढ़ने",required:"आवश्यक",text:"पाठ",html:"html"},expressions:{first:"पहला",last:"अंतिम",next:"अगला",previous:"पिछला",prev:"पिछ",at:"पर",random:"यादृच्छिक",closest:"निकटतम",parent:"मूल",children:"बच्चे",within:"के_अंदर",no:"नहीं",empty:"खाली",some:"कुछ","starts with":"से_शुरू","ends with":"पर_समाप्त"}};Xo(Ol,"hi",{allowEnglishFallback:!0});var Pl={commands:{on:"তে",toggle:"টগল",add:"যোগ",remove:"সরান",set:"সেট",get:"পান",put:"রাখুন",take:"নিন",show:"দেখান",hide:"লুকান",increment:"বৃদ্ধি",decrement:"হ্রাস",if:"যদি",else:"নতুবা",repeat:"পুনরাবৃত্তি",for:"জন্য",while:"যতক্ষণ",wait:"অপেক্ষা",fetch:"আনুন",call:"কল",return:"ফিরুন",log:"লগ",trigger:"ট্রিগার",send:"পাঠান",go:"যান",halt:"থামুন",throw:"নিক্ষেপ",continue:"চালিয়ে যান",make:"তৈরি করুন",append:"শেষে যোগ",prepend:"শুরুতে যোগ",focus:"ফোকাস",blur:"ঝাপসা",transition:"সংক্রমণ",settle:"স্থির",measure:"মাপুন",async:"অ্যাসিঙ্ক",tell:"বলুন",default:"ডিফল্ট",init:"শুরু",behavior:"আচরণ",install:"ইনস্টল",clone:"কপি",swap:"বদল",morph:"রূপান্তর",beep:"বীপ",break:"ভাঙুন",copy:"কপি",exit:"বের",js:"জেএস",pick:"বাছুন",render:"রেন্ডার",until:"পর্যন্ত"},modifiers:{to:"কে",from:"থেকে",into:"তে",on:"তে",with:"সাথে",by:"দ্বারা",as:"হিসাবে",before:"আগে",after:"পরে",at:"এ",in:"এ",over:"উপর",then:"তারপর",and:"এবং",end:"শেষ",until:"পর্যন্ত",of:"র"},events:{click:"ক্লিক",change:"পরিবর্তন",input:"ইনপুট",submit:"জমা",load:"লোড",focus:"ফোকাস",blur:"ঝাপসা",keydown:"কি-ডাউন",keyup:"কি-আপ",mouseover:"মাউস-ওভার",mouseout:"মাউস-আউট",scroll:"স্ক্রোল",resize:"রিসাইজ",every:"প্রতি"},logical:{if:"যদি",when:"যখন",where:"কোথায়",else:"নতুবা",not:"না",and:"এবং",or:"অথবা",is:"হয়",exists:"আছে",has:"আছে",have:"আছি",empty:"খালি",true:"সত্য",false:"মিথ্যা",null:"শূন্য",undefined:"অনির্ধারিত",end:"শেষ",then:"তারপর"},temporal:{now:"এখন",seconds:"সেকেন্ড",milliseconds:"মিলিসেকেন্ড",minutes:"মিনিট",hours:"ঘণ্টা",forever:"চিরকাল",times:"বার",s:"সে",ms:"মিসে"},values:{me:"আমি",my:"আমার",it:"এটি",its:"এর",result:"ফলাফল",event:"ঘটনা",target:"লক্ষ্য",body:"বডি",you:"আপনি",your:"তোমার"},attributes:{class:"শ্রেণি",id:"আইডি",style:"শৈলী",value:"মান",text:"পাঠ্য",html:"এইচটিএমএল",disabled:"অক্ষম",checked:"চেক করা"},expressions:{first:"প্রথম",last:"শেষ",next:"পরবর্তী",previous:"আগের",closest:"নিকটতম",parent:"মূল",children:"সন্তান",random:"এলোমেলো",length:"দৈর্ঘ্য",index:"সূচক"}};Xo(Pl,"bn",{allowEnglishFallback:!0});var Nl={commands:{on:"เมื่อ",toggle:"สลับ",add:"เพิ่ม",remove:"ลบ",set:"ตั้ง",get:"รับค่า",put:"ใส่",take:"รับ",show:"แสดง",hide:"ซ่อน",increment:"เพิ่มค่า",decrement:"ลดค่า",if:"ถ้า",else:"ไม่งั้น",repeat:"ทำซ้ำ",for:"สำหรับ",while:"ในขณะที่",wait:"รอ",fetch:"ดึงข้อมูล",call:"เรียก",return:"คืนค่า",log:"บันทึก",trigger:"ทริกเกอร์",send:"ส่ง",go:"ไป",halt:"หยุด",throw:"โยน",continue:"ต่อไป",make:"สร้าง",append:"เพิ่มท้าย",prepend:"เพิ่มหน้า",focus:"โฟกัส",blur:"เบลอ",transition:"เปลี่ยน",settle:"คงที่",measure:"วัด",async:"อะซิงค์",tell:"บอก",default:"ค่าเริ่มต้น",init:"เริ่มต้น",behavior:"พฤติกรรม",install:"ติดตั้ง",clone:"คัดลอก",swap:"สลับที่",morph:"แปลงร่าง",beep:"บี๊บ",break:"ขัดจังหวะ",copy:"คัดลอก",exit:"ออก",js:"เจเอส",pick:"เลือก",render:"แสดงผล",until:"จนถึง"},modifiers:{to:"ไปยัง",from:"จาก",into:"ใน",on:"เมื่อ",with:"ด้วย",by:"โดย",as:"เป็น",before:"ก่อน",after:"หลัง",at:"ที่",in:"ใน",over:"เหนือ",then:"แล้ว",and:"และ",end:"จบ",until:"จนถึง",of:"ของ"},events:{click:"คลิก",change:"เปลี่ยนแปลง",input:"อินพุต",submit:"ส่ง",load:"โหลด",focus:"โฟกัส",blur:"เบลอ",keydown:"กดคีย์",keyup:"ปล่อยคีย์",mouseover:"เมาส์เข้า",mouseout:"เมาส์ออก",scroll:"เลื่อน",resize:"ปรับขนาด",every:"ทุก"},logical:{if:"ถ้า",when:"เมื่อ",where:"ที่ไหน",else:"ไม่งั้น",not:"ไม่",and:"และ",or:"หรือ",is:"เป็น",exists:"มีอยู่",has:"มี",have:"มี",empty:"ว่าง",true:"จริง",false:"เท็จ",null:"ว่าง",undefined:"ไม่กำหนด",end:"จบ",then:"แล้ว"},temporal:{now:"ตอนนี้",seconds:"วินาที",milliseconds:"มิลลิวินาที",minutes:"นาที",hours:"ชั่วโมง",forever:"ตลอดไป",times:"ครั้ง",s:"วิ",ms:"มว"},values:{me:"ฉัน",my:"ของฉัน",it:"มัน",its:"ของมัน",result:"ผลลัพธ์",event:"เหตุการณ์",target:"เป้าหมาย",body:"บอดี้",you:"คุณ",your:"ของคุณ"},attributes:{class:"คลาส",id:"ไอดี",style:"สไตล์",value:"ค่า",text:"ข้อความ",html:"เอชทีเอ็มแอล",disabled:"ปิดใช้งาน",checked:"เลือกแล้ว"},expressions:{first:"แรก",last:"สุดท้าย",next:"ถัดไป",previous:"ก่อนหน้า",closest:"ใกล้สุด",parent:"ต้นทาง",children:"ลูก",random:"สุ่ม",length:"ความยาว",index:"ดัชนี"}};Xo(Nl,"th",{allowEnglishFallback:!0});var Il={commands:{on:"apabila",tell:"beritahu",trigger:"cetuskan",send:"hantar",take:"ambil",put:"letak",set:"tetapkan",get:"dapatkan",add:"tambah",remove:"buang",toggle:"togol",hide:"sembunyi",show:"tunjuk",if:"jika",unless:"kecuali",repeat:"ulang",for:"untuk",while:"selagi",until:"sehingga",continue:"teruskan",break:"henti",halt:"henti",wait:"tunggu",fetch:"ambil_dari",call:"panggil",return:"pulang",make:"buat",log:"catat",throw:"lempar",catch:"tangkap",measure:"ukur",transition:"peralihan",increment:"tambah_satu",decrement:"kurang_satu",default:"lalai",go:"pergi",pushUrl:"tolak_url",replaceUrl:"ganti_url",copy:"salin",pick:"pilih",beep:"bunyi",js:"js",async:"tak_segerak",render:"papar",swap:"tukar_tempat",morph:"ubah_bentuk",settle:"selesai",append:"tambah_hujung",prepend:"tambah_mula",exit:"keluar",else:"kalau_tidak",focus:"fokus",blur:"kabur",install:"pasang",behavior:"kelakuan",init:"mula",clone:"klon"},modifiers:{to:"ke",from:"dari",into:"ke_dalam",with:"dengan",at:"di",in:"dalam",of:"daripada",as:"sebagai",by:"oleh",before:"sebelum",after:"selepas",over:"atas",under:"bawah",between:"antara",through:"melalui",without:"tanpa",on:"pada",then:"kemudian",and:"dan",end:"tamat",until:"sehingga"},events:{click:"click",dblclick:"dblclick",mousedown:"mousedown",mouseup:"mouseup",mouseenter:"mouseenter",mouseleave:"mouseleave",mouseover:"mouseover",mouseout:"mouseout",mousemove:"mousemove",keydown:"keydown",keyup:"keyup",keypress:"keypress",focus:"focus",blur:"blur",change:"change",input:"input",submit:"submit",reset:"reset",load:"load",unload:"unload",resize:"resize",scroll:"scroll",touchstart:"touchstart",touchend:"touchend",touchmove:"touchmove",touchcancel:"touchcancel",every:"setiap"},logical:{when:"apabila",where:"di_mana",and:"dan",or:"atau",not:"bukan",is:"adalah",exists:"wujud",matches:"sepadan",contains:"mengandungi",includes:"termasuk",equals:"sama",has:"ada",have:"ada",then:"kemudian",else:"kalau_tidak",otherwise:"jika_tidak",end:"tamat",if:"jika",empty:"kosong",true:"benar",false:"salah",null:"null",undefined:"tidak_ditakrifkan"},temporal:{seconds:"saat",second:"saat",milliseconds:"milisaat",millisecond:"milisaat",minutes:"minit",minute:"minit",hours:"jam",hour:"jam",ms:"ms",s:"s",min:"min",h:"j",now:"sekarang",forever:"selamanya",times:"kali"},values:{true:"benar",false:"salah",null:"null",undefined:"tidak_ditakrifkan",it:"ia",its:"nya",me:"saya",my:"saya_punya",myself:"diri_saya",you:"kamu",your:"kamu_punya",yourself:"diri_kamu",element:"elemen",target:"sasaran",detail:"perincian",event:"peristiwa",window:"tetingkap",document:"dokumen",body:"badan",result:"hasil",value:"nilai"},attributes:{class:"kelas",classes:"kelas_kelas",style:"gaya",styles:"gaya_gaya",attribute:"atribut",attributes:"atribut_atribut",property:"sifat",properties:"sifat_sifat",id:"id",value:"nilai",text:"teks",html:"html",disabled:"dilumpuhkan",checked:"ditanda"},expressions:{first:"pertama",last:"terakhir",next:"seterusnya",previous:"sebelumnya",prev:"sebelum",at:"di",random:"rawak",closest:"terdekat",parent:"induk",children:"anak_anak",within:"dalam",no:"tiada",empty:"kosong",some:"beberapa","starts with":"bermula_dengan","ends with":"berakhir_dengan",length:"panjang",index:"indeks"}};Xo(Il,"ms",{allowEnglishFallback:!0});var jl={commands:{on:"kapag",tell:"sabihin",trigger:"palitawin",send:"ipadala",take:"kunin",put:"ilagay",set:"itakda",get:"kuhanin",add:"idagdag",remove:"alisin",toggle:"palitan",hide:"itago",show:"ipakita",if:"kung",unless:"maliban_kung",repeat:"ulitin",for:"para_sa",while:"habang",until:"hanggang",continue:"magpatuloy",break:"itigil",halt:"huminto",wait:"maghintay",fetch:"kuhanin_mula",call:"tawagin",return:"ibalik",make:"gumawa",log:"itala",throw:"ihagis",catch:"hulihin",measure:"sukatin",transition:"baguhin",increment:"dagdagan",decrement:"bawasan",default:"pamantayan",go:"pumunta",pushUrl:"itulak_url",replaceUrl:"palitan_url",copy:"kopyahin",pick:"pumili",beep:"tunog",js:"js",async:"sabay",render:"ipakita",swap:"palitan_pwesto",morph:"baguhin_hugis",settle:"ayusin",append:"idagdag_sa_dulo",prepend:"idagdag_sa_simula",exit:"lumabas",else:"kung_hindi",focus:"ituon",blur:"alisin_tuon",install:"ikabit",behavior:"ugali",init:"simulan",clone:"kopyahin"},modifiers:{to:"sa",from:"mula_sa",into:"papasok_sa",with:"kasama",at:"sa",in:"sa_loob",of:"ng",as:"bilang",by:"sa_pamamagitan_ng",before:"bago",after:"pagkatapos",over:"sa_ibabaw",under:"sa_ilalim",between:"sa_pagitan",through:"sa_pamamagitan",without:"walang",on:"sa",then:"pagkatapos",and:"at",end:"wakas",until:"hanggang"},events:{click:"click",dblclick:"dblclick",mousedown:"mousedown",mouseup:"mouseup",mouseenter:"mouseenter",mouseleave:"mouseleave",mouseover:"mouseover",mouseout:"mouseout",mousemove:"mousemove",keydown:"keydown",keyup:"keyup",keypress:"keypress",focus:"focus",blur:"blur",change:"change",input:"input",submit:"submit",reset:"reset",load:"load",unload:"unload",resize:"resize",scroll:"scroll",touchstart:"touchstart",touchend:"touchend",touchmove:"touchmove",touchcancel:"touchcancel",every:"bawat"},logical:{when:"kapag",where:"kung_saan",and:"at",or:"o",not:"hindi",is:"ay",exists:"may",matches:"tumutugma",contains:"naglalaman",includes:"kasama",equals:"katumbas",has:"may",have:"may",then:"pagkatapos",else:"kung_hindi",otherwise:"kung_hindi_man",end:"wakas",if:"kung",empty:"walang_laman",true:"totoo",false:"mali",null:"wala",undefined:"hindi_tinukoy"},temporal:{seconds:"segundo",second:"segundo",milliseconds:"milisegundo",millisecond:"milisegundo",minutes:"minuto",minute:"minuto",hours:"oras",hour:"oras",ms:"ms",s:"s",min:"min",h:"h",now:"ngayon",forever:"magpakailanman",times:"beses"},values:{true:"totoo",false:"mali",null:"wala",undefined:"hindi_tinukoy",it:"ito",its:"nito",me:"ako",my:"aking",myself:"sarili_ko",you:"ikaw",your:"iyong",yourself:"sarili_mo",element:"elemento",target:"target",detail:"detalye",event:"pangyayari",window:"bintana",document:"dokumento",body:"katawan",result:"resulta",value:"halaga"},attributes:{class:"klase",classes:"mga_klase",style:"estilo",styles:"mga_estilo",attribute:"katangian",attributes:"mga_katangian",property:"ari_arian",properties:"mga_ari_arian",id:"id",value:"halaga",text:"teksto",html:"html",disabled:"hindi_pinagana",checked:"naka_tsek"},expressions:{first:"una",last:"huli",next:"susunod",previous:"nakaraan",prev:"nakaraan",at:"sa",random:"random",closest:"pinakamalapit",parent:"magulang",children:"mga_anak",within:"sa_loob_ng",no:"walang",empty:"walang_laman",some:"ilan","starts with":"nagsisimula_sa","ends with":"nagtatapos_sa",length:"haba",index:"indeks"}};Xo(jl,"tl",{allowEnglishFallback:!0});var Rl=class e{static register(t,r){e.providers.set(t.toLowerCase(),r)}static unregister(t){e.providers.delete(t.toLowerCase())}static setDefault(t){const r=t.toLowerCase();if("en"!==r&&!e.providers.has(r))throw Error(`Locale '${t}' is not registered. Available locales: ${e.getAvailable().join(", ")}`);e.defaultLocale=r}static getDefault(){return e.defaultLocale}static get(t){const r=(t||e.defaultLocale).toLowerCase();if("en"===r)return e.englishProvider;const n=e.providers.get(r);if(!n)throw Error(`Locale '${r}' is not registered. Available locales: ${e.getAvailable().join(", ")}`);return n}static has(t){const r=t.toLowerCase();return"en"===r||e.providers.has(r)}static getAvailable(){return["en",...Array.from(e.providers.keys())]}static reset(){e.providers.clear(),e.defaultLocale="en"}static registerAll(t){for(const[r,n]of Object.entries(t))e.register(r,n)}};Rl.providers=new Map,Rl.defaultLocale="en",Rl.englishProvider=Qo();var ql=Rl;function _l(e){if(0===e.length)return"";let t="";for(let r=0;e.length>r;r++){const n=e[r],s=e[r+1],i=n.endsWith("-"),a=n.startsWith("-");let o=n;if(i&&(o=n.slice(0,-1)),a&&(o=n.substring(1)),t+=o,s){const e=s.startsWith("-");i||e||(t+=" ")}}return t}var Ml={en:{code:"en",name:"English",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","source","destination","quantity","duration","method","style"],markers:[{form:"on",role:"event",position:"preposition",required:!0},{form:"to",role:"destination",position:"preposition",required:!1},{form:"into",role:"destination",position:"preposition",required:!1},{form:"from",role:"source",position:"preposition",required:!1},{form:"with",role:"style",position:"preposition",required:!1},{form:"by",role:"quantity",position:"preposition",required:!1},{form:"as",role:"method",position:"preposition",required:!1},{form:"over",role:"duration",position:"preposition",required:!1},{form:"for",role:"duration",position:"preposition",required:!1}]},ja:{code:"ja",name:"日本語",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"を",role:"patient",position:"postposition",required:!0},{form:"に",role:"destination",position:"postposition",required:!0},{form:"から",role:"source",position:"postposition",required:!0},{form:"で",role:"event",position:"postposition",required:!0},{form:"で",role:"style",position:"postposition",required:!1},{form:"と",role:"style",position:"postposition",required:!1},{form:"へ",role:"destination",position:"postposition",required:!1}],rules:[{name:"event-handler",description:"Transform event handlers to Japanese SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"],optionalRoles:["patient"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}},{name:"put-into",description:"Transform put X into Y to Japanese order",priority:90,match:{commands:["put","置く"],requiredRoles:["action","patient","destination"]},transform:{roleOrder:["patient","destination","action"],insertMarkers:!0}}]},ko:{code:"ko",name:"한국어",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"를",role:"patient",position:"postposition",required:!0,alternatives:["을"]},{form:"에",role:"destination",position:"postposition",required:!0},{form:"에서",role:"source",position:"postposition",required:!0},{form:"로",role:"style",position:"postposition",required:!1,alternatives:["으로"]},{form:"와",role:"style",position:"postposition",required:!1,alternatives:["과"]},{form:"로",role:"method",position:"postposition",required:!1,alternatives:["으로"]}],rules:[{name:"event-handler",description:"Transform event handlers to Korean SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},zh:{code:"zh",name:"中文",wordOrder:"SVO",adpositionType:"preposition",morphology:"isolating",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"当",role:"event",position:"preposition",required:!0},{form:"时",role:"event",position:"postposition",required:!0},{form:"把",role:"patient",position:"preposition",required:!1},{form:"到",role:"destination",position:"preposition",required:!1},{form:"从",role:"source",position:"preposition",required:!1},{form:"用",role:"style",position:"preposition",required:!1},{form:"的",role:"method",position:"postposition",required:!1}],rules:[{name:"event-handler-standard",description:"Standard event handler: 当 X 时 Y",priority:100,match:{requiredRoles:["event","action"]},transform:{roleOrder:["event","action","patient"],insertMarkers:!0,custom:(e,t)=>{const r=e.roles.get("event"),n=e.roles.get("action"),s=e.roles.get("patient"),i=["当",r?.translated||r?.value,"时"];return i.push(n?.translated||n?.value||""),s&&i.push(s.translated||s.value),i.filter(Boolean).join(" ")}}},{name:"ba-construction",description:"BA construction for object-fronting: 把 X Y",priority:80,match:{commands:["put","set","move"],requiredRoles:["action","patient","destination"]},transform:{roleOrder:["patient","action","destination"],insertMarkers:!0}}]},ar:{code:"ar",name:"العربية",wordOrder:"VSO",adpositionType:"preposition",morphology:"fusional",direction:"rtl",canonicalOrder:["action","agent","patient","destination","source"],markers:[{form:"عند",role:"event",position:"preposition",required:!0},{form:"إلى",role:"destination",position:"preposition",required:!1},{form:"في",role:"destination",position:"preposition",required:!1},{form:"من",role:"source",position:"preposition",required:!1},{form:"بـ-",role:"style",position:"preposition",required:!1},{form:"مع",role:"style",position:"preposition",required:!1},{form:"كـ-",role:"method",position:"preposition",required:!1}],rules:[{name:"event-handler-vso",description:"VSO event handler: VERB TARGET عند EVENT",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["action","patient","event"],insertMarkers:!0}}]},tr:{code:"tr",name:"Türkçe",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"i",role:"patient",position:"postposition",required:!0,alternatives:["ı","u","ü"]},{form:"e",role:"destination",position:"postposition",required:!0,alternatives:["a"]},{form:"den",role:"source",position:"postposition",required:!0,alternatives:["dan"]},{form:"de",role:"event",position:"postposition",required:!0,alternatives:["da"]},{form:"ile",role:"style",position:"postposition",required:!1},{form:"olarak",role:"method",position:"postposition",required:!1}],rules:[{name:"event-handler-sov",description:"SOV event handler",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},es:{code:"es",name:"Español",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"en",role:"event",position:"preposition",required:!0},{form:"a",role:"destination",position:"preposition",required:!1},{form:"hacia",role:"destination",position:"preposition",required:!1},{form:"de",role:"source",position:"preposition",required:!1},{form:"con",role:"style",position:"preposition",required:!1},{form:"por",role:"quantity",position:"preposition",required:!1},{form:"como",role:"method",position:"preposition",required:!1}]},de:{code:"de",name:"Deutsch",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"bei",role:"event",position:"preposition",required:!0},{form:"zu",role:"destination",position:"preposition",required:!1},{form:"in",role:"destination",position:"preposition",required:!1},{form:"von",role:"source",position:"preposition",required:!1},{form:"aus",role:"source",position:"preposition",required:!1},{form:"mit",role:"style",position:"preposition",required:!1},{form:"um",role:"quantity",position:"preposition",required:!1},{form:"als",role:"method",position:"preposition",required:!1}]},fr:{code:"fr",name:"Français",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"sur",role:"event",position:"preposition",required:!0},{form:"à",role:"destination",position:"preposition",required:!1},{form:"dans",role:"destination",position:"preposition",required:!1},{form:"de",role:"source",position:"preposition",required:!1},{form:"avec",role:"style",position:"preposition",required:!1},{form:"par",role:"quantity",position:"preposition",required:!1},{form:"comme",role:"method",position:"preposition",required:!1}]},pt:{code:"pt",name:"Português",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"em",role:"event",position:"preposition",required:!0},{form:"para",role:"destination",position:"preposition",required:!1},{form:"em",role:"destination",position:"preposition",required:!1},{form:"de",role:"source",position:"preposition",required:!1},{form:"com",role:"style",position:"preposition",required:!1},{form:"por",role:"quantity",position:"preposition",required:!1},{form:"como",role:"method",position:"preposition",required:!1}]},id:{code:"id",name:"Bahasa Indonesia",wordOrder:"SVO",adpositionType:"preposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"pada",role:"event",position:"preposition",required:!0},{form:"ke",role:"destination",position:"preposition",required:!1},{form:"dari",role:"source",position:"preposition",required:!1},{form:"dengan",role:"style",position:"preposition",required:!1},{form:"sebagai",role:"method",position:"preposition",required:!1}]},qu:{code:"qu",name:"Runasimi",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","source","destination","event","action"],markers:[{form:"ta",role:"patient",position:"postposition",required:!0},{form:"man",role:"destination",position:"postposition",required:!0},{form:"manta",role:"source",position:"postposition",required:!0},{form:"pi",role:"event",position:"postposition",required:!0},{form:"wan",role:"style",position:"postposition",required:!1},{form:"hina",role:"method",position:"postposition",required:!1}]},sw:{code:"sw",name:"Kiswahili",wordOrder:"SVO",adpositionType:"preposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"kwenye",role:"event",position:"preposition",required:!0},{form:"kwa",role:"destination",position:"preposition",required:!1},{form:"kutoka",role:"source",position:"preposition",required:!1},{form:"na",role:"style",position:"preposition",required:!1},{form:"kama",role:"method",position:"preposition",required:!1}]},bn:{code:"bn",name:"বাংলা",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"কে",role:"patient",position:"postposition",required:!0},{form:"তে",role:"destination",position:"postposition",required:!0},{form:"এ",role:"event",position:"postposition",required:!0},{form:"থেকে",role:"source",position:"postposition",required:!0},{form:"দিয়ে",role:"style",position:"postposition",required:!1},{form:"জন্য",role:"duration",position:"postposition",required:!1}],rules:[{name:"event-handler",description:"Transform event handlers to Bengali SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"],optionalRoles:["patient"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},it:{code:"it",name:"Italiano",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"su",role:"event",position:"preposition",required:!0},{form:"in",role:"destination",position:"preposition",required:!1},{form:"a",role:"destination",position:"preposition",required:!1},{form:"da",role:"source",position:"preposition",required:!1},{form:"di",role:"source",position:"preposition",required:!1},{form:"con",role:"style",position:"preposition",required:!1},{form:"come",role:"method",position:"preposition",required:!1}]},ru:{code:"ru",name:"Русский",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"при",role:"event",position:"preposition",required:!0},{form:"в",role:"destination",position:"preposition",required:!1},{form:"на",role:"destination",position:"preposition",required:!1},{form:"к",role:"destination",position:"preposition",required:!1},{form:"из",role:"source",position:"preposition",required:!1},{form:"от",role:"source",position:"preposition",required:!1},{form:"с",role:"source",position:"preposition",required:!1},{form:"с",role:"style",position:"preposition",required:!1},{form:"со",role:"style",position:"preposition",required:!1},{form:"как",role:"method",position:"preposition",required:!1}]},uk:{code:"uk",name:"Українська",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"при",role:"event",position:"preposition",required:!0},{form:"в",role:"destination",position:"preposition",required:!1},{form:"на",role:"destination",position:"preposition",required:!1},{form:"до",role:"destination",position:"preposition",required:!1},{form:"з",role:"source",position:"preposition",required:!1},{form:"від",role:"source",position:"preposition",required:!1},{form:"із",role:"source",position:"preposition",required:!1},{form:"з",role:"style",position:"preposition",required:!1},{form:"із",role:"style",position:"preposition",required:!1},{form:"як",role:"method",position:"preposition",required:!1}]},vi:{code:"vi",name:"Tiếng Việt",wordOrder:"SVO",adpositionType:"preposition",morphology:"isolating",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"khi",role:"event",position:"preposition",required:!0},{form:"vào",role:"destination",position:"preposition",required:!1},{form:"cho",role:"destination",position:"preposition",required:!1},{form:"đến",role:"destination",position:"preposition",required:!1},{form:"từ",role:"source",position:"preposition",required:!1},{form:"khỏi",role:"source",position:"preposition",required:!1},{form:"với",role:"style",position:"preposition",required:!1},{form:"như",role:"method",position:"preposition",required:!1}]},hi:{code:"hi",name:"हिन्दी",wordOrder:"SOV",adpositionType:"postposition",morphology:"fusional",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"को",role:"patient",position:"postposition",required:!0},{form:"में",role:"destination",position:"postposition",required:!0},{form:"पर",role:"destination",position:"postposition",required:!1},{form:"पर",role:"event",position:"postposition",required:!0},{form:"से",role:"source",position:"postposition",required:!0},{form:"से",role:"style",position:"postposition",required:!1},{form:"साथ",role:"style",position:"postposition",required:!1},{form:"के रूप में",role:"method",position:"postposition",required:!1}],rules:[{name:"event-handler",description:"Transform event handlers to Hindi SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"],optionalRoles:["patient"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},tl:{code:"tl",name:"Tagalog",wordOrder:"VSO",adpositionType:"preposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["action","agent","patient","destination","source"],markers:[{form:"kapag",role:"event",position:"preposition",required:!0},{form:"sa",role:"destination",position:"preposition",required:!1},{form:"mula sa",role:"source",position:"preposition",required:!1},{form:"nang",role:"style",position:"preposition",required:!1},{form:"bilang",role:"method",position:"preposition",required:!1}],rules:[{name:"event-handler-vso",description:"VSO event handler: VERB TARGET kapag EVENT",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["action","patient","event"],insertMarkers:!0}}]},th:{code:"th",name:"ไทย",wordOrder:"SVO",adpositionType:"preposition",morphology:"isolating",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"เมื่อ",role:"event",position:"preposition",required:!0},{form:"ใน",role:"destination",position:"preposition",required:!1},{form:"ไปยัง",role:"destination",position:"preposition",required:!1},{form:"จาก",role:"source",position:"preposition",required:!1},{form:"ด้วย",role:"style",position:"preposition",required:!1},{form:"เป็น",role:"method",position:"preposition",required:!1}]},pl:{code:"pl",name:"Polski",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"gdy",role:"event",position:"preposition",required:!0},{form:"przy",role:"event",position:"preposition",required:!1},{form:"do",role:"destination",position:"preposition",required:!1},{form:"w",role:"destination",position:"preposition",required:!1},{form:"na",role:"destination",position:"preposition",required:!1},{form:"z",role:"source",position:"preposition",required:!1},{form:"od",role:"source",position:"preposition",required:!1},{form:"ze",role:"source",position:"preposition",required:!1},{form:"z",role:"style",position:"preposition",required:!1},{form:"ze",role:"style",position:"preposition",required:!1},{form:"jako",role:"method",position:"preposition",required:!1}]}};function $l(e){return Ml[e]}function Vl(e){const t={};for(const[r,n]of Object.entries(e.words))t[n]=r;const r={};if(e.categories)for(const[t,n]of Object.entries(e.categories)){r[t]={};for(const[e,s]of Object.entries(n))r[t][s]=e}const n={source:e.target,target:e.source,words:t};return Object.keys(r).length>0&&(n.categories=r),n}function Dl(e,t,r,n){const s={},i={};for(const r of["commands","modifiers","events","logical","temporal","values","attributes"]){const n=e[r],a=t[r];if(n&&a){i[r]={};for(const[e,t]of Object.entries(n)){const n=a[e];n&&t!==n&&(s[t]=n,i[r][t]=n)}}}return{source:r,target:n,words:s,categories:i}}var Bl=Dl(rl,ml,"ja","zh"),Fl=Vl(Bl),zl=Dl(ul,rl,"ko","ja"),Hl=Vl(zl),Ul={source:"es",target:"pt",words:{en:"em",decir:"dizer",disparar:"disparar",enviar:"enviar",tomar:"pegar",poner:"colocar",establecer:"definir",obtener:"obter",agregar:"adicionar",quitar:"remover",alternar:"alternar",ocultar:"esconder",mostrar:"mostrar",si:"se",menos:"a menos",repetir:"repetir",para:"para",mientras:"enquanto",hasta:"até",continuar:"continuar",romper:"parar",detener:"parar",esperar:"esperar",buscar:"buscar",llamar:"chamar",retornar:"retornar",hacer:"fazer",registrar:"registrar",lanzar:"lançar",atrapar:"capturar",medir:"medir","transición":"transição",incrementar:"incrementar",decrementar:"decrementar",predeterminar:"padrão",ir:"ir",copiar:"copiar",escoger:"escolher",intercambiar:"trocar",transformar:"transformar","añadir":"anexar",salir:"sair",a:"para",de:"de",dentro:"em",con:"com",como:"como",por:"por",clic:"clique",cambio:"mudança",entrada:"entrada","envío":"envio",carga:"carregar",enfoque:"foco",desenfoque:"desfoque",verdadero:"verdadeiro",falso:"falso",y:"e",o:"ou",no:"não",es:"é",segundos:"segundos",milisegundos:"milissegundos",nulo:"nulo",indefinido:"indefinido","vacío":"vazio"},categories:{commands:{en:"em",decir:"dizer",tomar:"pegar",poner:"colocar",establecer:"definir",obtener:"obter",agregar:"adicionar",quitar:"remover",ocultar:"esconder",si:"se",mientras:"enquanto",hasta:"até",romper:"parar",detener:"parar",llamar:"chamar",hacer:"fazer",lanzar:"lançar",atrapar:"capturar",escoger:"escolher",intercambiar:"trocar","añadir":"anexar",salir:"sair"},events:{clic:"clique",cambio:"mudança",carga:"carregar",enfoque:"foco",desenfoque:"desfoque"},logical:{verdadero:"verdadeiro",y:"e",o:"ou",no:"não",es:"é"}}},Wl=Vl(Ul),Jl=new Map([["ja->zh",Bl],["zh->ja",Fl],["ko->ja",zl],["ja->ko",Hl],["es->pt",Ul],["pt->es",Wl]]),Kl={en:{commands:{on:"on",tell:"tell",trigger:"trigger",send:"send",take:"take",put:"put",set:"set",get:"get",add:"add",remove:"remove",toggle:"toggle",hide:"hide",show:"show",if:"if",unless:"unless",repeat:"repeat",for:"for",while:"while",until:"until",continue:"continue",break:"break",halt:"halt",wait:"wait",fetch:"fetch",call:"call",return:"return",make:"make",log:"log",throw:"throw",catch:"catch",measure:"measure",transition:"transition",increment:"increment",decrement:"decrement",default:"default",go:"go",pushUrl:"pushUrl",replaceUrl:"replaceUrl",copy:"copy",pick:"pick",beep:"beep",js:"js",async:"async",render:"render",swap:"swap",morph:"morph",settle:"settle",append:"append",exit:"exit",install:"install"},modifiers:{to:"to",from:"from",into:"into",with:"with",at:"at",in:"in",of:"of",as:"as",by:"by",before:"before",after:"after",over:"over",under:"under",between:"between",through:"through",without:"without"},events:{click:"click",dblclick:"dblclick",mousedown:"mousedown",mouseup:"mouseup",mouseenter:"mouseenter",mouseleave:"mouseleave",mouseover:"mouseover",mouseout:"mouseout",mousemove:"mousemove",keydown:"keydown",keyup:"keyup",keypress:"keypress",focus:"focus",blur:"blur",change:"change",input:"input",submit:"submit",reset:"reset",load:"load",unload:"unload",resize:"resize",scroll:"scroll",touchstart:"touchstart",touchend:"touchend",touchmove:"touchmove",touchcancel:"touchcancel"},logical:{when:"when",where:"where",and:"and",or:"or",not:"not",is:"is",exists:"exists",matches:"matches",contains:"contains",includes:"includes",equals:"equals",has:"has",have:"have",then:"then",else:"else",otherwise:"otherwise",end:"end"},temporal:{seconds:"seconds",second:"second",milliseconds:"milliseconds",millisecond:"millisecond",minutes:"minutes",minute:"minute",hours:"hours",hour:"hour",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"true",false:"false",null:"null",undefined:"undefined",it:"it",its:"its",me:"me",my:"my",myself:"myself",you:"you",your:"your",yourself:"yourself",element:"element",target:"target",detail:"detail",event:"event",window:"window",document:"document",body:"body",result:"result",value:"value"},attributes:{class:"class",classes:"classes",style:"style",styles:"styles",attribute:"attribute",attributes:"attributes",property:"property",properties:"properties"},expressions:{first:"first",last:"last",next:"next",previous:"previous",prev:"prev",at:"at",random:"random",closest:"closest",parent:"parent",children:"children",within:"within",no:"no",empty:"empty",some:"some","starts with":"starts with","ends with":"ends with"}},es:el,ko:ul,zh:ml,fr:sl,de:al,ja:rl,ar:ll,tr:hl,id:yl,qu:vl,sw:wl,pt:El,it:Cl,vi:Al,pl:Sl,ru:Tl,uk:Ll,hi:Ol,bn:Pl,th:Nl,ms:Il,tl:jl},Zl=["commands","modifiers","events","logical","temporal","values","attributes","expressions"];function Yl(e){const t=e.filter(e=>!e.isBlank&&e.originalIndent.length>0);if(0===t.length)return e.map(()=>"");const r=t.map(e=>e.originalIndent.replace(/\t/g," ").length),n=Math.min(...r),s=n>0?n:4;return e.map(e=>{if(e.isBlank)return"";if(0===e.originalIndent.length)return"";const t=e.originalIndent.replace(/\t/g," ");return" ".repeat(Math.round(t.length/s))})}var Gl=new Set(["to","into","from","with","by","as","at","in","on","of","over"]);function Xl(e,t){const r=function(e){const t=new Set(Ho),r=Kl[e];return r?.commands&&Object.values(r.commands).forEach(e=>{"string"==typeof e&&t.add(e.toLowerCase())}),t}(t),n=e.split(/\s+/);if(0===n.length)return[e];const s=[];let i=[];const a=n[0]?.toLowerCase();let o=!ec.has(a);for(let e=0;n.length>e;e++){const t=n[e],a=t.toLowerCase();if(r.has(a)&&i.length>0){const e=i[i.length-1].toLowerCase();if(!o){o=!0,i.push(t);continue}if(!Gl.has(e)&&!r.has(e)){s.push(i.join(" ")),i=[t];continue}}i.push(t)}return i.length>0&&s.push(i.join(" ")),s.filter(e=>e.length>0)}function Ql(e,t){const r=Array.from(Go),n="en"===t?null:Kl[t];n?.modifiers?.then&&r.push(n.modifiers.then),n?.logical?.then&&r.push((n?.logical).then);const s=r.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=RegExp(`\\s+(${s.join("|")})\\s+`,"gi");return e.split(i).filter(e=>{const t=e.toLowerCase().trim();return t&&!r.some(e=>e.toLowerCase()===t)}).map(e=>e.trim()).filter(e=>e.length>0)}var ec=function(){const e=new Set;e.add("on");for(const t of Object.values(Ml))for(const r of t.markers)if("event"===r.role){const t=r.form.replace(/^-|-$/g,"").toLowerCase();t&&e.add(t),r.alternatives?.forEach(t=>{const r=t.replace(/^-|-$/g,"").toLowerCase();r&&e.add(r)})}return e}();function tc(e){const t={};e.markers.forEach(e=>{const r=e.form.replace(/^-|-$/g,"").toLowerCase();r&&(t[r]=e.role),e.alternatives?.forEach(r=>{const n=r.replace(/^-|-$/g,"").toLowerCase();n&&(t[n]=e.role)})});for(const[e,r]of Object.entries(Fo))e in t||(t[e]=r);return t}var rc={zh:["时","的","地","得"],ja:[],ko:[]},nc={zh:["当"],ar:["بـ","كـ","و"]};function sc(e,t,r){if(/^[#.<@]/.test(e))return e;if(/^\d+/.test(e))return e;const n="en"===t?null:Kl[t],s=Kl[r];if(!s)return e;let i=e;if(n){const t=function(e,t){const r=t.toLowerCase();for(const t of Zl){const n=e[t];for(const[e,s]of Object.entries(n))if(s.toLowerCase()===r)return{category:t,englishKey:e}}}(n,e);t&&(i=t.englishKey)}const a=function(e,t){const r=t.toLowerCase();for(const t of Zl){const n=e[t][r];if(n)return n}}(s,i);return a??e}var ic={en:{type:"suffix",marker:"'s"},es:{type:"preposition",marker:"de"},pt:{type:"preposition",marker:"de"},fr:{type:"preposition",marker:"de"},de:{type:"preposition",marker:"von"},ja:{type:"suffix",marker:"の"},ko:{type:"suffix",marker:"의"},zh:{type:"suffix",marker:"的"},ar:{type:"preposition",marker:"لـ"},tr:{type:"suffix",marker:"'ın"},id:{type:"preposition",marker:"dari"},qu:{type:"suffix",marker:"-pa"},sw:{type:"preposition",marker:"ya"}};function ac(e,t,r){const n=e.match(/^(.+)'s$/i);if(!n)return e;const s=n[1],i=ic[r]||ic.en,a={me:"my",it:"its",you:"your"},o=s.toLowerCase();if(a[o])return sc(a[o],"en",r);const l=sc(s,t,r);switch(i.type){case"suffix":return`${l}${i.marker}`;case"preposition":return`__POSS__${i.marker}__${l}__POSS__`;default:return l+"'s"}}var oc=/^(my|its|your|me|it|you)(\??\..+)$/i,lc={me:"my",it:"its",you:"your",my:"my",its:"its",your:"your"};function cc(e,t,r){const n=e.match(oc);if(!n)return null;const s=n[1].toLowerCase(),i=n[2],a=lc[s]||s,o=sc(a,t,r);if(o.includes(" "))return null;if(o!==a)return o+i;if(s!==a){const e=sc(s,t,r);if(e!==s&&!e.includes(" "))return e+i}return null}function uc(e,t,r){if(!e.includes(" ")){if(e.includes("'s"))return ac(e,t,r);const n=cc(e,t,r);return null!==n?n:sc(e,t,r)}const n=e.split(/\s+/),s=[];let i=0;for(;n.length>i;){const e=n[i];if(e.includes("'s")){const a=ac(e,t,r),o=a.match(/^__POSS__(.+)__(.+)__POSS__$/);if(o&&n.length>i+1){const e=o[1],a=o[2],l=sc(n[i+1],t,r);s.push(`${l} ${e} ${a}`),i+=2;continue}if(o){s.push(`${o[1]} ${o[2]}`),i++;continue}s.push(a),i++;continue}if(/^[#.<@]/.test(e)||/^\d+/.test(e)){s.push(e),i++;continue}if(/^["'].*["']$/.test(e)){s.push(e),i++;continue}const a=cc(e,t,r);null===a?(s.push(sc(e,t,r)),i++):(s.push(a),i++)}return s.join(" ")}var dc=class{constructor(e="en",t){const r=$l(e),n=$l(t);if(!r)throw Error("Unknown source locale: "+e);if(!n)throw Error("Unknown target locale: "+t);this.sourceProfile=r,this.targetProfile=n}transform(e){const t=function(e){if("en"===e)return"then";const t=Kl[e];return t&&(t.modifiers?.then||t.logical?.then)||"then"}(this.targetProfile.code);if(e.includes("\n")){const{parts:r,lineMetadata:n,partToLineIndex:s}=function(e,t){const r=e.split("\n"),n=[],s=[],i=[];for(let e=0;r.length>e;e++){const a=r[e],o=a.match(/^(\s*)/),l=o?o[1]:"",c=a.trim();if(n.push({content:c,originalIndent:l,isBlank:0===c.length}),c.length>0){const r=Ql(c,t);for(const n of r){const r=Xl(n,t);for(const t of r)s.push(t),i.push(e)}}}return{parts:s,lineMetadata:n,partToLineIndex:i}}(e,this.sourceProfile.code);return function(e,t,r,n){if(1>=t.filter(e=>!e.isBlank).length&&1>=e.length){const r=Yl(t),n=[];for(let s=0;t.length>s;s++)t[s].isBlank?n.push(""):e.length>0&&n.push(r[s]+e[0]);return n.join("\n")}const s=Yl(t),i=new Map;for(let t=0;e.length>t;t++){const n=r[t];i.has(n)||i.set(n,[]),i.get(n).push(e[t])}const a=[];for(let e=0;t.length>e;e++){const r=s[e];if(t[e].isBlank)a.push("");else{const t=i.get(e)||[];if(t.length>0){const e=t.join(` ${n} `);a.push(r+e)}}}return a.join("\n")}(r.map(e=>this.transformSingle(e)),n,s,t)}const r=function(e,t){const r=e.split(/\n/).map(e=>e.trim()).filter(e=>e.length>0),n=[];for(const e of r){const r=Ql(e,t);for(const e of r){const r=Xl(e,t);n.push(...r)}}return n}(e,this.sourceProfile.code);return r.length>1?r.map(e=>this.transformSingle(e)).join(` ${t} `):this.transformSingle(e)}transformSingle(e){const t=function(e,t="en"){const r=$l(t);if(!r)return null;const n=function(e,t){const r=[];let n="",s=!1,i=0;for(let t=0;e.length>t;t++){const a=e[t];"<"===a?(s=!0,i++):">"===a&&s&&(i--,0===i&&(s=!1)),/\s/.test(a)&&!s?n&&(r.push(n),n=""):n+=a}return n&&r.push(n),function(e,t){const r=rc[t]||[],n=nc[t]||[];if(0===r.length&&0===n.length)return e;const s=[];for(const t of e){if(/^[#.<@]/.test(t)||/^\d+/.test(t)){s.push(t);continue}let e=t,i="",a="";for(const t of n)if(e.startsWith(t)&&e.length>t.length){i=t,e=e.slice(t.length);break}for(const t of r)if(e.endsWith(t)&&e.length>t.length){a=t,e=e.slice(0,-t.length);break}i&&s.push(i),e&&s.push(e),a&&s.push(a)}return s}(r,t.code)}(e,r),s=function(e,t){if(0===e.length)return"unknown";const r=e[0].toLowerCase(),n=t.markers.find(e=>"event"===e.role&&"preposition"===e.position);return n&&r===n.form.toLowerCase()||ec.has(r)?"event-handler":Yo.has(r)?"conditional":"command"}(n,r);switch(s){case"event-handler":return function(e,t){const r=new Map;let n=ec.has(e[0]?.toLowerCase())?1:0;if(e[n]&&(r.set("event",{role:"event",value:e[n]}),n++),e[n]&&"from"===e[n].toLowerCase()&&e[n+1]){n++;const t=[];for(;e[n]&&!Ho.has(e[n].toLowerCase());)t.push(e[n]),n++;if(t.length>0){const e=t.join(" ");r.set("source",{role:"source",value:e,isSelector:/^[#.<@]/.test(e)})}}if(e[n]&&(r.set("action",{role:"action",value:e[n]}),n++),e[n]){const s=tc(t);let i="patient",a=[];for(let t=n;e.length>t;t++){const n=e[t],o=s[n.toLowerCase()];if(o){if(a.length>0){const e=a.join(" ");r.set(i,{role:i,value:e,isSelector:/^[#.<@]/.test(e)})}i=o,a=[]}else a.push(n)}if(a.length>0){const e=a.join(" ");r.set(i,{role:i,value:e,isSelector:/^[#.<@]/.test(e)})}}return{type:"event-handler",roles:r,original:e.join(" ")}}(n,r);case"command":return function(e,t){const r=new Map;if(0===e.length)return{type:"command",roles:r,original:""};r.set("action",{role:"action",value:e[0]});const n=tc(t);let s="patient",i=[];for(let t=1;e.length>t;t++){const a=e[t],o=n[a.toLowerCase()];if(o){if(i.length>0){const e=i.join(" ");r.set(s,{role:s,value:e,isSelector:/^[#.<@]/.test(e)})}s=o,i=[]}else i.push(a)}if(i.length>0){const e=i.join(" ");r.set(s,{role:s,value:e,isSelector:/^[#.<@]/.test(e)})}return{type:"command",roles:r,original:e.join(" ")}}(n,r);case"conditional":return function(e){const t=new Map;t.set("action",{role:"action",value:e[0]});const r=e.findIndex(e=>Go.has(e.toLowerCase()));if(r>1){const n=e.slice(1,r).join(" ");t.set("condition",{role:"condition",value:n})}return{type:"conditional",roles:t,original:e.join(" ")}}(n);default:return null}}(e,this.sourceProfile.code);if(!t)return e;!function(e,t,r){for(const[n,s]of e.roles)s.translated=s.value.includes("'s")?uc(s.value,t,r):s.isSelector||s.isLiteral?s.value:uc(s.value,t,r)}(t,this.sourceProfile.code,this.targetProfile.code);const r=this.findRule(t);if(r?.transform.custom)return r.transform.custom(t,this.targetProfile);const n=function(e,t){const r=[],n=new Set;for(const s of t){const t=e.get(s);t&&(r.push(t),n.add(s))}for(const[t,s]of e)n.has(t)||r.push(s);return r}(t.roles,r?.transform.roleOrder||this.targetProfile.canonicalOrder);return _l(r?.transform.insertMarkers??1?function(e,t,r){const n=[];for(const s of e){const e=t.find(e=>e.role===s.role);e?"preposition"===r?(e.form&&n.push(e.form),n.push(s.translated||s.value)):"postposition"===r?(n.push(s.translated||s.value),e.form&&n.push(e.form)):n.push(s.translated||s.value):n.push(s.translated||s.value)}return n}(n,this.targetProfile.markers,this.targetProfile.adpositionType):n.map(e=>e.translated||e.value))}findRule(e){if(this.targetProfile.rules)return this.targetProfile.rules.filter(t=>this.matchesRule(e,t)).sort((e,t)=>t.priority-e.priority)[0]}matchesRule(e,t){const{match:r}=t;for(const t of r.requiredRoles)if(!e.roles.has(t))return!1;if(r.commands&&r.commands.length>0){const t=e.roles.get("action");if(!t)return!1;const n=t.value.toLowerCase();if(!r.commands.some(e=>e.toLowerCase()===n))return!1}return!(r.predicate&&!r.predicate(e))}};function mc(e,t){return new dc("en",t).transform(e)}function pc(e,t){return new dc(t,"en").transform(e)}ql.register("en",Qo()),ql.register("es",tl),ql.register("ja",nl),ql.register("fr",il),ql.register("de",ol),ql.register("ar",cl),ql.register("ko",dl),ql.register("zh",pl),ql.register("tr",fl),ql.register("id",gl),ql.register("pt",xl),ql.register("qu",bl),ql.register("sw",kl);let hc="en";const fc=new class extends dr{constructor(e){super();for(const t of e)this.registerCategory(t)}}([rn,Zn,ci,Us,ds,js]),yc=function(e,t={}){const r=new hi;for(const t of e)r.register(t);return new Do({...t,registry:r})}([ua(),pa(),ja(),Ra(),Hi(),Wi(),Da(),io(),ao(),lo(),mo(),ho(),fo(),yo(),vo(),jo(),Ja(),Bo(),Za(),Ya(),So(),Ha(),Wa(),eo(),to(),ko(),Eo(),xo(),Mo(),Ga(),Oo(),bo(),No(),Io(),Ro(),Co(),Ao(),ro(),_o(),wo(),Vo(),Lo()],{expressionEvaluator:fc});function gc(e){const t=function(){if("en"!==hc)return ql.get(hc)}();return function(e,t){const r=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const r=e.length;for(;r>t.position&&(F(t),r>t.position);){const r=e[t.position];if("-"!==r||"-"!==D(t,1))if('"'!==r){if("'"===r||"'"===r){const e=D(t,1),r=t.tokens[t.tokens.length-1];if("s"!==e||!r||r.kind!==M.IDENTIFIER&&r.kind!==M.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)W(t);else{const e=t.position;B(t),B(t),z(t,M.OPERATOR,"'s",e)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===D(t,1)){const e=t.position;B(t),B(t),z(t,M.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],r=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),n=e&&e.kind===M.IDENTIFIER&&k.has(e.value.toLowerCase()),s=e&&e.kind===M.IDENTIFIER&&r.has(e.value.toLowerCase());if((!e||e.kind===M.OPERATOR&&")"!==e.value&&"]"!==e.value||n||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(te(D(t))||"{"===D(t))){K(t);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const e=t.tokens[t.tokens.length-1],r=e&&e.kind===M.IDENTIFIER&&q.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==M.IDENTIFIER&&")"!==e.value&&"]"!==e.value||r)&&r?(z(t,M.SYMBOL,"["),B(t)):(z(t,M.OPERATOR,"["),B(t));continue}if("]"!==r){if("$"===r){const e=D(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){ee(t);continue}}se(r)?G(t):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(z(t,M.UNKNOWN,r),B(t)):Q(t):X(t)}else z(t,M.OPERATOR,"]"),B(t)}else z(t,M.OPERATOR,"}"),B(t);else z(t,M.OPERATOR,"{"),B(t);else Y(t)}else K(t);else ne(t)?Z(t):G(t);else J(t)}else W(t);else U(t)}return t.tokens}(e);return new jt(r,t,e).parse()}(e,t?{keywords:t}:void 0)}const vc={parse:e=>gc(e),execute:async(e,t)=>{const r=Ft(t),n=gc(e);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await yc.execute(n.node,r)}},bc=new class{constructor(e){this.observer=null,this.initialized=!1,this.runtime=e}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,this.scanDocument(),this.observer=new MutationObserver(e=>{for(const t of e)"childList"===t.type?t.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(this.processElement(e),this.scanElement(e))}):"attributes"===t.type&&"_"===t.attributeName&&this.processElement(t.target)}),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(e){e.hasAttribute("_")&&this.processElement(e),e.querySelectorAll("[_]").forEach(e=>this.processElement(e))}processElement(e){const t=e.getAttribute("_");if(!t)return;const r=Bt(e);this.runtime.execute(t,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",e),console.error("Code:",t)})}}(vc),wc={getLocale:()=>hc,setLocale(e){if(ql.has(e)){if(hc=e,ql.setDefault(e),"undefined"!=typeof document){document.documentElement.setAttribute("lang",e);const t=$l(e);"rtl"===t?.direction?document.documentElement.setAttribute("dir","rtl"):document.documentElement.setAttribute("dir","ltr")}}else console.warn(`Locale '${e}' not registered. Available: ${ql.getAvailable().join(", ")}`)},getAvailableLocales:()=>ql.getAvailable(),detectAndSetLocale(){if("undefined"==typeof navigator)return"en";const e=navigator.languages||[navigator.language];for(const t of e){const e=t.split("-")[0].toLowerCase();if(ql.has(e))return this.setLocale(e),e}return"en"},registerLocale(e,t){ql.register(e,t)},toLocale:(e,t)=>mc(e,t||hc),toEnglish:(e,t)=>pc(e,t||hc),translate:function(e,t,r){return t===r?e:"en"===t?mc(e,r):"en"===r?pc(e,t):Jl.has(`${t}->${r}`)?function(e,t,r){const n=Jl.get(`${t}->${r}`);if(!n)return mc(pc(e,t),r);return e.split(/\s+/).map(e=>{if(e.startsWith("#")||e.startsWith(".")||e.startsWith("@"))return e;if(e.startsWith('"')||e.startsWith("'"))return e;const t=n.words[e];if(t)return t;const r=e.match(/^(.+?)(-.+)$/);if(r){const[,e,t]=r;return(n.words[e]||e)+t}return e}).join(" ")}(e,t,r):mc(pc(e,t),r)},createTransformer:(e,t)=>new dc(e,t),getProfile:$l,getSupportedGrammarLocales:function(){return Object.keys(Ml)},profiles:Ml,dictionaries:{en:{},es:el,ja:rl,fr:sl,de:al,ar:ll,ko:ul,zh:ml,tr:hl,id:yl,pt:El,qu:vl,sw:wl},createKeywordProvider:Xo},kc={runtime:vc,parse:e=>gc(e),compile:e=>{const t=performance.now();try{const r=gc(e);return{success:r.success,ast:r.node,errors:r.error?[r.error]:[],tokens:r.tokens||[],compilationTime:performance.now()-t}}catch(e){return{success:!1,ast:void 0,errors:[{message:e instanceof Error?e.message:e+"",line:1,column:1}],tokens:[],compilationTime:performance.now()-t}}},execute:async(e,t)=>{const r=Ft(t);if("string"==typeof e){const t=gc(e);if(!t.success||!t.node)throw Error(t.error?.message||"Parse failed");return await yc.execute(t.node,r)}if(e&&"object"==typeof e)return await yc.execute(e,r);throw Error("execute() requires a code string or compiled AST")},run:async(e,t)=>{const r=Ft(t),n=gc(e);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await yc.execute(n.node,r)},evaluate:async(e,t)=>kc.run(e,t),processNode:e=>{e===document?bc.scanAndProcessAll():e instanceof HTMLElement&&bc.processElement(e)},process:e=>kc.processNode(e),createContext:Bt,attributeProcessor:bc,version:"1.1.0-classic-i18n",i18n:wc,commands:["add","remove","toggle","put","hide","show","make","if","unless","repeat","break","continue","halt","return","exit","throw","set","get","increment","decrement","default","wait","fetch","trigger","send","transition","measure","settle","take","log","tell","call","copy","pick","beep","js","async","go","install","append","render","pseudo-command"],locales:["en","es","ja","fr","de","ar","ko","zh","tr","id","pt","qu","sw"],eval:async(e,t)=>vc.execute(e,t),init:e=>{!1!==e?.autoDetectLocale&&wc.detectAndSetLocale(),bc.init()}};return"undefined"!=typeof window&&(window.hyperfixi=kc,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{kc.init()}):kc.init()),kc}();
1
+ var hyperfixi=function(){"use strict";const e="then",t="else",r="end",n="and",s="for",i="while",a="until",o="forever",l="times",c="index",u="in",d="to",m="from",p="with",h="of",f="on",y="event",g="behavior",v="global",b="the",w="start",k=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"]),E=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","pick","start","swap","morph","push","replace","process"]),x=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),C="at end of",S=["into","before","after","at",x,C,"at the start of","at the end of"],A=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),T=e=>k.has(e.toLowerCase()),O=e=>E.has(e.toLowerCase()),P=e=>A.has(e.toLowerCase()),L=e=>N.has(e.toLowerCase()),N=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),I=new Set(["me","it","you","result","my","its","your"]),j=new Set(["and","or","not","no"]),R=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"]),_=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"]),q=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 M;!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"}(M||(M={}));const $=new Set(["+","-","*","/","mod"]),V=new Set(["ms","s","seconds","minutes","hours","days"]);function D(e,t=1){const r=e.position+t;return e.input.length>r?e.input[r]:""}function z(e){const t=e.input[e.position];return e.position++,"\n"===t?(e.line++,e.column=1):"\r"===t?("\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1):e.column++,t}function F(e){const t=e.input,r=t.length;for(;r>e.position;){const r=t[e.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;z(e)}}function B(e,t,r,n,s){const i=n??e.position-r.length,a=e.position;let o=e.column-r.length;if(void 0!==n){o=1;let t=-1;for(let r=0;n>r;r++)"\n"!==e.input[r]&&"\r"!==e.input[r]||(t=r);o=n-t}const l={kind:t,value:r,start:i,end:a,line:H(e,i),column:o};e.tokens.push(l)}function H(e,t){let r=1;for(let n=0;t>n&&e.input.length>n;n++){const t=e.input[n];"\n"===t?r++:"\r"===t&&(r++,e.input.length>n+1&&"\n"===e.input[n+1]&&n++)}return r}function U(e){const t=e.position;let r="";for(z(e),z(e);e.input.length>e.position&&"\n"!==e.input[e.position];)r+=z(e);B(e,M.COMMENT,"--"+r,t)}function W(e){const t=e.position,r=z(e);let n=r;for(;e.input.length>e.position;){const t=z(e);if(n+=t,t===r)break;"\\"===t&&e.input.length>e.position&&(n+=z(e))}B(e,M.STRING,n,t)}function J(e){const t=e.position;z(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){z(e);break}if("\\"===t){if(z(e),e.input.length>e.position){const t=z(e);switch(t){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=t}}}else r+=z(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-r.length}`);B(e,M.TEMPLATE,r,t)}function K(e){const t=e.position;let r=z(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(r+=z(e);e.input.length>e.position;){const t=e.input[e.position];if(r+=z(e),"}"===t)break}B(e,M.SELECTOR,r,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if(!re(t)&&"-"!==t&&"_"!==t&&":"!==t)break;r+=z(e)}B(e,M.SELECTOR,r,t)}}function G(e){const t=e.position;let r="";for(r+=z(e);e.input.length-1>e.position;){const t=e.input[e.position],n=e.input[e.position+1];if(r+=z(e),"/"===t&&">"===n){r+=z(e);break}}B(e,M.SELECTOR,r,t)}function Z(e){const t=e.position;let r=z(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!re(t)&&"_"!==t&&"-"!==t)break;r+=z(e)}B(e,M.SYMBOL,r,t)}function X(e){const t=e.position;let r="";const n=e.input[e.position];if(("'"===n||"'"===n)&&"s"===D(e,1))return r="'s",z(e),z(e),void B(e,M.OPERATOR,r,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(r=i,z(e),z(e),z(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,z(e),z(e)):r=z(e),B(e,M.OPERATOR,r,t)}function Y(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=z(e)}if(n>e.position&&"."===r[e.position]&&(e.position+1>=n||"."!==r[e.position+1]))for(s+=z(e);n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=z(e)}if(n>e.position){const t=r[e.position];if("e"===t||"E"===t){const t=n>e.position+1?r[e.position+1]:"",i=n>e.position+2?r[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=z(e),"+"!==r[e.position]&&"-"!==r[e.position]||(s+=z(e));n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=z(e)}}}const i=e.position;let a="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;a+=z(e)}V.has(a)?B(e,M.TIME,s+a,t):(e.position=i,B(e,M.NUMBER,s,t))}function Q(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=z(e)}const i=function(e,t,r){const n=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;const i=e.tokens[e.tokens.length-1];if(i&&(i.kind===M.IDENTIFIER||i.kind===M.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}F(e);let a="";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;a+=z(e)}if(a){const t=a.toLowerCase(),s=`${n} ${t}`,i=function(e,t,r,n){const s=t.toLowerCase(),i=r.toLowerCase();if("at"===s){const t=e.position;if("the"===i){F(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=z(e)}const s=r.toLowerCase();if("start"===s||"end"===s){F(e);let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;t+=z(e)}if("of"===t.toLowerCase())return B(e,M.IDENTIFIER,`at the ${s} of`,n),!0}return e.position=t,!1}if("start"===i||"end"===i){F(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=z(e)}return"of"===r.toLowerCase()?(B(e,M.IDENTIFIER,`at ${i} of`,n),!0):(e.position=t,!1)}}return!1}(e,n,t,r);if(i)return!0;const o=function(e,t,r){const n=e.position;let s=`${t} ${r}`,i=e.position;const a=[t,r];for(;8>a.length&&(F(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;t+=z(e)}if(!t)break;a.push(t.toLowerCase());const r=a.join(" ");R.has(r)&&(s=r,i=e.position)}return R.has(s)&&s!==`${t} ${r}`?(e.position=i,s):(e.position=n,null)}(e,n,t);if(o)return B(e,M.OPERATOR,o,r),!0;if(R.has(s))return B(e,M.OPERATOR,s,r),!0}return R.has(n)?(e.position=s,B(e,M.OPERATOR,t,r),!0):(e.position=s,!1)}(e,s,t);if(i)return;const a=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||j.has(t)||$.has(e)||$.has(t)||R.has(t)?M.OPERATOR:M.IDENTIFIER}(s);B(e,a,s,t)}function ee(e){const t=e.position,r=e.input,n=r.length;z(e);let s="$";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=z(e)}B(e,M.IDENTIFIER,s,t)}function te(e){return/[a-zA-Z]/.test(e)}function re(e){return/[a-zA-Z0-9]/.test(e)}function ne(e){let t=e.position+1,r=!1;for(;e.input.length>t;){const n=e.input[t];if("/"===n&&e.input.length>t+1&&">"===e.input[t+1])return r;if(re(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=!0,t++;else{if(" "!==n&&"\t"!==n)return!1;t++}if(t-e.position>50)return!1}return!1}function 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}(),ae=ie,oe=ie,le=ie,ce=ie,ue=(...e)=>{ae&&console.log("🔧",...e)},de=(...e)=>{oe&&console.log("🎯",...e)},me=(...e)=>{le&&console.log("📝",...e)},pe=(...e)=>{ce&&console.log("🚀",...e)};let he=!1,fe=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(he=!0,fe=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 r=e.toLowerCase();return!!/\bjs\b/.test(r)||!!/\btell\b/.test(r)||!!/\*[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 n=this.analyzer.analyze(e,this.language),s=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,a=!i&&n.confidence>0;if(he){const t={};if(n.command?.roles)for(const[e,r]of n.command.roles)t[e]=r.value;const o={input:e.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:a,command:n.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(e){if(!he)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",r=Math.round(100*e.confidence),n=Math.round(100*e.threshold),s=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),e.command&&console.log("Command: "+e.command),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),fe){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});fe.dispatchEvent(t)}}(o),r=o,ye.totalParses++,r.semanticSuccess?ye.semanticSuccesses++:r.fallbackTriggered?ye.semanticFallbacks++:ye.traditionalParses++,ye.confidenceHistory.push(r.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(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:!1,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var r}buildCommandNode(e){const{command:t}=e;if(!t)throw Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const r=[],n={};for(const[e,s]of t.roles){const i=this.semanticValueToExpression(s);switch(e){case"patient":case"event":r.push(i);break;case"destination":"put"===t.name?n.into=i:"add"===t.name||"append"===t.name||"prepend"===t.name?n.to=i:n.on=i;break;case"source":"fetch"===t.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[e]=i}}return{type:"command",name:t.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],r={},n=e.roles.get("loopType");n&&t.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("patient");"for"==(n?n.value+"":"")&&s&&t.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=e.roles.get("event");i&&t.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const a=e.roles.get("source");a&&t.push(this.semanticValueToExpression(a));const o=e.roles.get("quantity");o&&t.push(this.semanticValueToExpression(o));const l=e.roles.get("condition");return l&&(r.condition=this.semanticValueToExpression(l)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],r=e.roles.get("destination");if(r)if("property-path"===r.type){const e=r;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(r));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=e.roles.get("patient");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],r=e.roles.get("condition");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:e.name,args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(e.raw||"")}}parseExpressionString(e){let t=0;const r=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},n=()=>{r();const n=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(n,t)},s=()=>{const n=[];if(t++,r(),")"!==e[t])for(n.push(i()),r();","===e[t];)t++,r(),n.push(i()),r();return")"===e[t]&&t++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let a={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;e.length>t;){r();const i=e[t];if("."===i){t++;const e=n();e&&(a={type:"memberExpression",object:a,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;a={type:"callExpression",callee:a,arguments:s(),start:0,end:0,line:1,column:0}}}return a};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,r,n)=>{const s=n.parseExpr(e+1);return{type:"binaryExpression",operator:r.value,left:t,right:s,start:t.start,end:s.end??r.end,line:t.line??r.line,column:t.column??r.column}})}}}function ke(e,t){return{infix:{bp:[e+1,e],handler:(t,r,n)=>{const s=n.parseExpr(e);return{type:"binaryExpression",operator:r.value,left:t,right:s,start:t.start,end:s.end??r.end,line:t.line??r.line,column:t.column??r.column}}}}}function Ee(e,t){return{prefix:{bp:e,handler:t??((t,r)=>{const n=r.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:n,argument:n,prefix:!0,start:t.start,end:n.end??t.end,line:t.line,column:t.column}})}}}function xe(e){return(t,r,n)=>{const s=n.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 a=n.peek();return a&&"!"===a.value&&(n.advance(),i=!1),{type:"typeCheckExpression",value:t,typeName:s.value,nullOk:i,negated:e,start:t.start,end:s.end}}}const Ce=function(...e){const t=new Map;for(const r of e)for(const[e,n]of r){const r=t.get(e);t.set(e,r?{prefix:n.prefix??r.prefix,infix:n.infix??r.infix}:{...n})}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,r)=>{const n=r.parseExpr(31),s=r.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));r.advance();const i=r.parseExpr(31);return{type:"betweenExpression",value:e,min:n,max:i,negated:!1,start:e.start,end:i.end}})],["is not between",we(30,(e,t,r)=>{const n=r.parseExpr(31),s=r.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));r.advance();const i=r.parseExpr(31);return{type:"betweenExpression",value:e,min:n,max:i,negated:!0,start:e.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,r)=>(e.ignoringCase=!0,e)}}],["where",we(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:n,start:e.start,end:n.end}})],["sorted by",we(28,(e,t,r)=>{const n=r.parseExpr(29);let s="asc";const i=r.peek();if(i&&"string"==typeof i.value){const e=i.value.toLowerCase();"asc"===e||"ascending"===e?(r.advance(),s="asc"):"desc"!==e&&"descending"!==e||(r.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:n,order:s,start:e.start,end:n.end}})],["mapped to",we(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:n,start:e.start,end:n.end}})],["split by",we(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:n,start:e.start,end:n.end}})],["joined by",we(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:n,start:e.start,end:n.end}})],["+",{...we(40),...Ee(80)}],["-",{...we(40),...Ee(80)}],["*",we(50)],["/",we(50)],["%",we(50)],["mod",we(50)],["^",ke(60)],["**",ke(60)],["as",we(70,(e,t,r)=>{const n=r.parseExpr(71),s=r.peek();if(s&&":"===s.value&&n&&"identifier"===n.type){r.advance();const e=r.advance();e&&void 0!==e.value&&(n.name=`${n.name}:${e.value}`,n.end=e.end)}return{type:"asExpression",expression:e,targetType:n,start:e.start,end:n.end??t.end,line:e.line??t.line,column:e.column??t.column}})],["not",Ee(80)],["!",Ee(80)],["no",Ee(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,xe(!1))],["is an",we(30,xe(!1))],["is not a",we(30,xe(!0))],["is not an",we(30,xe(!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",Ee(80)]]),new Map([["=",ke(5)]])),Se=new Map,Ae=new Map,Te=new Map,Oe=new Set,Pe=new Set,Le=new Set,Ne=new Set;function Ie(e){return Se.get(e.toLowerCase())}function je(e){return Te.get(e)}function Re(e,t){if(0!==Pe.size)for(const r of Pe)try{r(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",e)}}function _e(e,t,r){if(0!==Le.size)for(const n of Le)try{n(e,t,r)}catch(e){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",e)}}function qe(e,t){if(0!==Ne.size)for(const r of Ne)try{r(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",e)}}function Me(e,t,r){if(e.globals.set(t,r),0!==Oe.size)for(const n of Oe)try{n(t,r,e)}catch(e){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",e)}}function $e(e){return e.kind===M.IDENTIFIER&&k.has(e.value.toLowerCase())}function Ve(e){return e.kind===M.IDENTIFIER&&q.has(e.value.toLowerCase())}function De(e){return e.kind===M.IDENTIFIER&&_.has(e.value.toLowerCase())}function ze(e){return e.kind===M.IDENTIFIER&&I.has(e.value.toLowerCase())}function Fe(e){return R.has(e.value.toLowerCase())}function Be(e){return e.kind===M.IDENTIFIER}function He(e){return e.kind===M.SELECTOR}function Ue(e){return e.kind===M.SELECTOR&&!e.value.startsWith("<")}function We(e){return e.kind===M.STRING||e.kind===M.NUMBER||e.kind===M.TEMPLATE}function Je(e){return e.kind===M.IDENTIFIER}function Ke(e){return e.kind===M.TIME}function Ge(e){return e.kind===M.SYMBOL}function Ze(e){return e.kind===M.COMMENT}function Xe(e){if(e.kind!==M.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(k.has(t)||q.has(t)||_.has(t)||I.has(t))}function Ye(e){return e.kind===M.STRING}function Qe(e){return e.kind===M.NUMBER}function et(e){if(e.kind===M.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function tt(e){return e.kind===M.TEMPLATE}function rt(e){return e.kind===M.SELECTOR&&e.value.startsWith("<")}function nt(e){return e.kind===M.SELECTOR&&e.value.startsWith("#")}function st(e){return e.kind===M.SELECTOR&&e.value.startsWith(".")}function it(e){return e.kind===M.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function at(e){if(e.kind!==M.OPERATOR)return!1;const t=e.value.toLowerCase();return!j.has(t)&&!R.has(t)}function ot(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function lt(e,t,r){return{type:"literal",value:e,raw:t,start:r.start,end:r.end,line:r.line,column:r.column}}function ct(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ut(e,t,r,n){return{type:"binaryExpression",operator:e,left:t,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function dt(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function mt(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function pt(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ht(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function ft(e,t,r){return{type:"propertyOfExpression",property:e,target:t,start:r.start,end:r.end,line:r.line,column:r.column}}function yt(e,t,r){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...r&&{source:r}}],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,n,t,r];function wt(e,t=[]){if(e.isAtEnd())return!0;for(const t of bt)if(e.check(t))return!0;for(const r of t)if(e.check(r))return!0;return!!e.checkIsCommand()}function kt(e,t=[]){if(!wt(e,t))return e.parseExpression()}function Et(e,t,r){return!!e.check(t)&&(e.advance(),r.push(e.createIdentifier(t)),!0)}function xt(e,t,r){for(const n of t)if(e.check(n))return e.advance(),r.push(e.createIdentifier(n)),n;return null}function Ct(e,t){return!!e.check(t)&&(e.advance(),!0)}function St(e){const t=e.savePosition();let r;if(e.checkIdentifierLike()){const n=e.peek().value;e.advance(),e.check(":")?(e.advance(),r=n):e.restorePosition(t)}const n=e.parseExpression();return void 0!==r?{name:r,value:n}:{value:n}}class At{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new At(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 At(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 At(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 At(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 Tt(e,t){const r=[];let n="";const s=e.peek().start||0,i=e.peek().line||1,a=e.peek().column||1;if(e.checkIdentifierLike()){for(n=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),n+=":",e.checkIdentifierLike()&&(n+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:r,value:n}=St(e);if(t.push(void 0!==r?{type:"objectLiteral",properties:[{key:{type:"identifier",name:r},value:n}],start:n.start,end:n.end,line:n.line,column:n.column}:n),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),r.push({type:"functionCall",name:n,args:t,start:s,end:e.getPosition().end,line:i,column:a})}else r.push({type:"string",value:n,start:s,end:e.getPosition().end,line:i,column:a})}const o=[...r];for(;!wt(e);){if(e.check("on")||e.check("to")){const t=e.advance().value;o.push(e.createIdentifier(t));continue}o.push(e.parsePrimary())}return At.fromIdentifier(t).withArgs(...o).endingAt(e.getPosition()).build()}function Ot(e,t){const r=[];if(e.check(b)){const t=e.advance();if(r.push({type:"identifier",name:b,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(y)){const t=e.advance();r.push({type:"identifier",name:y,start:t.start,end:t.end,line:t.line,column:t.column})}}return At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function Pt(n,s){const i=[];let a=!1;const o=n.savePosition();for(let t=0;500>t&&!n.isAtEnd();t++){const t=n.peek();if(t.value===e){a=!0;break}if(t.value===r||t.value===g||"def"===t.value||t.value===f)break;n.advance()}n.restorePosition(o);let l=!1;if(!a){const e=n.savePosition(),i=s.line,a=100;for(;!n.isAtEnd()&&a>n.current-e;){const e=n.peek(),s=e.value?.toLowerCase();if(s===g||"def"===s||s===f)break;if(s===t||s===r){e.line===i&&(l=!0);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==e.line&&e.line!==i){l=!0;break}n.advance()}n.restorePosition(e)}const c=a||l;let u;if(c)u=n.parseExpression();else{const t=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(e)&&r>i;){const e=n.savePosition();t.push(n.parseLogicalAnd()),n.savePosition()===e&&n.advance(),i++}if(0===t.length)throw Error("Expected condition after if/unless");u=1===t.length?t[0]:{type:"expression",tokens:t,start:t[0].start,end:t[t.length-1].end,line:s.line,column:s.column}}if(i.push(u),c){a&&n.advance();const e=[];for(;!n.isAtEnd()&&!n.check(t)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const t=n.parseCommand();t&&e.push(t)}if(0===e.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(dt(e,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}));let o=!1;if(n.check(t))if(n.advance(),n.check("if")){const e=n.peek();n.advance();const t=Pt(n,e);i.push(dt([t],{start:e.start,end:n.getPosition().end,line:e.line,column:e.column})),o=!0}else{const e=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const t=n.parseCommand();t&&e.push(t)}i.push(dt(e,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}o||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const e=n.parseCommand();i.push(dt([e],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return At.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function Lt(e,t){const r=[],n={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(r.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();r.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();n.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function Nt(e,t){const r=[],n=kt(e,[m]);n&&r.push(n),Et(e,m,r);const s=kt(e);return s&&r.push(s),At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function It(e,t){const r=[];if(e.check("between")){e.advance(),r.push(e.createIdentifier("between"));const i=kt(e,[n]);i&&r.push(i),Et(e,n,r);const a=kt(e,[m,f,s]);if(a&&r.push(a),xt(e,[m,f],r)){const t=kt(e);t&&r.push(t)}return At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}const i=kt(e,[m,f]);if(i&&r.push(i),xt(e,[m,f],r)){const t=kt(e);t&&r.push(t)}return At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function jt(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const s=e.peek();if(!s||!S.includes(s.value))return e.addError(`Expected operation keyword (${S.join(", ")}) after put expression, got: ${s?.value}`),null;let i=e.advance().value;const a=i.toLowerCase();"at start of"===a||"at the start of"===a?i=x:"at end of"===a||"at the end of"===a?i=C:"at"===i&&(e.check(w)||e.check(b)?(Ct(e,b),e.check(w)&&(e.advance(),e.check(h)&&(e.advance(),i=x))):e.check(r)&&(e.advance(),e.check(h)&&(e.advance(),i=C)));const o=e.parseExpression();return o?At.fromIdentifier(t).withArgs(n,e.createIdentifier(i),o).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Rt=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function _t(s,i){const a=s.savePosition();let o=null,l=[];try{o=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(),r=e.advance();return{type:"identifier",name:r.value,scope:t.value,start:t.start,end:r.end}}(s)??function(e){if(!e.check(b))return null;const t=e.savePosition();e.advance();const r=e.parseExpression();if(!r)return e.restorePosition(t),null;if("binaryExpression"===r.type&&r.operator===h){const e=r.left,t=r.right;return ft(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(d)?r:(e.restorePosition(t),null)}(s),o||(o=s.parseExpression())}catch{s.restorePosition(a),o=null}if(!o){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(d)||s.check(e)||s.check(n)||s.check(t)||s.check(r));)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")===h){const t=i[1],r=i[3];return{expression:ft(ct(e(t,"value")||e(t,"name")||"",{start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1}),{type:"idSelector"===r.type?"idSelector":"cssSelector",value:e(r,"value")||e(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:i[0].start??0,end:r.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);o=i.expression,l=i.tokens}if(!s.check(d)){const e=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+e)}s.advance();const c=s.parseExpression()??s.parsePrimary(),u=[];return o?u.push(o):l.length>0&&u.push(...l),u.push(s.createIdentifier(d)),c&&u.push(c),At.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function qt(e,t){const r=[];for(;!wt(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)r.push(e.parsePrimary());return At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}function Mt(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||wt(e)}function $t(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function Vt(e){const t=[],r=e.getPosition();do{if(!e.checkIdentifierLike())break;const r=e.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};e.consume(":","Expected ':' after property name in fetch named arguments");const s=e.parsePrimary();s&&t.push({key:n,value:s})}while(e.match(",")&&!e.isAtEnd());const n=e.getPosition();return{type:"objectLiteral",properties:t,start:r.start,end:n.end,line:r.line,column:r.column}}class Dt{constructor(e,t,r){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=r||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){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&&Ie(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(),r=t?Ie(t.value):void 0;if(r){const t=this.advance(),n=r(this.getContext(),t);n&&e.push(n);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")){me("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];me(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){me(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(me("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),r++,me(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),me(`✅ 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 me("⚠️ 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};me("✅ PARSER: No more event handlers, at end of input");break}}return me(`✅ 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 r=this.parseExpression();if(this.error)return{success:!1,node:r||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return r&&["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:r||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:r,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}`,r=this.prattCache.get(t);if(r)return this.current=r.endPos,r.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const n=this.peek(),s=Dt.PRATT_TABLE.get(n.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(),r=Dt.PRATT_TABLE.get(t.value);if(!r?.infix){if(ve.has(t.value)||be.has(t.value))break;break}const[n]=r.infix.bp;if(e>n)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){me("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()&&!Dt.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=r.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(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):T(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):P(e)}createCommandFromIdentifier(e){const t=[],r=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:!1,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return O(e)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return jt(s,i);case"trigger":case"send":return Tt(s,i);case"remove":return Nt(s,i);case"toggle":return It(s,i);case"set":return _t(s,i);case"halt":return Ot(s,i);case"measure":return Lt(s,i);case"js":return function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const s=e.peek().start,i=function(e,t){const r=e.getInputSlice(t);if(!r)return t;let n=0;for(;r.length>n;){const e=r[n];if("'"!==e&&"’"!==e&&"‘"!==e)if('"'!==e)if("`"!==e)if("/"===e&&r.length>n+1&&"/"===r[n+1])for(n+=2;r.length>n&&"\n"!==r[n];)n++;else if("/"===e&&r.length>n+1&&"*"===r[n+1]){for(n+=2;r.length>n&&("*"!==r[n]||n+1>=r.length||"/"!==r[n+1]);)n++;n+=2}else{if(!("e"!==e&&"E"!==e||n+3>r.length||"end"!==r.slice(n,n+3).toLowerCase()||0!==n&&/[a-zA-Z0-9_]/.test(r[n-1])||r.length>n+3&&/[a-zA-Z0-9_]/.test(r[n+3])))return t+n;n++}else{for(n++;r.length>n&&"`"!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&'"'!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&r[n]!==e;)"\\"===r[n]&&n++,n++;n++}}return t+r.length}(e,s);for(;!e.isAtEnd()&&!e.check(r)&&e.peek().start<i;)e.advance();e.consume(r,"Expected end after js code body");const a={type:"literal",value:e.getInputSlice(s,i).trim(),start:t.start,end:e.getPosition().end},o={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return At.fromIdentifier(t).withArgs(a,o).endingAt(e.getPosition()).build()}(s,i);case"tell":return function(s,i){const a=s.parseExpression();if(!a)throw Error("tell command requires a target expression");const o=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const e=s.parseCommand();if(!e)break;o.push(e)}catch{break}if(s.match(n))continue;if(s.check(e)||s.check(t)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===o.length)throw Error("tell command requires at least one command after the target");return At.fromIdentifier(i).withArgs(a,...o).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(e,t){const r=At.fromIdentifier(t);Ct(e,b);const n=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"===n){e.advance();const t=e.parsePrimary(),n=i();return r.withArgs(n).withModifier("variant",s("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===n){e.advance();const t=e.parsePrimary(),n=i();return r.withArgs(n).withModifier("variant",s("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===n){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const n=i(),a=r.withArgs(n).withModifier("variant",s("random"));return t&&a.withModifier("count",t),a.endingAt(e.getPosition()).build()}if("item"===n||"items"===n||"character"===n||"characters"===n){let t,n;e.advance(),e.match("at","from"),t=e.match("start")?s("start"):e.parsePrimary();let a=!1;(e.match("to")||e.match(".."))&&(e.match("end")?a=!0:n=e.parsePrimary());let o="default";e.match("inclusive")?o="inclusive":e.match("exclusive")&&(o="exclusive");const l=i(),c=r.withArgs(l).withModifier("variant",s("range")).withModifier("rangeStart",t).withModifier("rangeMode",s(o));return a?c.withModifier("rangeEnd",s("end")):n&&c.withModifier("rangeEnd",n),c.endingAt(e.getPosition()).build()}if("match"===n||"matches"===n){e.advance(),e.match("of");const t=e.parsePrimary();let a;e.matchOperator("|")&&(a=e.advance().value);const o=i(),l=r.withArgs(o).withModifier("variant",s("match"===n?"match":"matches")).withModifier("regex",t);return a&&l.withModifier("flags",s(a)),l.endingAt(e.getPosition()).build()}return qt(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 r={};if(e.match("using")){const t=e.parsePrimary();r.transitionName=t}const n=e.parseCommandListUntilEnd();return At.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(s,i);case"swap":case"morph":return function(e,t){const r=[];let n=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const s=t.value.toLowerCase();Rt.includes(s)&&(n=s,e.advance(),r.push(e.createIdentifier(n)))}}if("delete"===n){const n=e.parseExpression();return n&&r.push(n),At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(h)&&(e.advance(),r.push(e.createIdentifier("of")));const s=e.parseExpression();if(s&&r.push(s),!e.isAtEnd()&&e.check(p)){e.advance(),r.push(e.createIdentifier("with"));const t=e.parseExpression();t&&r.push(t)}return At.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition()).build()}(s,i);default:return qt(s,i)}}(this.getContext(),s)}parsePutCommand(e){return jt(this.getContext(),e)}parseSetCommand(e){return _t(this.getContext(),e)}parseHaltCommand(e){return Ot(this.getContext(),e)}parseMeasureCommand(e){return Lt(this.getContext(),e)}parseTriggerCommand(e){return Tt(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],r=()=>this.check("end")||e.some(e=>this.check(e));for(me("🔄 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!r();){me("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const n=this.checkIsCommand(),s=!n&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(n||s){me(n?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const r=this.error;try{const n=this.parseCommand();this.error&&this.error!==r&&(me("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=r),n&&(me("✅ Parsed command:",n.name),t.push(n),e=!0)}catch(e){me("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=r}}else this.checkIdentifier()&&me("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){me("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(me("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||r()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)me("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))me("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){me("📍 No separator and no command, breaking. Current token:",this.peek().value);break}me("✅ Next token is a command, continuing without separator")}}let n="end";for(const t of e)if(this.check(t)){n=t;break}return this.check("end")||e.some(e=>this.check(e))||(n=""),me("✅ parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",n,")"),{commands:t,terminator:n}}parseCommandListUntilEnd(){const{commands:e}=this.parseCommandListUntilTerminator([]);if(me('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw me('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return me('✅ Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),r="else"===t;if(!r){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:r}}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 r=[];let n="forever",d=null,h=null,f=null,g=null,v=null,w=null;if(e.check(s)){e.advance(),n=s;const t=e.peek();Be(t)&&(v=t.value,e.advance()),e.check(u)&&(e.advance(),g=e.parseExpression())}else if(e.check(u))e.advance(),n=s,v="it",g=e.parseExpression();else if(e.check(i))e.advance(),n=i,f=e.parseExpression();else if(e.check(a))if(e.advance(),n=a,e.check(y)){e.advance(),n="until-event";const t=e.peek();if(me("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!Be(t)&&!De(t))throw Error('Expected event name after "event"');if(d=t.value,e.advance(),me("✅ Got event name:",d,"Next token:",e.peek().value),me('🔍 Checking for "from", current token:',e.peek().value),e.check(m)){me('✅ Found "from", advancing...'),e.advance(),me('📍 After consuming "from", current token:',e.peek().value),Ct(e,b)&&me('✅ Found "the", advancing...');const t=e.peek();me("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),h=e.parsePrimary(),me("✅ After parsePrimary, eventTarget:",h)}else me('❌ No "from" found, skipping target parsing')}else f=e.parseExpression();else e.check(o)?(e.advance(),n=o):(w=e.parseExpression(),e.check(l)&&(e.advance(),n=l));let k,E=null;if(e.check(p)){const t=e.peekAt(1);t&&t.value.toLowerCase()===c&&(e.advance(),e.advance(),E=c)}else if(e.check(c)){e.advance();const t=e.peek();Be(t)?(E=t.value,e.advance()):E=c}let x=null,C=!1;if(n===o){const t=e.parseRepeatBody();if(k=t.commands,"else"===t.terminator)e.advance(),x=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(C=!0,n=t.terminator,e.advance(),f=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();k=t.commands,t.hasElse&&(e.advance(),x=e.parseCommandListUntilEnd())}r.push({type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column});const S={start:t.start,end:t.end,line:t.line,column:t.column};v&&r.push(mt(v,S)),g&&r.push(g),f&&r.push(f),w&&r.push(w),d&&r.push(mt(d,S)),h&&r.push(h),E&&r.push(mt(E,S)),r.push(dt(k,{...S,end:S.end||0})),null!==x&&r.push(dt(x,{...S,end:S.end||0}));const A=At.from(t).withArgs(...r);return C&&A.withModifier("bottomTested",{type:"literal",value:!0,...S}),A.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const r=[];let n=null,s=null;e.check("each")&&e.advance();const i=e.peek();if(!Be(i))throw Error('Expected variable name after "for"');if(n=i.value,e.advance(),!e.check(u))throw Error('Expected "in" after variable name in for loop');if(e.advance(),s=e.parseExpression(),!s)throw Error('Expected collection expression after "in"');let a=null;if(e.check(p)){const t=e.peekAt(1);t&&t.value.toLowerCase()===c&&(e.advance(),e.advance(),a=c)}else if(e.check(c)){e.advance();const t=e.peek();Be(t)?(a=t.value,e.advance()):a=c}const o=e.parseCommandListUntilEnd();r.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const l={start:t.start,end:t.end,line:t.line,column:t.column};return r.push(mt(n,l)),r.push(s),a&&r.push(mt(a,l)),r.push(dt(o,{...l,end:l.end||0})),At.from({...t,value:"repeat"}).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const r=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!wt(e)){const n=e.parseExpression();return r.push(n),At.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const n=[];do{const t=e.peek();if(!Be(t))throw Error('Expected event name after "for"');const r=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!Be(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(n.push({name:r,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(m)&&(e.advance(),Ct(e,b),s=e.parsePrimary());const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};r.push(ht(n.map(e=>pt([{key:ct("name",i),value:lt(e.name,`"${e.name}"`,i)},{key:ct("args",i),value:ht(e.params.map(e=>lt(e,`"${e}"`,i)),i)}],i)),i)),s&&r.push(s)}return At.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const r=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=e.advance().value,s=e.previous();if(r.push(ct(n,{start:s.start,end:s.end,line:s.line,column:s.column})),e.check("(")){e.advance();const n=[];for(;!e.isAtEnd()&&!e.check(")");)if(n.push(St(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),n.length>0){const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};r.push(pt(n.map(e=>({key:e.name?ct(e.name,s):lt("_positional","_positional",s),value:e.value})),s))}}return At.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const r=[],n={};let s=null;const i=e.peek();if(Be(i)||"*"===i.value){let t="";e.check("*")&&(t="*",e.advance());const r=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);r&&(t+=r,s={type:"string",value:t,start:i.start||0,end:e.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!e.check(d))throw Error('Expected "to" keyword after property in transition command');e.advance();const a=e.parsePrimary();if(n.to=a,e.check("over")){e.advance();const t=e.parsePrimary();n.over=t}if(e.check(p)){e.advance();const t=e.parsePrimary();n.with=t}return At.from(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const r=[];if(e.match("{"))r.push(e.parseCSSObjectLiteral());else{const t=kt(e,[d]);t&&r.push(t)}if(e.check(d)){e.advance();const t=kt(e);t&&r.push(t)}return At.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return Pt(this.getContext(),e)}parseRemoveCommand(e){return Nt(this.getContext(),e)}parseToggleCommand(e){return It(this.getContext(),e)}parseRegularCommand(e){return qt(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"),r=this.createMemberExpression(e,this.createIdentifier(t.value),!1);r.optional=!0,e=r}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()&&Be(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),r=this.processEscapeSequences(t);return this.createLiteral(r,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value.slice(1,-2).trim(),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(Ve)||this.matchPredicate(ze)||this.matchPredicate($e)||this.matchPredicate(De))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}return this.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,r=e.slice(1,-1);t=this.createLiteral(r,e)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(e.push({key:t,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(Xe))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);r=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=!1,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();n.push(e.value),"$"===e.value&&this.check("{")&&(s=!0),"{"===e.value&&i++,"}"===e.value&&i--}const a=n.join(""),o=s?{type:"templateLiteral",value:a,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(a,a);if(t.push({key:r,value:o}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),r=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const n=[];if(!this.check(")"))do{n.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column},arguments:n,isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]);let s,i,a;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),a=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==a&&{finallyHandler:a},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 r=t.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}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,r,n,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)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],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 r=e.callee.name,n=this.peek();if(!(Dt.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||Xe(n)&&!this.isCommand(n.value)||ze(n)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),Dt.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(r,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&&(me("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return me("⚠️ Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseEventHandler(){me("🔧 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],r=e?.value?.toLowerCase();r&&"of"!==r&&"in"!==r&&"from"!==r&&(this.advance(),t=!0,me("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const r=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(r),me("🔧 parseEventHandler: Parsed first event name: "+r);this.check("or");){this.advance(),me("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),me("🔧 parseEventHandler: Parsed additional event name: "+t)}let n;if(me("🔧 parseEventHandler: Total events parsed: "+e.join(", ")),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);n=e?.name,me(`🔧 parseEventHandler: Detected custom event source '${n}' 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"),me("🔧 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,me("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)i.prevent=!0,me("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)i.stop=!0,me("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),r=parseInt(t.value,10);if(isNaN(r))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(i.debounce=r,me(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(i.throttle=r,me(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else me(`🔧 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 r=this.advance(),n=(a=r.value).endsWith("ms")?parseInt(a,10):a.endsWith("seconds")||a.endsWith("s")?1e3*parseFloat(a):a.endsWith("minutes")?6e4*parseFloat(a):a.endsWith("hours")?36e5*parseFloat(a):a.endsWith("days")?864e5*parseFloat(a):parseInt(a,10);i[t]=n,me(`🔧 parseEventHandler: Parsed '${e} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);i[t]=r,me(`🔧 parseEventHandler: Parsed '${e} at ${r}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`)}var a;let o,l,c,u;if(t&&(i.once=!0),Object.keys(i).length>0&&me("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();l=e.value,me(`🔧 parseEventHandler: Parsed 'from' target: ${l} (kind: ${e.kind})`)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value,me("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(me("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),me("🔧 parseEventHandler: Parsed watch target expression"));const d=[];for(me(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(me(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){me("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())me("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){me("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const r=this.parseCommand();d.push(r);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(d.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.parseCommandWithErrorRecovery();e&&(d.push(e),me("✅ 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&&d.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){me("⚠️ 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(d.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 r={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};d.push(r)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const m=this.getPosition(),p={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:d,...s.length>0&&{params:s},...o&&{condition:o},...l&&{target:l},...c&&{attributeName:c},...u&&{watchTarget:u},...n&&{customEventSource:n},...Object.keys(i).length>0&&{modifiers:i},start:m.start,end:m.end,line:m.line,column:m.column};return me(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${u?"yes":"none"}`),p}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Xe(e)?(r.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),r=n.has(t.value);this.checkIsCommand()&&!r||(e.push(t.value),i=t.value,this.advance())}}const a={type:"eventHandler",event:t,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...r.length>0&&{args:r},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(a)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,r=this.parseCommand();for(this.error&&this.error!==t&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(me("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)me("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){me('✅ 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(),r=this.getPosition(),n="Expected command, got: "+t.value;this.addError(n);const s=yt(r,n,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,r){const n=e.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!wt(e,["catch","finally",...n.keywords])&&!vt(e.peek(),n.keywords);){const t=e.parsePrimary();if(!t)break;if(s.push(t),!e.match(",")&&vt(e.peek(),n.keywords))break}for(;!e.isAtEnd()&&vt(e.peek(),n.keywords);){const t=e.advance().value,r=e.parseExpression();if(r&&(i[t]=r),!vt(e.peek(),n.keywords))break}const a=At.from(t).withArgs(...s).endingAt(e.getPosition());return Object.keys(i).length>0&&a.withModifiers(i),a.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?(me(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(me(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return me("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),r=t.value.toLowerCase();if(e.includes(r))break;if($e(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 r={};let n=null;if(!e.isAtEnd()&&e.check("/")&&(n=function(e){const t=e.savePosition();let r="";for(;!e.isAtEnd()&&!Mt(e);)r+=e.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:t,end:e.savePosition()}:(e.restorePosition(t),null)}(e)),n||(n=e.parsePrimary()),!n)return e.addError("fetch requires a URL"),At.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(r.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||r.as){if(!e.check("with")||r.with){if(e.check("do")&&!r.doNotThrow){const t=e.peekAt(1),n=e.peekAt(2);if("not"===t?.value&&"throw"===n?.value){const t=e.advance();e.advance();const n=e.advance();r.doNotThrow={type:"literal",value:!0,start:t.start,end:n.end,line:t.line,column:t.column};continue}}break}e.advance(),r.with=$t(e)?Vt(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||Ct(e,"a")||Ct(e,"an"),r.as=e.parsePrimary();const s=At.from(t).withArgs(n).endingAt(e.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),e);const r=this.parseMultiWordCommand(e,t);if(r)return r;const n=t.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(e);if("for"===n)return this.parseForCommand(e);if("if"===n||"unless"===n)return this.parseIfCommand(e);if("wait"===n)return this.parseWaitCommand(e);if("install"===n)return this.parseInstallCommand(e);if("transition"===n)return this.parseTransitionCommand(e);if("add"===n)return this.parseAddCommand(e);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||function(e,t){return{type:"command",name:e,args:[],partial:!0,start:t.start,end:t.end,line:t.line,column:t.column}}(n,this.getPosition());const s=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const r=t.value,n="increment"===r?"+":"-";let s=!1;e.check(v)&&(s=!0,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let a;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${r} command`);a=t}else a=lt(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let o=i;s&&"identifier"===i.type&&(o={...i,scope:"global"});const l={start:t.start,end:e.previous().end,line:t.line,column:t.column},c=ut(n,i,a,l),u=[o,ct(d,l),c];return At.from(t).withName("set").withArgs(...u).withOriginalCommand(r).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 r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!t.includes(r.name??r.value))break}const i=this.getPosition();return{type:"command",name:t,args:s,isBlocking:!1,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(e),t)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;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 r="computed-"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(r),!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;L(t)&&me(`💡 Tip: CSS functions like ${t}() should be quoted for clean parsing. Use '${t}(...)' or \`${t}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return lt(e,t,this.getPosition())}createIdentifier(e){return ct(e,this.getPosition())}createBinaryExpression(e,t,r){return ut(e,t,r,this.getPosition())}createUnaryExpression(e,t,r){return function(e,t,r,n){return{type:"unaryExpression",operator:e,argument:t,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}createCallExpression(e,t){return function(e,t,r){return{type:"callExpression",callee:e,arguments:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.getPosition())}createMemberExpression(e,t,r){return function(e,t,r,n){return{type:"memberExpression",object:e,property:t,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,r){return{type:"possessiveExpression",object:e,property:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(me(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return me("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return me(`✅ 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 me(`✅ createProgramNode: Returning Program node with ${e.length} statements, type=${t.type}`),t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!at(t)||t.value!==e||(this.advance(),0))}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Ue)}matchSelector(){return this.matchPredicate(Ue)}checkAnySelector(){return this.checkPredicate(He)}checkLiteral(){return this.checkPredicate(We)}checkIdentifierLike(){return this.checkPredicate(Be)}checkIsCommand(){return this.checkPredicate($e)}checkCommandTerminator(){return this.checkPredicate(ot)}checkReference(){return this.checkPredicate(Je)}checkTimeExpression(){return this.checkPredicate(Ke)}checkEvent(){return this.checkPredicate(De)}checkContextVar(){return this.checkPredicate(ze)}checkComment(){return this.checkPredicate(Ze)}checkIdentifier(){return this.checkPredicate(Xe)}checkKeyword(){return this.checkPredicate(Ve)}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(rt)}matchQueryReference(){return this.matchPredicate(rt)}checkIdSelector(){return this.checkPredicate(nt)}checkClassSelector(){return this.checkPredicate(st)}checkCssSelector(){return this.checkPredicate(it)}checkBasicOperator(){return this.checkPredicate(at)}matchBasicOperator(){return this.matchPredicate(at)}matchTimeExpression(){return this.matchPredicate(Ke)}matchIdentifierLike(){return this.matchPredicate(Be)}matchComparisonOperator(){return this.matchPredicate(Fe)}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(Be,e)}consumeEvent(e){return this.consumePredicate(De,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let r=t.start||0,n=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1,0===r&&this.current>0&&(r=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;r=e.start||0,n=e.line||1,s=e.column||1,0===r&&(r=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const r=this.tokens[t];if(r&&("+"===r.value||"-"===r.value)){e=r;break}}r=e.start||0,n=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)},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;me("⚠️ synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();n.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:e,end:this.previous().end,line:t,column:r}}const n=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&n.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,r=this.advance().value;e+=t+'"'+(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const a=[];if(!this.check("]"))do{if(this.check("]"))break;a.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:a,start:e,end:this.previous().end,line:t,column:r}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),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 r=e.current+t;return r>=0&&e.tokens.length>r?e.tokens[r]: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 zt(e,t){const r=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const r=e.length;for(;r>t.position&&(F(t),r>t.position);){const r=e[t.position];if("-"!==r||"-"!==D(t,1))if('"'!==r){if("'"===r||"'"===r){const e=D(t,1),r=t.tokens[t.tokens.length-1];if("s"!==e||!r||r.kind!==M.IDENTIFIER&&r.kind!==M.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)W(t);else{const e=t.position;z(t),z(t),B(t,M.OPERATOR,"'s",e)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===D(t,1)){const e=t.position;z(t),z(t),B(t,M.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],r=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),n=e&&e.kind===M.IDENTIFIER&&k.has(e.value.toLowerCase()),s=e&&e.kind===M.IDENTIFIER&&r.has(e.value.toLowerCase());if((!e||e.kind===M.OPERATOR&&")"!==e.value&&"]"!==e.value||n||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(te(D(t))||"{"===D(t))){K(t);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const e=t.tokens[t.tokens.length-1],r=e&&e.kind===M.IDENTIFIER&&_.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==M.IDENTIFIER&&")"!==e.value&&"]"!==e.value||r)&&r?(B(t,M.SYMBOL,"["),z(t)):(B(t,M.OPERATOR,"["),z(t));continue}if("]"!==r){if("$"===r){const e=D(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){ee(t);continue}}se(r)?X(t):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(B(t,M.UNKNOWN,r),z(t)):Q(t):Y(t)}else B(t,M.OPERATOR,"]"),z(t)}else B(t,M.OPERATOR,"}"),z(t);else B(t,M.OPERATOR,"{"),z(t);else Z(t)}else K(t);else ne(t)?G(t):X(t);else J(t)}else W(t);else U(t)}return t.tokens}(e);return new Dt(r,t,e).parse()}Dt.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Dt.PRATT_TABLE=Ce,Dt.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Ft{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const r of this.afterExecuteHooks)await r(e,t)}async runOnError(e,t){let r=t;for(const t of this.onErrorHooks){const n=await t(e,r);n instanceof Error&&(r=n)}return r}shouldIntercept(e,t){for(const r of this.interceptCommandHooks)if(r(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Bt(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function Ht(e){return{ok:!0,value:e}}function Ut(e){return{ok:!1,error:e}}function Wt(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,r]of this.types)if(r.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),r=this.types.get(t);return r?.hyperscriptType??"unknown"}coerce(e,t,r){const n=this.types.get(t);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(n.isType(e))return e;if(this.config.cacheCoercions){const r=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(e),i=n.coerceFrom?.[s];if(i){const n=i(e,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(e,t){const r=this.types.get(t);if(!r)return!1;if(r.isType(e))return!0;const n=this.inferType(e);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(e,t){const r=this.types.get(t);return r&&(e===t||r.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const r=e;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,r)=>{t[r+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Kt(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 Zt(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 er=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function tr(e,t){return er.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const rr={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 r=e.getAttribute("name");r&&"value"in e&&t.append(r,e.value)}),t}(e)};function nr(e,t){if(t.startsWith("computed-")){const r=t.slice(9);return function(e){return e instanceof HTMLElement}(e)?getComputedStyle(e).getPropertyValue(r):void 0}if(t.startsWith("@"))return tr(e,t.slice(1));const r=rr[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return tr(e,t);const n=e[t];return Yt(n)?n.bind(e):n}function sr(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 ir(e,t){const r=e.registry?.get(t);if(!r)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 r}function ar(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 or(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 ur(e,t);const r=e;switch(e.type){case"literal":return function(e){return e.value}(r);case"identifier":return ur(r,t);case"binaryExpression":return async function(e,t){const r=e.operator,n=e.right,s=e.left;if("has"===r||"have"===r){const r=await or(e.left,t);return!!(r instanceof Element&&"selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("."))&&r.classList.contains(n.value.slice(1))}if("in"===r||"is in"===r){const r="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===r||"last"===r)&&Array.isArray(s.arguments)){const n=s.arguments[0];if("selector"===n?.type&&"string"==typeof n.value){const s=await or(e.right,t);if(s&&"function"==typeof s.querySelectorAll){const e=Array.from(s.querySelectorAll(n.value));return 0===e.length?null:"first"===r?e[0]:e[e.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const r=await or(e.right,t),n=r&&"function"==typeof r.querySelectorAll?r:null;if(n)return Array.from(n.querySelectorAll(s.value))}}const i=await or(e.left,t);if("and"===r){if(!i)return i;const r=await or(e.right,t);return ir(t,"and").evaluate(t,i,r)}if("or"===r){if(i)return i;const r=await or(e.right,t);return ir(t,"or").evaluate(t,i,r)}const a=await or(e.right,t),o=e=>"string"==typeof e?e.toLowerCase():e,l=e.ignoringCase?o(i):i,c=e.ignoringCase?o(a):a;switch(r){case"+":return"string"==typeof i||"string"==typeof a?(i??"")+""+(a??""):ar(await ir(t,"addition").evaluate(t,{left:i,right:a}));case"-":return ar(await ir(t,"subtraction").evaluate(t,{left:i,right:a}));case"*":return ar(await ir(t,"multiplication").evaluate(t,{left:i,right:a}));case"/":return ar(await ir(t,"division").evaluate(t,{left:i,right:a}));case"%":case"mod":return ar(await ir(t,"modulo").evaluate(t,{left:i,right:a}));case"^":case"**":return ar(await ir(t,"power").evaluate(t,{left:i,right:a}));case">":case"is greater than":return ir(t,"greaterThan").evaluate(t,i,a);case"<":case"is less than":return ir(t,"lessThan").evaluate(t,i,a);case">=":case"is greater than or equal to":return ir(t,"greaterThanOrEqual").evaluate(t,i,a);case"<=":case"is less than or equal to":return ir(t,"lessThanOrEqual").evaluate(t,i,a);case"==":case"is":case"am":case"equals":case"is equal to":return ir(t,"equals").evaluate(t,l,c);case"!=":case"is not":case"is not equal to":return ir(t,"notEquals").evaluate(t,l,c);case"===":case"really equals":case"is really equal to":return ir(t,"strictEquals").evaluate(t,l,c);case"!==":case"is not really equal to":return ir(t,"strictNotEquals").evaluate(t,l,c);case"as":return ir(t,"as").evaluate(t,i,pr(a));case"contains":return ir(t,"contains").evaluate(t,l,c);case"does not contain":case"does not include":return ir(t,"doesNotContain").evaluate(t,l,c);case"starts with":return ir(t,"startsWith").evaluate(t,l,c);case"ends with":return ir(t,"endsWith").evaluate(t,l,c);case"does not start with":return!await ir(t,"startsWith").evaluate(t,l,c);case"does not end with":return!await ir(t,"endsWith").evaluate(t,l,c);case"match":case"matches":return ir(t,"matches").evaluate(t,l,c);case"in":case"is in":return dr(i,a);case"is not in":return!dr(i,a);case"of":return a&&"object"==typeof a?a[i]:void 0;case"precedes":return mr(i,a,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!mr(i,a,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return mr(i,a,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!mr(i,a,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+r)}}(r,t);case"asExpression":return async function(e,t){const r=await or(e.expression,t),n=pr(e.targetType);return ir(t,"as").evaluate(t,r,n)}(r,t);case"betweenExpression":return async function(e,t){const r=await or(e.value,t),n=await or(e.min,t),s=await or(e.max,t),i=e=>"string"==typeof e?e.toLowerCase():e,[a,o,l]=e.ignoringCase?[i(r),i(n),i(s)]:[r,n,s],c=await ir(t,"between").evaluate(t,a,o,l);return e.negated?!c:c}(r,t);case"typeCheckExpression":return async function(e,t){const r=function(e,t,r){if(null==e&&r)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const n=globalThis[t];return"function"==typeof n&&e instanceof n}(await or(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!r:r}(r,t);case"collectionExpression":return async function(e,t){const r=await or(e.collection,t),n=async(e,r)=>or(e,{...t,it:r});switch(e.operator){case"where":return async function(e,t,r){const n=sr(e),s=[];for(const e of n)await r(t,e)&&s.push(e);return s}(r,e.right,n);case"sorted by":return async function(e,t,r,n){const s=[...sr(e)],i=await Promise.all(s.map(e=>n(t,e))),a=s.map((e,t)=>t);a.sort((e,t)=>{const r=i[e],n=i[t];return r===n?0:null==r?1:null==n||n>r?-1:1});const o=a.map(e=>s[e]);return"desc"===r?o.reverse():o}(r,e.right,e.order??"asc",n);case"mapped to":return async function(e,t,r){const n=sr(e);return Promise.all(n.map(e=>r(t,e)))}(r,e.right,n);case"split by":return i=await or(e.right,t),null==(s=r)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(e,t){const r=null==t?"":t+"";return sr(e).map(e=>null==e?"":e+"").join(r)}(r,await or(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var s,i}(r,t);case"unaryExpression":return async function(e,t){const r=e.operand??e.argument;if(!r)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const n=await or(r,t);switch(e.operator){case"not":case"!":return ir(t,"not").evaluate(t,n);case"no":return ir(t,"no").evaluate(t,n);case"-":return-n;case"+":return+n;case"exists":case"some":return ir(t,"exists").evaluate(t,n);case"does not exist":return ir(t,"doesNotExist").evaluate(t,n);case"is empty":return ir(t,"isEmpty").evaluate(t,n);case"is not empty":return ir(t,"isNotEmpty").evaluate(t,n);default:throw Error("Unknown unary operator: "+e.operator)}}(r,t);case"memberExpression":return async function(e,t){const r=await or(e.object,t);if(e.computed){const n=await or(e.property,t);return r?.[n]}{const t=e.property.name;if("string"==typeof t&&t.startsWith("@")){const e=t.substring(1);return r&&"function"==typeof r.getAttribute?r.getAttribute(e):void 0}return r instanceof Element&&"string"==typeof t?nr(r,t):r?.[t]}}(r,t);case"callExpression":return async function(e,t){const r=await or(e.callee,t);if(e.isConstructor&&"function"==typeof r)return new r(...await Promise.all(e.arguments.map(e=>or(e,t))));if("identifier"===e.callee.type){const n=e.callee.name,s=await async function(e,t,r){return yr.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:or(e,r))):Promise.all(e.map(e=>or(e,r)))}(e.arguments,n,t);switch(n){case"closest":return ir(t,"closest").evaluate(t,...s);case"previous":return ir(t,"previous").evaluate(t,...s);case"next":return ir(t,"next").evaluate(t,...s);case"first":return ir(t,"first").evaluate(t,...s);case"last":return ir(t,"last").evaluate(t,...s);default:if("function"==typeof r)return r(...s);throw Error("Cannot call non-function: "+n)}}if("function"==typeof r){const n=await Promise.all(e.arguments.map(e=>or(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const s=await or(e.callee.object,t);return r.apply(s,n)}return r(...n)}throw Error("Cannot call non-function")}(r,t);case"selector":return async function(e,t){const r=e.value,n="string"==typeof r?function(e){return e.replace(gr,"$1\\:")}(r):r,s=await ir(t,"elementWithSelector").evaluate(t,n);return!e.fromQuery&&"string"==typeof r&&r.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(r,t);case"possessiveExpression":return async function(e,t){const r=await or(e.object,t),n=e.property.name;return ir(t,"possessive").evaluate(t,r,n)}(r,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async r=>{const n={...t,event:r,target:r.target,currentTarget:r.currentTarget};for(const t of e.commands)await or(t,n)}}}(r,t);case"conditionalExpression":return async function(e,t){return await or(e.test,t)?or(e.consequent,t):e.alternate?or(e.alternate,t):void 0}(r,t);case"string":return r.value;case"arrayLiteral":return async function(e,t){const r=[];for(const n of e.elements)r.push(await or(n,t));return r}(r,t);case"objectLiteral":return async function(e,t){const r={};for(const n of e.properties){const e=n.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await or(e,t)+"",r[s]=await or(n.value,t)}return r}(r,t);case"attributeAccess":return async function(e,t){const r=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(r):"@"+r}(r,t);case"propertyOfExpression":return async function(e,t){const r=e.property;if("identifier"!==r?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const n=r.name,s=await or(e.target,t);if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);if(function(e){return e instanceof Element}(s))return nr(s,n);const i=s[n];return"function"==typeof i?i.bind(s):i}(r,t);case"templateLiteral":return async function(e,t){let r=e.value;return r=await fr(r,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,r)=>{try{if(/^\d+$/.test(r))return r;if(r.includes(".")){const e=r.split(".");let n=hr(e[0],t);for(let t=1;e.length>t&&null!=n;t++)n=n[e[t]];return(n??"")+""}return(hr(r,t)??"")+""}catch{return""}}),r=await fr(r,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,r,n)=>{const s=r||n;try{const e=await async function(e,t){const r=zt(e);if(!r.success||!r.node){const e=r.error??r.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const n=t.registry?t:{...t,registry:await cr()};return or(r.node,n)}(s,t);return e+""}catch{return"undefined"}}),r}(r,t);default:{const r=Ae.get(e.type);if(r)return r(e,t);throw Error("Unknown AST node type: "+e.type)}}}let lr=null;async function cr(){if(!lr){const e=await Promise.resolve().then(function(){return Yl});lr=e.createFullExpressionRegistry()}return lr}async function ur(e,t){const r=e.name;return"me"===r||"my"===r||"I"===r?ir(t,"me").evaluate(t):"you"===r||"your"===r||"yourself"===r?ir(t,"you").evaluate(t):"it"===r||"its"===r?ir(t,"it").evaluate(t):"window"===r?ir(t,"window").evaluate(t):"document"===r?ir(t,"document").evaluate(t):t.locals&&t.locals.has(r)?(qe(r,t),t.locals.get(r)):t.globals&&t.globals.has(r)?(r.startsWith("$")&&Re(r.slice(1),t),t.globals.get(r)):r.startsWith("$")&&t.globals&&t.globals.has(r.slice(1))?(Re(r.slice(1),t),t.globals.get(r.slice(1))):void 0!==t[r]?t[r]:"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:void 0}function dr(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 mr(e,t,r){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&r)}function pr(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 hr(e,t){return t.locals?.has(e)?(qe(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 fr(e,t,r){const n=[];let s;for(;null!==(s=t.exec(e));)n.push({index:s.index,length:s[0].length,replacement:await r(s[0],...s.slice(1))});let i=e;for(let e=n.length-1;e>=0;e--){const{index:t,length:r,replacement:s}=n[e];i=i.substring(0,t)+s+i.substring(t+r)}return i}const yr=new Set(["closest","previous","next"]),gr=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g");class vr{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,r,n,s){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,s),this.debugMode&&pe(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&pe("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&pe("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&pe("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,r){this.addCleanup(e,{type:"custom",cleanup:t,description:r||"Custom cleanup"})}registerGlobal(e,t="custom",r){this.globalCleanups.push({type:t,cleanup:e,description:r||"Global cleanup"}),this.debugMode&&pe("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e);r?r.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&pe(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let r=0;for(const e of t){try{e.cleanup(),r++}catch(e){this.debugMode&&pe("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&pe(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(e){let t=this.cleanupElement(e);const r=e.querySelectorAll("*");for(const e of r)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&pe("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&pe(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const br=new Map;function wr(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||br,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function kr(e){if(!e)return wr();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=wr(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}class Er{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const r=e.toLowerCase();this.sources.has(r)&&pe("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(r,t)}unregister(e){const t=e.toLowerCase(),r=this.sources.get(t);if(r){for(const[e,r]of this.subscriptions.entries())r.source===t&&(r.unsubscribe(),this.subscriptions.delete(e));return r.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,r){const n=this.get(e);if(!n)return void pe("[EventSourceRegistry] Unknown event source: "+e);n.initialize?.();const s=n.subscribe(t,r);return this.subscriptions.set(s.id,s),s}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,r]of this.sources.entries())if(r.supports?.(e)??r.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class xr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,r){const n=e.toLowerCase();this.providers.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}registerGlobal(e,t,r){const n=e.toLowerCase();this.globalProviders.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,r){const n=this.get(e);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const e of n.dependencies)await this.resolve(e,t,r);const i=await n.provide(t);return n.cache&&r&&r.set(s,i),i}resolveSync(e,t,r){const n=this.get(e);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(e){const t=this,r=new Map;return new Proxy(e,{get(e,n,s){if("string"==typeof n&&t.get(n))try{return t.resolveSync(n,e,r)}catch{return t.resolve(n,e,r)}return Reflect.get(e,n,s)},has:(e,r)=>!("string"!=typeof r||!t.has(r))||Reflect.has(e,r)})}async resolveAll(e){const t=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,e,t)}catch(e){pe(`[ContextProviderRegistry] Failed to resolve '${s}':`,e),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Cr={evaluate:(e,t)=>or(e,t)};class Sr{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 Ar{constructor(e,t,r){this.impl=e,this.hookRegistry=r??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,r={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:r,event:e.event??void 0,executionContext:e}}get name(){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 r=t[0],n=this.createHookContext(e,t,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(ue(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void ue(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=Sr.toTyped(e);let i,a;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ue(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers,n=t?.when||t?.where;if(n&&!await or(n,e))return void ue(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:t||{},commandName:r.commandName},Cr,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)a=await this.impl.execute(i,s);else{const e=Array.isArray(i)?i:[i];a=await this.impl.execute(s,...e)}return ue("CommandAdapterV2: Command result:",a),Object.assign(e,Sr.fromTyped(s,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,a),a}catch(e){if(Ir(e)||ue(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(n,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class Tr{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);pe(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=t.toLowerCase();pe(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,e);const n=new Ar(e,void 0,this.hookRegistry);this.adapters.set(r,n),k.add(r);const s=e.metadata?.aliases;if(s&&Array.isArray(s))for(const t of s){const r=t.toLowerCase();this.implementations.set(r,e),this.adapters.set(r,n),k.add(r)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const r=this.getAdapter(e);return r?r.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Or=null;function Pr(){return Or||(Or=function(e){const t=e?.commands??new Tr,r=e?.eventSources??new Er,n=e?.context??new xr,s=new Set,i={commands:t,eventSources:r,context:n,use(e){if(s.has(e.name))pe(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const r of e.commands)t.register(r);if(e.eventSources)for(const t of e.eventSources)r.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:r,options:s}of e.contextProviders)n.register(t,r,s);e.setup?.(i),s.add(e.name)}},reset(){s.clear()}};return i}()),Or}class Lr{constructor(e={}){this.contextCache=new WeakMap;const t=Pr();this.options={enableContextProviders:e.enableContextProviders??!0,enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,pe(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(e){if(!this.options.enableContextProviders)return e;const t=this.contextCache.get(e);if(t)return t;try{const t=this.contextRegistry.enhance(e);return this.contextCache.set(e,t),pe(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return pe("[RegistryIntegration] Failed to enhance context: "+(t instanceof Error?t.message:t+"")),e}}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return pe(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return pe(`[RegistryIntegration] Found event source '${r}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(e,t,r);if(!n)throw Error(`Failed to subscribe to event source '${e}'`);return pe(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,pe("[RegistryIntegration] Destroyed")}}function Nr(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 Ir(e){return e instanceof Error&&(null!==Bt(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function jr(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 Rr(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const _r=new WeakMap;class qr{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=br,this.hookRegistry=new Ft,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new vr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Lr("object"==typeof e.registryIntegration?e.registryIntegration:{}),pe("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,r)=>await this.installBehaviorOnElement(e,t,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const r of e)for(const e of r.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&pe(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}trackListener(e,t,r,n,s){this.cleanupRegistry.registerListener(e,t,r,n,s)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),pe("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){pe(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.registry||(t.registry=this.expressionRegistry),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,r)=>this.execute(e,r||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return pe("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(e,t);if(!Wt(r))throw Nr(r.error);return r.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const r={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(r,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=e,n=await this.executeCommandSequenceWithResult(r.commands||[],t);if(!Wt(n))throw Nr(n.error);return n.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(e,t);if(!Wt(r))throw Nr(r.error);return r.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:r,args:n,modifiers:s}=e,i=r.toLowerCase();if(ue(`RUNTIME BASE: Processing command '${i}'`),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:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(e){throw Ir(e)||this.logError(`Error executing command '${i}':`,e),e}}const a=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.logWarn(a),Error(a)}toSignal(e){const t=Bt(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:r,args:n,modifiers:s}=e,i=r.toLowerCase();if(ue(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const a=await this.registry.getAdapter(i);if(!a)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Ht(await a.execute(t,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return Ut(t);throw this.logError(`Error executing command '${i}':`,e),e}}async executeCommandSequenceWithResult(e,t){let r;for(const n of e){if(this.hasErrorDiagnostics(n)){const e=n.diagnostics?.[0];pe("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===n.type){const e=await this.processCommandWithResult(n,t);if(!Wt(e)){const r=e.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==r.returnValue&&Object.assign(t,{it:r.returnValue,result:r.returnValue}),Ht(r.returnValue)}}r=e.value}else{const e=await this.evaluateExpressionWithResult(n,t);if(!Wt(e))return e;r=e.value}}return Ht(r)}async evaluateExpression(e,t){const r=t.registry?t:{...t,registry:this.expressionRegistry},n=await or(e,r);return Rr(n)?await this.executeCommandFromPattern(n.command,n.selector,t):n}async evaluateExpressionWithResult(e,t){const r=t.registry?t:{...t,registry:this.expressionRegistry},n=await async function(e,t){try{return Ht(await or(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return Ut({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return Ut({type:"exit",returnValue:t.returnValue});if(t.isBreak)return Ut({type:"break"});if(t.isContinue)return Ut({type:"continue"});if(t.isReturn)return Ut({type:"return",returnValue:t.returnValue})}throw e}}(e,r);if(!Wt(n))return n;const s=n.value;if(Rr(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return Ht(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return Ut(t);throw e}}return Ht(s)}async executeCommandFromPattern(e,t,r){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},r)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let r;const n=[],s=[],i=[];for(const t of e.statements)"eventHandler"===t.type?n.push(t):"initBlock"===t.type?s.push(t):i.push(t);for(const e of n)try{await this.execute(e,t)}catch(e){if(Ir(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{r=await this.execute(e,t)}catch(e){if(Ir(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(Ir(e)&&(e.isHalt||e.isExit))break;throw e}return r}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const r of e.commands)try{await this.execute(r,t)}catch(e){if(Ir(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let r;for(const n of e.commands)try{r=await this.execute(n,t)}catch(e){if(Ir(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 r}async executeObjectLiteral(e,t){const r={};if(!e.properties)return r;for(const n of e.properties){let e;e="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,t)+"";const s=await this.execute(n.value,t);r[e]=s}return r}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:r,parameters:n=[],eventHandlers:s=[],initBlock:i}=e,a=e.imperativeInstaller;"function"==typeof a?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:a}),pe(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),pe(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(e,t,r){pe("BEHAVIOR: installBehaviorOnElement called: "+e);let n=this.behaviorRegistry.get(e);if(!n&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(n=this.behaviorRegistry.get(e)),!n))throw Error(`Behavior "${e}" not found`);if("imperative"===n.type)return void("function"==typeof n.install&&(pe(`BEHAVIOR: Installing imperative behavior '${e}'`),n.install(t,r),pe(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));pe("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(n.parameters)for(const e of n.parameters)i.locals.set(e,e in r?r[e]:void 0);for(const[e,t]of Object.entries(r))n.parameters?.includes(e)||i.locals.set(e,t);if(n.initBlock){pe("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),pe("BEHAVIOR: Init block completed for "+e)}catch(t){if(pe(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&Ir(t)))throw t}}if(pe(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers){const t=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}pe("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:r,events:n,commands:s,target:i,args:a,selector:o,attributeName:l,watchTarget:c,modifiers:u}=e,d=n&&n.length>0?n:[r];pe(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let m=[],p=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)p=window;else if("document"===e||"the document"===e||"body"===e)p=document;else if("me"===e||"myself"===e)m=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);pe(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(e)}`),this.isElement(e)?m=[e]:Array.isArray(e)?m=e.filter(e=>this.isElement(e)):"string"==typeof e&&(m=this.queryElements(e,t))}else pe(`BEHAVIOR: Target resolution: querying for '${i}'`),m=this.queryElements(i,t)}else m=t.me?[t.me]:[];if(0===m.length&&!p)return void pe(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&l)return void this.setupMutationObserver(m,l,s,t);if("change"===r&&c)return void this.setupChangeObserver(c,s,t);const h=e.customEventSource;if(h&&this.registryIntegration){pe(`BEHAVIOR: executeEventHandler - Using custom event source '${h}' for event '${r}'`);const e=async e=>{const n=new Map(t.locals),i={...t,locals:n,it:e,event:e},a=this.enhanceContext(i);pe(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},a)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${r}':`,e)}};try{const n=this.registryIntegration.subscribeToEventSource(h,{event:r,handler:e,target:i,selector:o},t);pe(`BEHAVIOR: Subscribed to custom event source '${h}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${h}' subscription ${n.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${h}':`,e)}return}const f=qr.createEventHandler(this,s,t,o,a);let y,g=null;if(u){let e=f;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>e(n),t)},g=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const t=u.throttle;let r=0;y=n=>{const s=Date.now();t>s-r||(r=s,e(n))}}else y=e}else y=f;const v=u?.once?{once:!0}:void 0;if(p){for(const e of d)p.addEventListener(e,y,v),m.length>0?this.cleanupRegistry.registerListener(m[0],p,e,y):this.cleanupRegistry.registerGlobal(()=>p.removeEventListener(e,y),"listener",`Global ${e} listener`);g&&(m.length>0?this.cleanupRegistry.registerCustom(m[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const e of m){for(const t of d){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const r of e){const e=new CustomEvent("resize",{detail:r,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,r,n,s){return async i=>{const a=_r.get(i)??0;if(a>=100)return;if(_r.set(i,a+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{pe(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const o=new Map(r.locals),l={...r,locals:o,it:i,event:i};o.has("target")||l.locals.set("target",i.target);const c=e.enhanceContext(l);if(s&&s.length>0){const e=i,t=e.detail;for(const r of s)c.locals.set(r,e[r]??t?.[r]??null)}for(const r of t)try{const t=jr(await e.execute(r,c));void 0!==t&&Object.assign(c,{it:t,result:t})}catch(t){if(Ir(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(c,{it:t.returnValue,result:t.returnValue});break}}throw e.logError("COMMAND FAILED:",t),t}}}setupMutationObserver(e,t,r,n){pe(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const s of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){de(`MUTATION DETECTED: attribute '${t}' changed on`,s);const e={...n,me:s,it:i,locals:new Map(n.locals)},a=i.oldValue,o=s.getAttribute(t);e.locals.set("oldValue",a),e.locals.set("newValue",o);const l=this.enhanceContext(e);for(const e of r)try{await this.execute(e,l)}catch(e){if(Ir(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing mutation handler command:",e)}}});e.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(s,e),pe("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){pe("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(e,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(e=>this.isElement(e))),pe(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const e of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){de("CONTENT CHANGE DETECTED on",e,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",e);const i=s.oldValue,a=e.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",a);const o=this.enhanceContext(n);for(const e of t)try{await this.execute(e,o)}catch(e){if(Ir(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing change handler command:",e)}}});n.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),pe("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=e;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return pe(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function Mr(...e){const t=new Map;for(const r of e)for(const[e,n]of Object.entries(r))t.set(e,n);return t}class $r{constructor(e){this.observer=null,this.initialized=!1,this.runtime=e}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,this.scanDocument(),this.observer=new MutationObserver(e=>{for(const t of e)"childList"===t.type?t.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(this.processElement(e),this.scanElement(e))}):"attributes"===t.type&&"_"===t.attributeName&&this.processElement(t.target)}),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(e){e.hasAttribute("_")&&this.processElement(e),e.querySelectorAll("[_]").forEach(e=>this.processElement(e))}processElement(e){const t=e.getAttribute("_");if(!t)return;const r=wr(e);this.runtime.execute(t,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",e),console.error("Code:",t)})}}const Vr={1:"one",2:"two",3:"three",4:"four",5:"five"};function Dr(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${s=t,Vr[s]??s+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var s;return null}function zr(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function Fr(e,t,r){return Dr(e,1,t,r)??zr(e,0,t,r)}function Br(e,t){return Dr(e,2,t,"left, right")}function Hr(){return null}function Ur(e,t,r,n){return e.length>t?`${r} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${n?` (${n})`:""}`:null}function Wr(e,t,r,n,s){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${s?` (${s})`:""}`:null}function Jr(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const Kr="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 Gr;function Zr(){return Gr({validate:e=>({success:!0,data:e})})}function Xr(e,t){if(Kr)return Zr();const r=Gr({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:Jr("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(t?.strict){const t=Object.keys(e),r=Object.keys(n).filter(e=>!t.includes(e));if(r.length>0)return{success:!1,error:Jr("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=n[t];if(!(t in n)&&!r._isOptional)return{success:!1,error:Jr("missing-argument",`Required field "${t}" is missing`,t)};const i=r.validate(e);if(!i.success)return{success:!1,error:Jr("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 r.strict=()=>Xr(e,{strict:!0}),r}Gr=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,_isOptional:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return Gr(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&e>n.data.length?{success:!1,error:Jr("runtime-error",`String must be at least ${e} characters long`)}:n}};return Gr(r)}),e.max||(e.max=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&n.data.length>e?{success:!1,error:Jr("runtime-error",`String must be at most ${e} characters long`)}:n}};return Gr(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,_defaultValue:e,_hasDefault:!0,validate:r=>void 0===r?{success:!0,data:e}:t(r)};return Gr(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?e(s.data)?s:{success:!1,error:Jr("runtime-error",t||"Refinement validation failed")}:s}};return Gr(n)}),new Proxy(e,{get:(e,t,r)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,r):function(...e){return r}})};const Yr=e=>function(e={}){return Kr?Zr():Gr({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:Jr("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:Jr("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:Jr("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:Jr("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:Jr("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),Qr=e=>function(e={}){return Kr?Zr():Gr({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:Jr("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:Jr("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:Jr("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{}),en=()=>Kr?Zr():Gr({validate:e=>"boolean"!=typeof e?{success:!1,error:Jr("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),tn=e=>Xr(e),rn=e=>function(e){return Kr?Zr():Gr({validate:t=>{if(!Array.isArray(t))return{success:!1,error:Jr("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:Jr("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const r=[];for(let n=0;e.length>n;n++){const s=e[n].validate(t[n]);if(!s.success)return{success:!1,error:Jr("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(e),nn=()=>Zr(),sn=()=>Zr(),an=()=>function(e,t="Custom validation failed"){return Kr?Zr():Gr({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:Jr("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class on{trackPerformance(e,t,r,n){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(e,t,r,n=(r?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:t,duration:Date.now()-t,success:r})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||Gt(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,r,n,s=[]){return{success:!1,error:{name:e,type:t,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!==e&&"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":Kt(e)?"String":Gt(e)?"Number":Zt(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Kt(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(Kt(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Zt(e)?e?1:0:null}}const ln=tn({selector:Yr().min(1),single:en().optional().default(!1)});new class extends on{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=an(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends on{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=an(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends on{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=an(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.it,s={success:!0,value:n,type:this.inferType(n)};return this.trackPerformance(e,t,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,s,r),s}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends on{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=ln,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const r=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,n,r),n}let n;if(t.single)n=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));n=e.length>0?e:null}const s={success:!0,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(e,t,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=t.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}};const cn={name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:Hr},un={name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:Hr},dn={name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Hr},mn={name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Hr},pn={name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Hr},hn={name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:e=>Fr(e,"querySelector","selector")},fn={name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>Fr(e,"querySelectorAll","selector")},yn={name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:e=>Fr(e,"getElementById","ID")},gn={me:cn,you:un,it:dn,its:mn,result:pn,querySelector:hn,querySelectorAll:fn,getElementById:yn,getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:e=>Fr(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let r=t[0];if(r&&"object"==typeof r&&"type"in r){const e=r;"identifier"===e.type&&e.name?r=e.name:"literal"===e.type&&"string"==typeof e.value&&(r=e.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return e.me?e.me.closest(r):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:Hr},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Hr},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Hr},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>Fr(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||e.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(s).getPropertyValue(e)||""}return s.style.getPropertyValue(r)||void 0}},validate:e=>Wr(e,1,2,"styleRef","property, optional element")??zr(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===r&&e.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=>Dr(e,2,"possessiveStyleRef","possessor, property")??zr(e,0,"possessiveStyleRef","possessor")??zr(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===n&&e.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=>Dr(e,2,"ofStyleRef","property, reference")??zr(e,0,"ofStyleRef","property")??zr(e,1,"ofStyleRef","reference")}};class vn{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[r,n]of this.accessOrder)t>n&&(t=n,e=r);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,r)=>e+(t-r.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const bn=new class{constructor(){this.domQueryCache=new vn(200,3e3),this.exprResultCache=new vn(500,2e3),this.cssMatchCache=new vn(100,5e3),this.formValueCache=new vn(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(e);return this.domQueryCache.set(t,n),n}querySelectorAll(e){const t="querySelectorAll:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,n),n}getElementById(e){const t="getElementById:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(e);return this.domQueryCache.set(t,n),n}getElementsByClassName(e){const t="getElementsByClassName:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,n),n}matches(e,t){const r=`matches:${this.getElementCacheKey(e)}:${t}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(r,s),s}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),r=this.formValueCache.get("formValue:"+t);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(e,t){const r=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+r,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(e.cache.keys()))"string"==typeof r&&r.includes(t)&&e.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),r=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${r}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([r,n])=>{e-n.timestamp>t.ttl&&t.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{bn.cleanup()},1e4);const wn=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const r=performance.now()-t;return this.startTimes.delete(e),r}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=bn.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 kn(){bn.cleanup(),wn.getMetrics().memoryUsage>52428800&&wn.reset()}let En=null;function xn(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const r=e.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${t} cannot be converted to number: "${e}"`);return n}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const r=e[0];if(Array.isArray(r))throw Error(t+" is a nested array, cannot convert to number");return xn(r,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 r=parseFloat(e);if(!isNaN(r))return r}}const r=e.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Cn(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?null:r}return"boolean"==typeof e?e?1:0:null==e?0:null}function Sn(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 An(e){try{return xn(e,"_"),!0}catch{return!1}}function Tn(e,t,r){if("==="===r)return e===t;if("!=="===r)return e!==t;if(null==e||null==t)return function(e,t,r){if(null==e&&null==t)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,r);const[n,s]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const r=parseFloat(e),n=parseFloat(t);return isNaN(r)||isNaN(n)?[e,t]:[r,n]}const r=Cn(e),n=Cn(t);return null!==r&&null!==n?[r,n]:[e+"",t+""]}(e,t);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return On(e,t);case"!=":return!On(e,t);default:return!1}}function On(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 r=parseFloat(t);return!isNaN(r)&&e===r}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);return!isNaN(r)&&r===t}return"boolean"==typeof e?On(e?1:0,t):"boolean"==typeof t?On(e,t?1:0):e+""==t+""}function Pn(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function Ln(e,t,r=[],n="error"){return{type:e,message:t,suggestions:r,severity:n}}function Nn(e,t,r,n,s,i=!0,a){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==a&&{error:a}}),n}"undefined"!=typeof window&&function(e=3e4){En&&clearInterval(En),En=setInterval(kn,e)}();const In=tn({left:nn().describe("Left operand value"),right:nn().describe("Right operand value")}).strict(),jn=tn({operand:nn().describe("Operand value to negate")}).strict();function Rn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new class extends on{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=In,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(t.left);if(!s)return this.trackSimple(e,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),a=s&&i;return this.trackSimple(e,r,!0,"boolean"),this.success(a,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends on{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=In,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(t.left);if(s)return this.trackSimple(e,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),a=s||i;return this.trackSimple(e,r,!0,"boolean"),this.success(a,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends on{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=jn,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=!this.toBoolean(t.operand);return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const _n=rn([nn(),nn()]),qn=rn([nn(),Yr()]),Mn={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return Nn(this,e,[t,r],t==r,n)}catch(s){throw Nn(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Br(e,"equals"),inputSchema:_n,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"]}},$n={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,r){const n=e.evaluationHistory,s=t===r;return n&&Nn(this,e,[t,r],s,n?Date.now():0),s},validate:e=>Br(e,"strictEquals")},Vn={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,r){const n=e.evaluationHistory,s=t!=r;return n&&Nn(this,e,[t,r],s,n?Date.now():0),s},validate:e=>Br(e,"notEquals")},Dn={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,r){const n=e.evaluationHistory,s=t!==r;return n&&Nn(this,e,[t,r],s,n?Date.now():0),s},validate:e=>Br(e,"strictNotEquals")},zn={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=Tn(t,r,"<");return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Br(e,"lessThan")},Fn={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=Tn(t,r,"<=");return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Br(e,"lessThanOrEqual")},Bn={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=Tn(t,r,">");return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Br(e,"greaterThan")},Hn={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=Tn(t,r,">=");return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Br(e,"greaterThanOrEqual")},Un={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return Nn(this,e,[t,r],t&&r,n)}catch(s){throw Nn(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Br(e,"and"),inputSchema:_n,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"]}},Wn={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,r){const n=e.evaluationHistory,s=t||r;return n&&Nn(this,e,[t,r],s,n?Date.now():0),s},validate:e=>Br(e,"or")},Jn={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const r=e.evaluationHistory,n=!t;return r&&Nn(this,e,[t],n,r?Date.now():0),n},validate:e=>Dr(e,1,"not","operand")},Kn={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let s;return s=null==t||(Kt(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Xt(t)||0!==Object.keys(t).length)),r&&Nn(this,e,[t],s,n),s},validate:e=>Dr(e,1,"isEmpty","value")},Gn={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let s;return s=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:(Kt(t),!1)),r&&Nn(this,e,[t],s,n),s},validate:e=>Dr(e,1,"no","value")},Zn={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,s=!await Kn.evaluate(e,t);return r&&Nn(this,e,[t],s,n),s},validate:e=>Dr(e,1,"isNotEmpty","value")},Xn={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const r=e.evaluationHistory,n=null!=t;return r&&Nn(this,e,[t],n,r?Date.now():0),n},validate:e=>Dr(e,1,"exists","value")},Yn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const r=e.evaluationHistory,n=null==t;return r&&Nn(this,e,[t],n,r?Date.now():0),n},validate:e=>Dr(e,1,"doesNotExist","value")},Qn={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0;let i;if(t&&r){if(Rn(t)&&Rn(r))return i=t.contains(r),n&&Nn(this,e,[t,r],i,s),i;if(Kt(t)&&t.match(/^[.#][\w-]+$/)){const a=document.querySelector(t);if(a&&Rn(r))return i=a.contains(r),n&&Nn(this,e,[t,r],i,s),i;if(a&&Kt(r)&&r.match(/^[.#][\w-]+$/)){const o=document.querySelector(r);return i=!!o&&a.contains(o),n&&Nn(this,e,[t,r],i,s),i}}if(Kt(r)&&r.match(/^[.#][\w-]+$/)&&Rn(t)){const a=document.querySelector(r);return i=!!a&&t.contains(a),n&&Nn(this,e,[t,r],i,s),i}}return i=Kt(t)&&Kt(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!Xt(t)||!Kt(r))&&r in t,n&&Nn(this,e,[t,r],i,s),i},validate:e=>Dr(e,2,"contains","container, value")},es={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!await Qn.evaluate(e,t,r);return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Dr(e,2,"doesNotContain","container, value")},ts={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!(!Kt(t)||!Kt(r))&&t.startsWith(r);return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Dr(e,2,"startsWith","str, prefix")},rs={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!(!Kt(t)||!Kt(r))&&t.endsWith(r);return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Dr(e,2,"endsWith","str, suffix")},ns={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,r,n){const s=e.evaluationHistory;let i=r,a=n;if(null!=i&&null!=a&&i>a){const e=i;i=a,a=e}const o=null!=i&&null!=a&&t>=i&&a>=t;return s&&Nn(this,e,[t,r,n],o,s?Date.now():0),o},validate:e=>Dr(e,3,"between","value, min, max")},ss={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let s;if(t instanceof Element&&Kt(r)){const e=r;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{s=function(e,t){return bn.matches(e,t)}(t,e)}catch(e){s=!1}else s=!1}else if(Kt(t)&&Kt(r)){const e=t,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(e)}catch(t){s=e.includes(n)}}else s=!1;return Nn(this,e,[t,r],s,n)}catch(s){throw Nn(this,e,[t,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:e=>Dr(e,2,"matches","element, selector"),inputSchema:qn,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"]}},is={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0;let i=!1;if(t instanceof Element&&Kt(r)){const e=r;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Dr(e,2,"has","element, selector")},as={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,r){const n=e.evaluationHistory,s=n?Date.now():0,i=!await is.evaluate(e,t,r);return n&&Nn(this,e,[t,r],i,s),i},validate:e=>Dr(e,2,"doesNotHave","element, selector")},os={equals:Mn,strictEquals:$n,notEquals:Vn,strictNotEquals:Dn,lessThan:zn,lessThanOrEqual:Fn,greaterThan:Bn,greaterThanOrEqual:Hn,and:Un,or:Wn,not:Jn,no:Gn,isEmpty:Kn,isNotEmpty:Zn,exists:Xn,doesNotExist:Yn,contains:Qn,doesNotContain:es,startsWith:ts,endsWith:rs,between:ns,matches:ss,has:is,doesNotHave:as},ls=tn({value:Yr().describe("String literal value")}).strict(),cs=tn({value:Qr().describe("Number literal value")}).strict(),us=tn({value:en().describe("Boolean literal value")}).strict(),ds=tn({left:nn().describe("Left operand"),right:nn().describe("Right operand")}).strict();const ms={stringLiteral:new class extends on{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=ls,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid){const t=this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(e,r,!1),t}let s=t.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,e));const i=this.success(s,"string");return this.trackSimple(e,r,!0,s),i}catch(t){return this.trackSimple(e,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let r=e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=this.resolveExpression(r.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,r)=>{try{const e=this.resolveVariable(r,t);return void 0!==e?e+"":""}catch(e){return""}}),r}resolveExpression(e,t){if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?(qe(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends on{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=cs,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?Number.isFinite(t.value)?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?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 on{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=us,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends on{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=ds,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=xn(t.left,"left operand")+xn(t.right,"right operand");return this.trackSimple(e,r,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends on{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=ds,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,r,!0,s),this.success(s,"string")}catch(t){return this.trackSimple(e,r,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=ds.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(Kt(e))return e;if(Gt(e))return""+e;if(Zt(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends on{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=ds,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=xn(t.left,"left operand")*xn(t.right,"right operand");return this.trackSimple(e,r,!0,s),this.success(s,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}},ps=new Set(["__proto__","constructor","prototype"]),hs={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[r,n]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return nr(r,n);if(Xt(r)){if(ps.has(n))return;return r[n]}return r[n]}},validate:e=>Dr(e,2,"possessive","element, property")??zr(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[r]=t;if(e.me){if("string"!=typeof r)throw Error("Property name must be a string");if(e.me instanceof Element)return nr(e.me,r);if(Xt(e.me)){if(ps.has(r))return;return e.me[r]}return e.me[r]}},validate:e=>Fr(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[r]=t;if(null==e.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=e.it;if(n instanceof Element)return nr(n,r);if(Xt(n)){if(ps.has(r))return;return n[r]}return n[r]},validate:e=>Fr(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[r]=t;if(e.you){if("string"!=typeof r)throw Error("Property name must be a string");if(e.you instanceof Element)return nr(e.you,r);if(Xt(e.you)){if(ps.has(r))return;return e.you[r]}return e.you[r]}},validate:e=>Fr(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[r,n]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return nr(n,r);if(Xt(n)){if(ps.has(r))return;return n[r]}return n[r]}},validate:e=>Dr(e,2,"of","property, object")??zr(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||e.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:e=>Wr(e,1,2,"attribute","attributeName, optional element")??zr(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[r,n,s]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(r)===n},validate:e=>Wr(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??zr(e,0,"attributeWithValue","attribute name")??zr(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:e=>Fr(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:e=>Fr(e,"idReference","idValue")}};function fs(e,t,r,n,s="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:s,message:r,code:t,suggestions:n}}}function ys(e,t){return{success:!0,value:e,type:t}}function gs(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const vs={Array:(e,t)=>{try{return Array.isArray(e)?ys(e,"array"):e instanceof NodeList?ys(Array.from(e),"array"):ys(null==e?[]:[e],"array")}catch(e){return fs("Array","ARRAY_CONVERSION_FAILED",gs("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?ys("","string"):Kt(e)?ys(e,"string"):Xt(e)?ys(JSON.stringify(e),"string"):ys(e+"","string")}catch(e){return fs("String","STRING_CONVERSION_FAILED",gs("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Zt(e))return ys(e,"boolean");if(null==e)return ys(!1,"boolean");if(Kt(e)){const t=e.toLowerCase().trim();return ys("false"!==t&&"0"!==t&&""!==t,"boolean")}return Gt(e)?ys(0!==e&&!isNaN(e),"boolean"):ys(!!e,"boolean")}catch(e){return fs("Boolean","BOOLEAN_CONVERSION_FAILED",gs("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 ys(e,"number");if(null==e)return ys(0,"number");const t=Number(e);return isNaN(t)?fs("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):ys(t,"number")}catch(e){return fs("Number","NUMBER_CONVERSION_FAILED",gs("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=vs.Number(e,t);return r.success?ys(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=vs.Number(e,t);return r.success?ys(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return ys(e,"object");if(null==e)return ys(new Date(""),"object");if(Kt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return ys(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?fs("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"):ys(t,"object")}catch(e){return fs("Date","DATE_CONVERSION_FAILED",gs("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{if(!Kt(e))return ys(e,"object");try{return ys(JSON.parse(e),"object")}catch(e){return fs("JSON","JSON_PARSE_FAILED",gs("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 ys(JSON.stringify(e),"string")}catch(e){return fs("JSONString","JSON_STRINGIFY_FAILED",gs("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 ys(e,"object");if(Kt(e))try{return ys(JSON.parse(e),"object")}catch(e){return fs("Object","JSON_PARSE_FAILED",gs("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return ys({},"object")}catch(e){return fs("Object","OBJECT_CONVERSION_FAILED",gs("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 ys(Es(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{const t=e;if(t.name){const e=xs(t);void 0!==e&&(r[t.name]=e)}}),ys(r,"object")}return ys({},"object")}catch(e){return fs("FormValues","FORM_VALUES_EXTRACTION_FAILED",gs("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 r=e;if(e instanceof HTMLElement){const n=vs.Values(e,t);if(!n.success)return n;r=n.value}if(!Xt(r))return ys("","string");const n=new URLSearchParams;for(const[e,t]of Object.entries(r))if(null!=t)if(Array.isArray(t))for(const r of t)n.append(e,r+"");else n.append(e,t+"");return ys(""+n,"string")}catch(e){return fs("FormEncoded","FORM_ENCODE_FAILED",gs("Failed to URL-encode values",e),["Ensure input is a form element or plain object of scalar/array values"])}}},bs=tn({value:sn(),type:Yr().min(1)}),ws=tn({value:sn(),type:Yr().min(1)});new class extends on{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=bs,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 r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=t;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),a=n?parseInt(n[1],10):2,o=vs.Number(s,e);if(!o.success)return o;const l={success:!0,value:o.value.toFixed(a),type:"string"};return this.trackPerformance(e,t,l,r),l}let a=vs[i];if(a){const n=a(s,e);return this.trackPerformance(e,t,n,r),n}const o={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(o&&(a=vs[o],a)){const n=a(s,e);return this.trackPerformance(e,t,n,r),n}const l={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,l,r),l}catch(n){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends on{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=ws,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=t,a=i.toLowerCase();let o;switch(a){case"null":o=null===s;break;case"undefined":o=void 0===s;break;case"string":o=Kt(s);break;case"number":o=Gt(s)&&!isNaN(s);break;case"boolean":o=Zt(s);break;case"object":o=Xt(s);break;case"array":o=Array.isArray(s);break;case"function":o=Yt(s);break;case"date":o=s instanceof Date;break;case"element":o=s instanceof Element;break;case"node":o=s instanceof Node;break;case"node-list":o=s instanceof NodeList;break;case"empty":o=null==s||""===s||Array.isArray(s)&&0===s.length||Xt(s)&&0===Object.keys(s).length;break;default:o=s?.constructor?.name?.toLowerCase()===a}const l=this.success(o,"boolean");return this.trackPerformance(e,t,l,r),l}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const ks={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Kt(e)?e:Xt(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Zt(e))return e;if(null==e)return!1;if(Kt(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=ks.Number(e);return Math.trunc(t)},Float:e=>{const t=ks.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Kt(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)}return new Date(e)},JSON:e=>{if(!Kt(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(Kt(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{Kt(e)||(e=ks.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>Kt(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:ks.String(e)).join(""):e instanceof Element?e.outerHTML:ks.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return Es(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=xs(e))}),r}return{}},FormEncoded:(e,t)=>{const r=e instanceof HTMLElement?ks.Values(e,t):e;if(!Xt(r))return"";const n=new URLSearchParams;for(const[e,t]of Object.entries(r))if(null!=t)if(Array.isArray(t))for(const r of t)n.append(e,r+"");else n.append(e,t+"");return""+n},"Values:Form":(e,t)=>{const r=ks.Values(e,t);return ks.FormEncoded(r,t)},"Values:JSON":(e,t)=>{const r=ks.Values(e,t);return JSON.stringify(r)}};function Es(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=xs(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}function xs(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 Cs={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:e}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}(n);return ks.Number(r).toFixed(e||2)}let s=ks[n];if(s)return s(r,e);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[n.toLowerCase()];return i&&(s=ks[i],s)?s(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>Dr(e,2,"as","value, type")??zr(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!Kt(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return Kt(r);case"number":return Gt(r)&&!isNaN(r);case"boolean":return Zt(r);case"object":return Xt(r);case"array":return Array.isArray(r);case"function":return Yt(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||Xt(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>Dr(e,2,"is","value, type")??zr(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Dr(e,1,"async","expression")}},Ss={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"},As=tn({collection:nn().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Ts=tn({collection:nn().describe("Collection to access"),index:Qr().describe("Index position to access")}).strict(),Os=tn({collection:nn().describe("Collection to select random item from")}).strict();new class extends on{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=As,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[0]:void 0,a={success:!0,value:i,type:Ss[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends on{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=As,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=s.length>0?s[s.length-1]:void 0,a={success:!0,value:i,type:Ss[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends on{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=Ts,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection),i=this.normalizeIndex(t.index,s.length),a=i>=0&&s.length>i?s[i]:void 0,o={success:!0,value:a,type:Ss[this.inferEvaluationType(a)]};return this.trackPerformance(e,t,o,r),o}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid at input: "+e.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return 0>e?t+e:e}},new class extends on{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=Os,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(t.collection);if(0===s.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],a={success:!0,value:i,type:Ss[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,a,r),a}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,s,r),s}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid random input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}};const Ps={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const r=void 0!==t?t:e.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:Kt(r)?r.length>0?r[0]:null:Xt(r)&&"length"in r&&Gt(r.length)&&r.length>0?r[0]:null},validate:e=>Ur(e,1,"first","collection")},Ls={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const e=r.children;return e.length>0?e[e.length-1]:null}return Kt(r)?r.length>0?r[r.length-1]:null:Xt(r)&&"length"in r&&Gt(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>Ur(e,1,"last","collection")},Ns={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!Gt(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>s?e.length+s:s;return t>=0&&e.length>t?e[t]:null}if(Kt(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=>Wr(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function Is(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;const e=r.querySelector(t);if(e)return e;r=r.nextElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Is(n,t):null}function js(e,t){let r=e.previousElementSibling;for(;r;){const e=Array.from(r.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(r.matches(t))return r;r=r.previousElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?js(n,t):null}function Rs(e){let t=0,r=e;for(;r&&r.parentElement;)t+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,t+=1e3;return t}const _s={first:Ps,last:Ls,at:Ns,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[r,n]=t,s=n||e.me;return s&&s instanceof Element?r?Is(s,r):s.nextElementSibling:null},validate:e=>Ur(e,2,"next","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[r,n]=t,s=n||e.me;return s&&s instanceof Element?r?js(s,r):s.previousElementSibling:null},validate:e=>Ur(e,2,"previous","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const a=i.closest(n);return a?function(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=Rs(e);for(const e of n)if(Rs(e)>s)return e;return null}(i,r,a):null},validate:e=>Wr(e,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const a=i.closest(n);return a?function(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=Rs(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(s>Rs(t))return t}return null}(i,r,a):null},validate:e=>Wr(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}};function qs(e,t,r,n,s,i){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,l=n.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=!t&&e?n.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),m=!1,p=r.length-1;p>=0;p--){var h={};for(var f in n)h[f]="access"===f?{}:n[f];for(var f in n.access)h.access[f]=n.access[f];h.addInitializer=function(e){if(m)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(e||null))};var y=(0,r[p])("accessor"===l?{get:d.get,set:d.set}:d[c],h);if("accessor"===l){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(o=a(y.get))&&(d.get=o),(o=a(y.set))&&(d.set=o),(o=a(y.init))&&s.unshift(o)}else(o=a(y))&&("field"===l?s.unshift(o):d[c]=o)}u&&Object.defineProperty(u,n.name,d),m=!0}function Ms(e,t,r){for(var n=arguments.length>2,s=0;t.length>s;s++)r=n?t[s].call(e,r):t[s].call(e);return n?r:void 0}function $s(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}function Vs(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function Ds(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),r=e.indexOf("=");if(-1===r)return{name:e.trim()};const n=e.slice(0,r).trim();let s=e.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function zs(e,t){for(const r of e)t(r);return e}function Fs(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function Bs(e,t,r){const n=e.hasAttribute(t);void 0!==r?n&&e.getAttribute(t)===r?e.removeAttribute(t):e.setAttribute(t,r):n?e.removeAttribute(t):e.setAttribute(t,"")}function Hs(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&&Ws(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&&Ws(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&Ws(r)?[r]:[]}function Us(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Ws(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Us(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Js(e,t){return e.map(e=>{if(Us(e)){const r=function(e){const t=e.trim(),r=t.match(/^\{(.+)\}$/);return r?r[1].trim():t}(e),n=t.locals.get(r)??t.globals.get(r);return null!=n?n+"":(ue(`Dynamic class variable '${r}' not found in context`),"")}return e}).filter(e=>e.length>0)}"function"==typeof SuppressedError&&SuppressedError;const Ks=Symbol("command:name"),Gs=Symbol("command:category"),Zs=Symbol("command:metadata");function Xs(e){return function(t,r){const n=t;n[Ks]=e.name,n[Gs]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Ys(e){return function(t,r){const n=t,s=n[Gs];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};n[Zs]=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 Qs(e){return()=>new e}function ei(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function ti(e,t){return e?`[${e}] ${t}`:t}function ri(e,t,r){if(ei(e))return e;if(!e){const e=t.me;if(!e)throw Error(ti(r,"No target element — provide explicit target or ensure context.me is set"));return si(e)}if("string"==typeof e){const n=e.trim();if("me"===n){if(!t.me)throw Error(ti(r,'Context reference "me" is not available'));return si(t.me)}if("it"===n){if(!ei(t.it))throw Error(ti(r,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===n){if(!t.you)throw Error(ti(r,'Context reference "you" is not available'));return si(t.you)}const s=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw Error(ti(r,"DOM not available — cannot resolve element selector"));const i=s.querySelector(n);if(!i)throw Error(ti(r,"Element not found with selector: "+n));if(!ei(i))throw Error(ti(r,"Element found but is not an HTMLElement: "+n));return i}throw Error(ti(r,"Invalid target type: "+typeof e))}function ni(e,t){if(Array.isArray(e))return e.filter(ei);if(e instanceof NodeList)return Array.from(e).filter(ei);if(ei(e))return[e];if(!e){const e=t.me;return e&&ei(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&ei(t.me)?[t.me]:[];if("it"===r)return ei(t.it)?[t.it]:[];if("you"===r)return t.you&&ei(t.you)?[t.you]:[];const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let e=r;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.querySelectorAll(e);return Array.from(t).filter(ei)}}return[]}function si(e){if(ei(e))return e;throw Error("Value is not an HTMLElement")}function ii(e,t,r){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(ti(r,'No "me" element in context'));if(!ei(t.me))throw Error(ti(r,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(ti(r,'No "it" value in context'));if(!ei(t.it))throw Error(ti(r,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(ti(r,'No "you" element in context'));if(!ei(t.you))throw Error(ti(r,"context.you is not an HTMLElement"));return t.you;default:throw Error(ti(r,"Unknown possessive: "+e))}}const ai=["on","from","to","in","with","at"];async function oi(e,t,r,n,s={},i){let a=e;if(s.filterPrepositions&&e&&(a=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!ai.includes(t.name.toLowerCase())})),(!a||0===a.length)&&s.fallbackModifierKey&&i){const e=i[s.fallbackModifierKey];e&&(a=[e])}if(!a||0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!ei(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const o=[];for(const e of a){const s=await t.evaluate(e,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(ei(s))o.push(s);else if(s instanceof NodeList){const e=Array.from(s).filter(ei);o.push(...e)}else if(Array.isArray(s)){const e=s.filter(ei);o.push(...e)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let e=s;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const n=t.querySelectorAll(e),i=Array.from(n).filter(ei);o.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!ei(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return o}function li(e){return"string"==typeof e&&e.trim().startsWith("*")}function ci(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const r=t.substring(1).trim();return r?{property:r}:null}(e);if(!t)return null;const r=t.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function ui(e,t,r){e.style.setProperty(t,r)}const di=["dialog","details","summary","select"];function mi(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 pi(e,t,r){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const r=mi(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const r=mi(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:mi(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=mi(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(n=e,"attributeAccess"===n.type?"@"+n.attributeName:mi(n)),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1};var n}class hi{async resolveTargets(e,t,r,n){return oi(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return pi(e,t,r)}parseClassNames(e){return Hs(e)}isAttribute(e){return Vs(e.trim())}isCSSProperty(e){return li(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>ei(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 fi=(()=>{let e,t,r=[Ys({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"]}),Xs({name:"add",category:"dom"})],n=[],s=hi;return t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(e){const t=Ds(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const i=await t.evaluate(e.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,r,e.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const r=Js(e.classes,t);r.length>0&&Fs(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,zs(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":!function(e,t){Fs(e,Object.entries(t),(e,[t,r])=>{e.style.setProperty(t,r)})}(e.targets,e.styles)}var r,n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const r=t.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(e=>"string"==typeof e))return!1}return!0}},$s(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const yi=Qs(fi);function gi(e){return!!e.parentNode&&(e.remove(),!0)}let vi=(()=>{let e,t,r=[Ys({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"]}),Xs({name:"remove",category:"dom"})],n=[],s=hi;return t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if(ei(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&ei(n[0]))return{type:"element",targets:n.filter(e=>ei(e))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:Ds(s).name,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const r=Js(e.classes,t);r.length>0&&Fs(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,zs(e.targets,e=>{e.removeAttribute(r)});break;case"styles":!function(e,t){Fs(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)gi(t)}var r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}},$s(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const bi=Qs(vi);function wi(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function ki(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=wi(e);return r?r.milliseconds:t}return t}function Ei(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=wi(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function xi(e){return e&&"none"!==e?e.split(",").map(e=>{const t=parseFloat(e.trim());return isNaN(t)?0:e.includes("s")&&!e.includes("ms")?1e3*t:t}):[0]}function Ci(e,t){let r=0;for(let n=0;e.length>n;n++)r=Math.max(r,(e[n]||0)+(t[n]||0));return r}function Si(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function Ai(e){return"DIALOG"===e.tagName}function Ti(e){return"DETAILS"===e.tagName}function Oi(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&Bs(e,r)}}function Pi(e,t,r,n){const s=Oi(e,t,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Li(e,t,r,n){const s=Oi(e,t,r),i=()=>{s(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function Ni(e,t,r){if(t.startsWith("@")){const n=t.substring(1);return void(!1===r?e.removeAttribute(n):e.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(t){case"textContent":return void(e.textContent=n);case"innerHTML":return void(e.innerHTML=n);case"innerText":return void(e.innerText=n);case"id":return void(e.id=n);case"className":return void(e.className=n);case"value":return void("value"in e&&(e.value=n));case"checked":return void("checked"in e&&(e.checked=!!r))}if(t.includes(".")){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++)if(s=s[n[e]],null==s)return;return void(s[n[n.length-1]]=r)}if(t.includes("-")||t in e.style)e.style.setProperty(t,n);else try{e[t]=r}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function Ii(e){return null==e||""===e}const ji=/^the\s+(.+?)\s+of\s+(.+)$/i,Ri=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 _i(e){return"string"==typeof e&&ji.test(e)}function qi(e,t){const r=e.match(ji);if(!r)return null;try{return{element:ri(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function Mi(e,t,r){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,r){const n=e.property?.name;if(!n)return null;let s=await t.evaluate(e.target,r);return Array.isArray(s)&&(s=s[0]),ei(s)?{element:s,property:n}:null}(e,t,r);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,r){const n="string"==typeof e.property?e.property:e.property?.name;if(!n)return null;let s=await t.evaluate(e.object,r);return Array.isArray(s)&&(s=s[0]),ei(s)?{element:s,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const e=n.object,s=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!ei(i))return null;const a=s?.name||s?.value;return a?{element:i,property:a}:null}return null}function $i(e,t){const{element:r,property:n}=e;n.startsWith("*")?ui(r,n.substring(1),t+""):Ni(r,n,t)}async function Vi(e,t,r){let n,s;if(e?.for){const s=await t.evaluate(e.for,r);n="number"==typeof s?s:"string"==typeof s?ki(s):void 0}if(e?.until){const n=await t.evaluate(e.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}function Di(e,t){const r=t?.name,n=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return di.includes(t)}(t)}(t);if(ei(e)||Array.isArray(e)&&e.every(e=>ei(e)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return di.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const zi=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"toggle",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("toggle command requires an argument");const n=e.args[0],s=n?.name;if("between"===s&&e.args.length>=4){const{duration:n,untilEvent:s}=await Vi(e.modifiers,t,r),i=await t.evaluate(e.args[1],r),a=await t.evaluate(e.args[3],r),o=[];for(let t=4;e.args.length>t;t++){const r=e.args[t]?.name;"on"!==r&&"from"!==r&&o.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},c=await oi(o,t,r,"toggle",l,e.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:c,duration:n,untilEvent:s}}const i=await Mi(n,t,r);if(i)return{type:"property",target:i};if("selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("*")){let s=n.value,i=1;if("*"===s&&e.args.length>1&&"identifier"===e.args[1].type&&(s="*"+e.args[1].name,i=2),"*"===s&&e.modifiers?.on){const n=e.modifiers.on?.name;if(n&&["display","visibility","opacity"].includes(n)){s="*"+n;const{duration:i,untilEvent:a}=await Vi(e.modifiers,t,r),o=ci(s);if(o){const e=r.me;return{type:"css-property",property:o,targets:e?[e]:[],duration:i,untilEvent:a}}}}const a=ci(s);if(a){const{duration:n,untilEvent:s}=await Vi(e.modifiers,t,r),o={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:a,targets:await oi(e.args.slice(i),t,r,"toggle",o,e.modifiers),duration:n,untilEvent:s}}}const{duration:a,untilEvent:o}=await Vi(e.modifiers,t,r),{value:l}=await pi(n,t,r);if(_i(l)){const e=qi(l,r);if(e)return{type:"property",target:e}}const{type:c,expression:u}=Di(l,n),d={filterPrepositions:!0,fallbackModifierKey:"on"};switch(c){case"attribute":{const{name:n,value:s}=Ds(u);return{type:"attribute",name:n,value:s,targets:await oi(e.args.slice(1),t,r,"toggle",d,e.modifiers),duration:a,untilEvent:o}}case"css-property":{const n=ci(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await oi(e.args.slice(1),t,r,"toggle",d,e.modifiers)}}case"element":{let s;if(ei(l))s=[l];else if(Array.isArray(l)&&l.every(e=>ei(e)))s=l;else if(u){const e=document.querySelectorAll(u);s=Array.from(e).filter(e=>ei(e))}else s=await oi([n],t,r,"toggle",d,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(e,t,r,n){if(t?.as){const e=await r.evaluate(t.as,n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await r.evaluate(e[1],n);if("string"==typeof t){const s=t.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&e.length>=3){const t=await r.evaluate(e[2],n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:Si(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:Hs(u),targets:s,duration:a,untilEvent:o}}default:{const n=Hs(u||l);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await oi(e.args.slice(1),t,r,"toggle",d,e.modifiers),duration:a,untilEvent:o}}}}async execute(e,t){switch(e.type){case"classes":{const r=Js(e.classes,t);if(0===r.length)return[...e.targets];if(Fs(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&Pi(t,"class",r[0],e.duration),e.untilEvent&&Li(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,zs(e.targets,e=>{Bs(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Pi(t,"attribute",e.name,e.duration),e.untilEvent&&Li(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return zs(e.targets,t=>function(e,t){const r=window.getComputedStyle(e);switch(t){case"display":"none"===r.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=r.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:r}=e;return r.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,r.substring(1)):nr(t,r)}(e),r=e.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof t||Ri.has(n)||Ri.has(n.toLowerCase())){const r=!t;return $i(e,r),r}if("number"==typeof t){const r=0===t?1:0;return $i(e,r),r}if("string"==typeof t){const n="__ht_"+r,s=e.element[n];return""===t&&void 0!==s?($i(e,s),s):(e.element[n]=t,$i(e,""),"")}$i(e,!t)}(e.target),[e.target.element];case"dialog":return zs(e.targets,t=>{return n=e.mode,void((r=t).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return zs(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return zs(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const r=t.classList.contains(e.classA),n=t.classList.contains(e.classB);r?(t.classList.remove(e.classA),t.classList.add(e.classB)):n?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Pi(t,"class",e.classA,e.duration),e.untilEvent&&Li(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},$s(t,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());const Fi=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"put",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("put requires arguments");const n=e=>e?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,a=null;for(let t=0;e.args.length>t;t++){const r=e.args[t],o=n(r),l="literal"===o?r.value:r.name;if(("literal"===o||"identifier"===o)&&s.includes(l)){i=t,a=l;break}}let o=null,l=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";o=e.args[0],a=t,l=e.modifiers[t]}else if(3>e.args.length){if(2>e.args.length)throw Error("put requires content and position");o=e.args[0],a=e.args[1]?.value||e.args[1]?.name||"into"}else o=e.args[0],a=e.args[1]?.value||e.args[1]?.name||null,l=e.args[2];else o=e.args.slice(0,i)[0]||null,l=e.args.slice(i+1)[0]||null;if(!o)throw Error("put requires content");if(!a)throw Error("put requires position keyword");const c=await t.evaluate(o,r),u=this.mapPosition(a);let d,m,p=null;if(l){const e=n(l),s=await Mi(l,t,r);if(s)return{value:c,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===e){const e=l.object,n=l.property;if("selector"===e?.type)p=e.value;else if("identifier"===e?.type){const s=e.name;if("my"===s||"me"===s||"I"===s){if(r.me&&n?.name)return{value:c,targets:[r.me],position:"replace",memberPath:n.name}}else if("its"===s||"it"===s){const e=await t.evaluate(l,r);"string"==typeof e&&(p=e)}else p=s}if(p&&n?.name)d=n.name;else if(!p&&!d){const e=await t.evaluate(l,r);"string"==typeof e&&(p=e)}}else if("identifier"===e&&"me"===l.name)p=null;else if("selector"===e||"cssSelector"===e)p=l.value||l.selector;else if("literal"===e){const e=l.value;if("string"==typeof e&&_i(e)){const t=qi(e,r);if(t)return{value:c,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?p=e:m=e+""}else if("identifier"===e){const e=l.name;if(this.looksLikeCss(e))p=e;else{const n=await t.evaluate(l,r),s=this.resolveEvaluatedAsElements(n);if(s)return{value:c,targets:s,position:u,memberPath:d};m=e}}else{const e=await t.evaluate(l,r),n=this.resolveEvaluatedAsElements(e);if(n)return{value:c,targets:n,position:u,memberPath:d};"string"==typeof e&&(this.looksLikeCss(e)?p=e:m=e)}}return m?{value:c,targets:[],position:u,memberPath:d,variableName:m}:{value:c,targets:await this.resolveTargets(p,r),position:u,memberPath:d}}async execute(e,t){const{value:r,targets:n,position:s,memberPath:i,variableName:a}=e;if(a)return t.locals&&t.locals.set(a,r),t[a]=r,void Object.assign(t,{it:r});if(i)for(const e of n)this.setProperty(e,i,r);else for(const e of n){const t=this.parseValue(r);this.insertContent(e,t,s)}return n}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!ei(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>ei(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return ei(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(ei(t)){const n=t;switch(r){case"beforebegin":e.parentElement?.insertBefore(n,e);break;case"afterbegin":e.insertBefore(n,e.firstChild);break;case"beforeend":e.appendChild(n);break;case"afterend":e.parentElement?.insertBefore(n,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t);else ei(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(ei(e))return[e];if(Array.isArray(e)){const t=e.filter(ei);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(ei);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,r){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++){if(!s[n[e]])throw Error(`Property path "${t}" does not exist`);s=s[n[e]]}s[n[n.length-1]]=r}},$s(t,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());class Bi{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await oi(e.args,t,r,n)}}(e,t,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>ei(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const r=e.dataset.originalDisplay;void 0!==r?(e.style.display=r||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let Hi=(()=>{let e,t,r=[Ys({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Xs({name:"hide",category:"dom"})],n=[],s=Bi;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=>ei(e))}},$s(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const Ui=Qs(Hi);let Wi=(()=>{let e,t,r=[Ys({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Xs({name:"show",category:"dom"})],n=[],s=Bi;return t=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const r=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,r)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>ei(e))&&"string"==typeof t.defaultDisplay}},$s(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const Ji=Qs(Wi);function Ki(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 Gi(e,t,r){return"global"===r&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==r&&t.locals&&t.locals.has(e)?(qe(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"===r&&t.locals&&t.locals.has(e)?(qe(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 Zi(e,t,r,n){if("global"===n)return Me(r,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))Me(r,e.slice(1),t);else{if(r.locals&&r.locals.has(e))return r.locals.set(e,t),void _e(e,t,r);if(r.globals&&r.globals.has(e))return Me(r,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(r.variables&&r.variables.has(e))r.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void Me(r,e,t);r.locals.set(e,t),_e(e,t,r)}}}function Xi(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Gi(e,t)}let Yi=(()=>{let e,t,r=[Ys({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"]}),Xs({name:"make",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){const n=e.args.length>0?await t.evaluate(e.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const s=void 0!==e.modifiers.an?"an":"a",i=await async function(e,t,r){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const n=[];for(const s of e.args)n.push(await t.evaluate(s,r));return n}const n=await t.evaluate(e,r);return Array.isArray(n)?n:[n]}(e.modifiers.from,t,r),a=await async function(e,t,r){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const n=await t.evaluate(e,r);return"string"==typeof n?n:n+""}(e.modifiers.called,t,r);return{article:s,expression:n,constructorArgs:i,variableName:a}}async execute(e,t){const{expression:r,constructorArgs:n=[],variableName:s}=e,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(e){const t=e.slice(1,-2);let r="div",n=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(r=s[1],n=t.slice(s[0].length));const i=document.createElement(r),a=n.split(/(?=[.#])/);for(const e of a)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(r):function(e,t,r){if(ei(e))return e;const n=e+"";let s;if("undefined"!=typeof window&&(s=window[n]),s||"undefined"==typeof global||(s=global[n]),!s&&r.variables?.has(n)&&(s=r.variables.get(n)),!s||"function"!=typeof s)throw Error(`Constructor '${n}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(r,n,t);return Object.assign(t,{it:i}),s&&Zi(s,i,t),i}},$s(t,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})();const Qi=Qs(Yi),ea=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"empty",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){return{targets:await oi(e.args,t,r,"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=>ei(e))}},$s(t,"EmptyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function ta(e){return e.hasAttribute("popover")}const ra=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"open",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){const n=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const r=t.name?.toLowerCase();return"as"!==r&&"modal"!==r&&"non-modal"!==r&&"nonmodal"!==r}),s=Si(await oi(n,t,r,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)),i=await async function(e,t,r,n){if(t?.as){const e=await r.evaluate(t.as,n);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 r.evaluate(e[t+1],n);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,r);return{targets:s,dialogMode:i}}async execute(e,t){for(const t of e.targets)if(Ai(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(Ti(t))t.open=!0;else if(ta(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=>ei(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}},$s(t,"OpenCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function na(e){return e.hasAttribute("popover")}const sa=Qs((()=>{let e,t,r=[Ys({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"]}),Xs({name:"close",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){return{targets:Si(await oi(e.args,t,r,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(Ai(t))t.open&&t.close();else if(Ti(t))t.open=!1;else if(na(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=>ei(e))}},$s(t,"CloseCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function ia(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const aa=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"select",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){return{targets:await oi(e.args,t,r,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(ia(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),r=e?.defaultView;if(!e||!r)continue;const n=r.getSelection?.();if(n)try{const r=e.createRange();r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ei(e))}},$s(t,"SelectCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function oa(e){return"FORM"===e.tagName}const la=Qs((()=>{let e,t,r=[Ys({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"]}),Xs({name:"reset",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){return{targets:await oi(e.args,t,r,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)oa(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=>ei(e))}},$s(t,"ResetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function ca(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const r=Gi(e,t);return void 0!==r?!!r:!!e}return!!e}const ua=Qs((()=>{let e,t,r=[Ys({description:"Conditional execution based on boolean expressions",syntax:["if <condition> then <commands>","if <condition> then <commands> else <commands>","unless <condition> <commands>"],examples:["if x > 5 then add .active","if user.isAdmin then show #adminPanel else hide #adminPanel","unless user.isLoggedIn showLoginForm"],sideEffects:["conditional-execution"],aliases:["unless"]}),Xs({name:"if",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){const n="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(n+" command requires a condition to evaluate");let s,i;if("unless"===n){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");s=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(s=e.args[1],i=3>e.args.length?void 0:e.args[2]):e.modifiers?.then&&(s=e.modifiers.then,i=e.modifiers.else),!s)throw Error('if command requires "then" branch with commands');return{mode:n,condition:await t.evaluate(e.args[0],r),thenCommands:s,elseCommands:i}}async execute(e,t){const{mode:r,condition:n,thenCommands:s,elseCommands:i}=e,a=ca(n,t);let o,l;return("unless"===r?!a:a)?(o="then",l=await this.executeCommandsOrBlock(s,t),"unless"===r&&Object.assign(t,{it:l})):i&&"if"===r?(o="else",l=await this.executeCommandsOrBlock(i,t)):o="none",{mode:r,conditionResult:a,executedBranch:o,result:l}}async executeCommandsOrBlock(e,t){return"block"===e?.type?this.executeBlock(e,t):Array.isArray(e)?this.executeCommands(e,t):e}async executeBlock(e,t){const r=t.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let n;if(e.commands?.length)for(const s of e.commands)n=await r(s,t);return n}async executeCommands(e,t){let r;for(const n of e)r=n?.execute?await n.execute(t):"function"==typeof n?await n():n;return r}},$s(t,"ConditionalCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),da=ua,ma=ua;let pa=(()=>{let e,t,r=[Ys({description:"Iteration in hyperscript - for-in, counted, conditional, event-driven, and infinite loops",syntax:["repeat for <var> in <collection> { <commands> }","repeat <count> times { <commands> }","repeat while <condition> { <commands> }","repeat until <condition> { <commands> }","repeat forever { <commands> }"],examples:["repeat for item in items { log item }",'repeat 5 times { log "hello" }'],sideEffects:["iteration","conditional-execution"]}),Xs({name:"repeat",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){let n;if(e.modifiers?.index){const s=await t.evaluate(e.modifiers.index,r);"string"==typeof s&&(n=s)}let s,i=e.modifiers?.block||e.modifiers?.commands;if(!i){const t=[];for(let r=e.args.length-1;r>=0;r--){const n=e.args[r];if("block"===n?.type&&n.commands&&(t.unshift(n),2===t.length))break}2===t.length?(i=t[0],s=t[1]):1===t.length&&(i=t[0])}const a=e.args[0],o="identifier"===a?.type?a.name:null,l=!!e.modifiers?.bottomTested&&await t.evaluate(e.modifiers.bottomTested,r);if("for"===o||e.modifiers?.for){const a=e.args[1],o=a?.value||a?.name,l=e.args[2]?await t.evaluate(e.args[2],r):void 0;if(!o||void 0===l)throw Error("for loops require variable and collection");return{type:"for",variable:o,collection:Array.isArray(l)?l:[l],indexVariable:n,commands:i,elseCommands:s}}if("times"===o||e.modifiers?.times){const a=e.args[1],o=a?await t.evaluate(a,r):void 0,l="number"==typeof o?o:parseInt(o+"",10);if(isNaN(l))throw Error("times loops require a count number");return{type:"times",count:l,indexVariable:n,commands:i,elseCommands:s}}if("while"===o||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw Error("while loops require a condition");return{type:"while",condition:t,indexVariable:n,commands:i,elseCommands:s,bottomTested:l}}if("until"===o&&e.modifiers?.from||"until-event"===o){const a=e.args[1],o=a?.value||a?.name;if(!o)throw Error("until-event loops require an event name");let l=r.me;if(e.args[2]){const n=await t.evaluate(e.args[2],r);n instanceof EventTarget?l=n:"document"===n&&(l=document)}return{type:"until-event",eventName:o,eventTarget:l,indexVariable:n,commands:i,elseCommands:s}}if("until"===o||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw Error("until loops require a condition");return{type:"until",condition:t,indexVariable:n,commands:i,elseCommands:s,bottomTested:l}}if("forever"===o||e.modifiers?.forever)return{type:"forever",indexVariable:n,commands:i,elseCommands:s};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:r,variable:n,collection:s,condition:i,count:a,indexVariable:o,commands:l,elseCommands:c,bottomTested:u,eventName:d,eventTarget:m}=e;let p,h;switch(r){case"for":({config:p,iterCtx:h}=function(e,t,r){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:r}}}(s,n,o));break;case"times":({config:p,iterCtx:h}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(a,o));break;case"while":({config:p,iterCtx:h}=function(e,t,r,n){return{config:{type:"while",shouldContinue:()=>t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,ca,t,o));break;case"until":({config:p,iterCtx:h}=function(e,t,r,n){return{config:{type:"until",shouldContinue:()=>!t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,ca,t,o));break;case"until-event":({config:p,iterCtx:h}=function(e,t,r){const n={index:0,eventFired:!1,indexVariable:r};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{n.eventFired=!0}}},iterCtx:n}}(d,m,o));break;case"forever":({config:p,iterCtx:h}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(o));break;default:throw Error("Unknown repeat type: "+r)}if(u){const e=p.shouldContinue;p.shouldContinue=async t=>0===t.index||await e(t)}try{const e=await async function(e,t,r,n,s){const i=e.maxIterations??1e4;let a,o=0,l=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>o&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,r),n.indexVariable&&r.locals&&r.locals.set(n.indexVariable,o);try{a=await s(t,r)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){l=!0;break}if(t.message.includes("CONTINUE")){o++,n.index=o,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}o++,n.index=o,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:o,lastResult:a,interrupted:l}}(p,l,t,h,this.executeCommands.bind(this));if(0===e.iterations&&!e.interrupted&&c){const e=await this.executeCommands(c,t);return Object.assign(t,{it:e}),{type:r,iterations:0,completed:!0,lastResult:e}}return Object.assign(t,{it:e.lastResult}),{type:r,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:r,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const r=e,n=t.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let s;if(r.commands)for(const e of r.commands)s=await n(e,t);return s}if(Array.isArray(e)){let r;for(const n of e)r="function"==typeof n?await n(t):n&&"function"==typeof n.execute?await n.execute(t):n;return r}return"function"==typeof e?await e(t):e}},$s(t,"RepeatCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})();const ha=Qs(pa);class fa{async parseInput(e,t,r){return{signalType:this.signalType}}async execute(e,t){const r=Error(this.errorMessage);throw r[this.errorFlag]=!0,"exit"===this.signalType&&(r.returnValue=void 0,r.timestamp=Date.now()),r}}let ya=(()=>{let e,t,r=[Ys({description:"Exit from the current loop (repeat, for, while, until)",syntax:["break"],examples:["break","if found then break","repeat for item in items { if item == target then break }"],sideEffects:["control-flow"]}),Xs({name:"break",category:"control-flow"})],n=[],s=fa;return t=class extends s{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},$s(t,"BreakCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const ga=Qs(ya);let va=(()=>{let e,t,r=[Ys({description:"Skip to the next iteration of the current loop",syntax:["continue"],examples:["continue","if item.isInvalid then continue","repeat for item in items { if item.skip then continue; process item }"],sideEffects:["control-flow"]}),Xs({name:"continue",category:"control-flow"})],n=[],s=fa;return t=class extends s{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},$s(t,"ContinueCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const ba=Qs(va),wa=Qs((()=>{let e,t,r=[Ys({description:"Stop command execution or prevent event defaults",syntax:["halt","halt the event"],examples:["halt","halt the event","if error then halt",'on click halt the event then log "clicked"'],sideEffects:["control-flow","event-prevention"]}),Xs({name:"halt",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(e.args&&e.args.length>0){const n=e.args[0],s=e.args.length>1?e.args[1]:null;return"identifier"===n.type&&"the"===n.name&&s&&"identifier"===s.type&&"event"===s.name?{target:r.event}:{target:await t.evaluate(e.args[0],r)}}return{}}async execute(e,t){let r=e.target;if(("the"===r&&t.event||"object"==typeof r&&null!==r&&"the"===r.target&&t.event)&&(r=t.event),this.isEvent(r)){const e=r;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in t&&(t.halted=!0);const n=Error("HALT_EXECUTION");throw n.isHalt=!0,n}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},$s(t,"HaltCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),ka=Qs((()=>{let e,t,r=[Ys({description:"Return a value from a command sequence or function, terminating execution",syntax:["return","return <value>"],examples:["return","return 42","return user.name","if found then return result"],sideEffects:["control-flow","context-mutation"]}),Xs({name:"return",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{value:await t.evaluate(e.args[0],r)}:{value:void 0}}async execute(e,t){const{value:r}=e;"returnValue"in t&&(t.returnValue=r),Object.assign(t,{it:r});const n=Error("RETURN_VALUE");throw n.isReturn=!0,n.returnValue=r,n}},$s(t,"ReturnCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());let Ea=(()=>{let e,t,r=[Ys({description:"Immediately terminate execution of the current event handler or behavior",syntax:["exit"],examples:["exit","if no draggedItem exit","on click if disabled exit"],sideEffects:["control-flow"]}),Xs({name:"exit",category:"control-flow"})],n=[],s=fa;return t=class extends s{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},$s(t,"ExitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ms(t,n)})(),t})();const xa=Qs(Ea),Ca=Qs((()=>{let e,t,r=[Ys({description:"Throw an error with a specified message",syntax:["throw <message>"],examples:['throw "Invalid input"','if not valid then throw "Validation failed"'],sideEffects:["error-throwing","execution-termination"]}),Xs({name:"throw",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],r)}}async execute(e,t){const{message:r}=e;let n;throw n=r instanceof Error?r:Error("string"==typeof r?r:r+""),n}},$s(t,"ThrowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Sa=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"set",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("set command requires a target");const n=e.args[0],s=n?.name||n?.value,i=n?.type;if(i){const s=je(i);if(s)return{type:"node-write",node:n,value:await this.extractValue(e,t,r),writer:s}}const a=await Mi(n,t,r);if(a){const n=await this.extractValue(e,t,r);if(a.property.startsWith("*")){const e=a.property.substring(1);return{type:"style",element:a.element,property:e,value:n+""}}return{type:"property",element:a.element,property:a.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,e,t,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await t.evaluate(n,r):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(ei(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(o))return{type:"object-literal",properties:o,targets:await this.resolveTargets(e.modifiers.on,t,r)};if(_i(o)){const n=qi(o,r);if(n){const s=await this.extractValue(e,t,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,e,t,r)}if("string"==typeof o&&li(o)){const n=o.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,r),property:n,value:s+""}}if("string"==typeof o&&Vs(o)){const n=o.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=ii(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:s,property:n[2],value:i}}}if(ei(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(o)&&o.length>0&&ei(o[0])){const n=await this.extractValue(e,t,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o)throw Error("set command target must be a string or object literal"+("memberExpression"===n?.type||"propertyAccess"===n?.type?` (a property chain evaluated to ${null===o?"null":typeof o} — check that all intermediate objects exist)`:""));return{type:"variable",name:o,value:await this.extractValue(e,t,r)}}async execute(e,t){switch(e.type){case"variable":return Zi(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 Ni(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return ui(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[r,n]of Object.entries(e.properties))Ni(t,r,n);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,r,n){const s=e.object,i=e.property;if(s?.name&&i?.name){const e=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const s=ii(e,n),a=await this.extractValue(t,r,n);return{type:"property",element:s,property:i.name,value:a}}}const a=e.object,o=e.computed;if(a){const s=await r.evaluate(a,n);if(null!=s&&"object"==typeof s){const a=o?await r.evaluate(e.property,n)+"":i?.name||"";if(a)return{type:"member-assignment",container:s,property:a,value:await this.extractValue(t,r,n)}}}return null}async extractValue(e,t,r){if(e.modifiers.to)return t.evaluate(e.modifiers.to,r);const n=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(n>=0&&e.args.length>n+1)return t.evaluate(e.args[n+1],r);if(e.args.length>=2)return t.evaluate(e.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,r){return ri(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return ni(e?await t.evaluate(e,r):void 0,r)}async parseTheXofY(e,t,r,n){const s=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,a]=s,o=ri(a,n),l=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.trim(),value:l}}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&&ei(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&ei(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&ei(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}}},$s(t,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Aa=Qs((()=>{let e,t,r=[Ys({description:"Evaluate an expression and store the result in it",syntax:"get <expression>",examples:["get #my-dialog","get <button/>","get me.parentElement"],sideEffects:["context-mutation"]}),Xs({name:"get",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const n=e.args[0],s=await t.evaluate(n,r);return s instanceof NodeList&&1===s.length||Array.isArray(s)&&1===s.length?{value:s[0]}:{value:s}}execute(e,t){return t.it=e.value,Object.assign(t,{result:e.value}),{value:e.value}}validate(e){return"object"==typeof e&&null!==e&&"value"in e}},$s(t,"GetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());let Ta=(()=>{let e,t,r=[Ys({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"]}),Xs({name:"increment",category:"data"})],n=[];return t=class{async parseInput(e,t,r){const n="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,r,n){if(!e.args||0===e.args.length)throw Error(n+" command requires a target");const s=e.args[0];let i,a,o;const l=(c=s)&&"object"==typeof c&&c.type||"unknown";var c;if("identifier"===l)i=s.name,s.scope&&(a=s.scope);else if("literal"===l)i=s.value;else{const e=je(l);if(e){const n=await t.evaluate(s,r),a="number"==typeof n?n:null==n?0:Number(n)||0;i=a,o={node:s,writer:e,currentValue:a}}else{const e=await t.evaluate(s,r);i=Array.isArray(e)&&e.length>0?e[0]:e}}let u=1,d=a;for(let n=1;e.args.length>n;n++){const s=e.args[n];if(s&&"literal"===s.type){const e=s.value;"global"===e?d="global":"number"==typeof e&&(u=e)}else if(s&&"literal"!==s.type){const e=await t.evaluate(s,r);"number"==typeof e&&(u=e)}}return{target:i,amount:u,...d&&{scope:d},...o&&{customWrite:o}}}(e,t,r,n);return{...s,operation:n}}async execute(e,t){const{target:r,property:n,scope:s,amount:i=1,operation:a="increment",customWrite:o}=e;if(o){const e=isFinite(i)?i:1,r="increment"===a?o.currentValue+e:o.currentValue-e;return await o.writer(o.node,r,t),Object.assign(t,{it:r}),r}const l=function(e,t,r,n){if("number"==typeof e)return e;if(ei(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?Ki(r.getAttribute(t)):Ki(r[t]):Ki(r.value||r.textContent)}return"string"==typeof e?"global"===r?Ki(Gi(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],s=Xi(r[0],t);return s?Ki(s[n]):0}(e,n):Ki("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:Gi(e,n)):Ki(e)}(r,n,s,t);let c;if(isNaN(l))c=NaN;else{const e=isFinite(i)?i:1;c="increment"===a?l+e:l-e}return function(e,t,r,n,s){if(ei(e)){const r=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?r.setAttribute(t,n+""):r[t]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof e){if("global"===r)return void Zi(e,n,s,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),s=n[1],i=Xi(n[0],r);i&&(i[s]=t)}(e,n,s);if("me"===e&&s.me)return void(s.me.value=n);if("it"===e)return void Object.assign(s,{it:n});if("you"===e&&s.you)return void(s.you.value=n);Zi(e,n,s)}}(r,n,s,c,t),Object.assign(t,{it:c}),c}},$s(t,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})();const Oa=Qs(Ta),Pa=Qs(Ta),La=Qs((()=>{let e,t,r=[Ys({description:"Set a value only if it doesn't already exist",syntax:["default <expression> to <expression>"],examples:['default myVar to "fallback"','default @data-theme to "light"','default my innerHTML to "No content"'],sideEffects:["data-mutation","dom-mutation"]}),Xs({name:"default",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("default command requires a target");const n=await t.evaluate(e.args[0],r);let s;if(e.modifiers?.to)s=await t.evaluate(e.modifiers.to,r);else{if(2>e.args.length)throw Error('default command requires a value (use "to <value>")');s=await t.evaluate(e.args[1],r)}return{target:n,value:s}}async execute(e,t){const{target:r,value:n}=e;if("string"==typeof r){if(r.startsWith("@"))return this.defaultAttribute(t,r.substring(1),n);const e=r.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,r,s]=e;return this.defaultElementProperty(t,r,s,n)}return this.defaultVariable(t,r,n)}if(ei(r))return this.defaultElementValue(t,r,n);throw Error("Invalid target type: "+typeof r)}defaultVariable(e,t,r){const n=Gi(t,e);return null!=n?{target:t,value:r,wasSet:!1,existingValue:n,targetType:"variable"}:(Zi(t,r,e),Object.assign(e,{it:r}),{target:t,value:r,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,r){if(!e.me)throw Error("No element context available for attribute default");const n=e.me.getAttribute(t);return null!==n?{target:"@"+t,value:r,wasSet:!1,existingValue:n,targetType:"attribute"}:(e.me.setAttribute(t,r+""),Object.assign(e,{it:r}),{target:"@"+t,value:r,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,r,n){const s=ii(t,e,"default"),i=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const r=t.split(".");let n=e;for(const e of r){if(null==n)break;n=n[e]}return n}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(s,r),a=`${t} ${r}`;return Ii(i)?(Ni(s,r,n),Object.assign(e,{it:n}),{target:a,value:n,wasSet:!0,targetType:"property"}):{target:a,value:n,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(e,t,r){const n=function(e){return"value"in e?e.value:e.textContent}(t);return Ii(n)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,r),Object.assign(e,{it:r}),{target:"element",value:r,wasSet:!0,targetType:"element"}):{target:"element",value:r,wasSet:!1,existingValue:n,targetType:"element"}}},$s(t,"DefaultCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function Na(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const Ia=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"clear",category:"data"})],n=[];return t=class{async parseInput(e,t,r){const n=e.args?.[0],s=n?.type,i=n?.name;if(n&&("variable"===s||"identifier"===s&&"string"==typeof i))try{const e=await t.evaluate(n,r);if(!ei(e)&&!Array.isArray(e))return{type:"variable",name:i}}catch{return{type:"variable",name:i}}return{type:"form-fields",targets:await oi(e.args,t,r,"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)Na(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=>ei(e))}return!1}},$s(t,"ClearCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());function ja(e,t,r,n){return e?new Promise(r=>{const s=()=>{i({event:null,timedOut:!1,cancelled:!0})},i=_a(()=>{e.removeEventListener(t,a),n&&n.removeEventListener("abort",s)},r),a=e=>{i({event:e,timedOut:!1,cancelled:!1})};n?.aborted?r({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,a),n&&n.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function Ra(e){return new Promise(t=>setTimeout(t,e))}function _a(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}const qa=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"wait",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,r);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r);const n=e.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,e.args[1],t,r):this.parseTimeWait(e.args[0],t,r)}async execute(e,t){const r=Date.now();if("time"===e.type)return await Ra(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,s=(await ja(n,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const r of e.destructure)r in s&&t.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in n&&t.locals.set(e,n[e]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(e,t,r){return{type:"time",milliseconds:Ei(await t.evaluate(e,r))}}async parseEventWait(e,t,r,n){const s=await r.evaluate(e,n);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),a=i?i[1]:s,o=i?i[2].split(",").map(e=>e.trim()):void 0;let l;if(t){const e=await r.evaluate(t,n);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");l=e}else l=n.me??void 0;return{type:"event",eventName:a,target:l,destructure:o}}async parseEventArrayWait(e,t,r,n){const s=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",r=[];for(const n of e.properties){const e=n.key?.name||n.key?.value;"name"===e&&n.value?t=n.value.value||"":"args"===e&&n.value?.elements&&(r=n.value.elements.map(e=>e.value||e.name||""))}t&&s.push({name:t,params:r})}}let i;if(t){const e=await r.evaluate(t,n);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=n.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,r){const n=[];e.modifiers.for?n.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r)):e.args[0]&&n.push(await this.parseTimeWait(e.args[0],t,r));const s=await t.evaluate(e.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const e of i)try{n.push({type:"time",milliseconds:Ei(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);n.push(t?{type:"event",eventName:t[1],target:r.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(e,t){const r=new AbortController,n=r.signal,s=e.map(e=>"time"===e.type?Ra(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):ja(e.target??t.me??document,e.eventName,0,n).then(t=>({result:t.event,winningCondition:e})));try{return await Promise.race(s)}finally{r.abort()}}},$s(t,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Ma=new Map;let $a=[/^4\d{2}$/,/^5\d{2}$/],Va=(()=>{let e,t,r=[Ys({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"]}),Xs({name:"fetch",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("fetch requires a URL");const n=await this.parseURL(e.args[0],t,r),s=this.parseResponseType(e.modifiers.as);return{url:n,responseType:s,options:await this.parseRequestOptions(e.modifiers.with,t,r),throwOnError:!e.modifiers.doNotThrow&&"response"!==s}}async execute(e,t){const r=Date.now(),{url:n,responseType:s,options:i}=e,a=new AbortController;let o;t.me&&(o=()=>a.abort(),t.me.addEventListener("fetch:abort",o,{once:!0}));const l={...i,signal:a.signal},c=Ma.get(s);if(c?.accept){const e=new Headers(l.headers);e.has("Accept")||e.set("Accept",c.accept),l.headers=e}if(t.me){const e={...l,sender:t.me,headers:l.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),l.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>a.abort(),i.timeout));try{let i=await fetch(n,l);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 $a.some(e=>e.test(t))}(i.status)){const e=Error(`Fetch failed for ${n}: HTTP ${i.status} ${i.statusText}`.trim());throw e.response=i,e.isFetchStatusError=!0,e}const a=await this.handleResponse(i,s,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:a});const o={status:i.status,statusText:i.statusText,headers:i.headers,data:a,url:i.url,duration:Date.now()-r};return Object.assign(t,{it:a}),o}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+n);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${n}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&o&&t.me.removeEventListener("fetch:abort",o)}}async parseURL(e,t,r){const n=await t.evaluate(e,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(Ma.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,r){if(!e)return{};const n=await t.evaluate(e,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const s={};return"method"in n&&(s.method=(n.method+"").toUpperCase()),"headers"in n&&(s.headers=this.parseHeaders(n.headers)),"body"in n&&(s.body=this.parseBody(n.body)),"credentials"in n&&(s.credentials=n.credentials),"mode"in n&&(s.mode=n.mode),"cache"in n&&(s.cache=n.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[r,n]of Object.entries(e))t.set(r,n+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,r){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 n=Ma.get(t);return n?n.handler(e,r):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),r=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),1===r.childNodes.length&&ei(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},$s(t,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})();const Da=Qs(Va);function za(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 Fa=(()=>{let e,t,r=[Ys({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"]}),Xs({name:"trigger",category:"event"})],n=[];return t=class{async parseInput(e,t,r){const n="send"===e.commandName?.toLowerCase()?"send":"trigger",s=n;if(!e.args?.length)throw Error(s+" command requires an event name");const i=e=>e?.type||"unknown",a=e.args[0];let o,l,c;if("functionCall"===i(a)||"callExpression"===i(a)){o=a.name||a.callee?.name;const e=a.args||a.arguments;e?.length&&(l=await this.parseEventDetail(e,t,r))}else if("identifier"===i(a)||"keyword"===i(a))o=a.name;else{const e=await t.evaluate(a,r);o="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)c=await this.resolveTargets([u],t,r,s);else{const n=e.args.findIndex((e,t)=>{if(0===t)return!1;const r=e.name||e.value;return"on"===r||"to"===r});if(-1!==n&&e.args.length-1>n){const i=e.args.slice(n+1),a=i.findIndex(e=>"with"===(e.name||e.value)),o=-1===a?i:i.slice(0,a);c=await this.resolveTargets(o,t,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");c=[r.me]}}return{eventName:o,detail:l,targets:c,options:await this.parseEventOptions(e.args,t,r),mode:n}}async execute(e,t){const r=function(e,t,r={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(r);t.it=r}async resolveTargets(e,t,r,n){const s=[];for(const n of e){const e=await t.evaluate(n,r);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&r.me)s.push(r.me);else if("you"===e&&r.you)s.push(r.you);else if("it"===e&&r.it)s.push(r.it);else if(ei(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(ei));else if(Array.isArray(e))s.push(...e.filter(ei));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(ei));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);s.push(e)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(e,t,r){if(!e?.length)return;if(1===e.length){const n=e[0];if("objectLiteral"!==n?.type)return await t.evaluate(n,r)}const n={};for(const s of e){const e=await t.evaluate(s,r);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,r]=e.split(":",2);n[t.trim()]=za(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:!0,cancelable:!0,composed:!1},s=e.findIndex(e=>"with"===(e.name||e.value));if(-1===s)return n;for(const i of e.slice(s+1)){const e=await t.evaluate(i,r);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?n.bubbles=!0:"nobubbles"===t?n.bubbles=!1:"cancelable"===t?n.cancelable=!0:"nocancelable"===t?n.cancelable=!1:"composed"===t&&(n.composed=!0)}}return n}},$s(t,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})();const Ba=Qs(Fa),Ha=Qs(Fa),Ua=Qs((()=>{let e,t,r=[Ys({description:"Animate CSS properties using CSS transitions",syntax:"transition <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"]}),Xs({name:"transition",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("transition requires property and value");let n,s;const i=await t.evaluate(e.args[0],r);if(ei(i)||"string"==typeof i&&/^[#.]|^(?:me|it|you)$/.test(i)?(s=i,n=await t.evaluate(e.args[1],r)+""):n=i+"",!n)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let a=await t.evaluate(e.modifiers.to,r);void 0===a&&"identifier"===e.modifiers.to.type&&(a=e.modifiers.to.name);const o={property:n,value:a};return void 0!==s&&(o.target=s),e.modifiers?.over&&(o.duration=await t.evaluate(e.modifiers.over,r)),e.modifiers?.with&&(o.timingFunction=await t.evaluate(e.modifiers.with,r)+""),o}async execute(e,t){let{property:r}=e;const{target:n,value:s,duration:i,timingFunction:a}=e;r.startsWith("*")&&(r=r.substring(1)),r=r.replace(/([A-Z])/g,"-$1").toLowerCase();const o=ri(n,t,"transition"),l=ki(i,300),c=getComputedStyle(o).getPropertyValue(r),u=o.style.transition,d=`${r} ${l}ms ${a||"ease"}`;o.style.transition=u?`${u}, ${d}`:d;let m=s+"",p=!1;if("initial"===m||"inherit"===m||"unset"===m||"revert"===m){const e=o.style.getPropertyValue(r);o.style.removeProperty(r),m=getComputedStyle(o).getPropertyValue(r),e&&o.style.setProperty(r,e),p=!0}o.style.setProperty(r,m);const h=await function(e,t,r){return new Promise(n=>{const s=r=>{r.target===e&&r.propertyName===t&&a({completed:!0,cancelled:!1})},i=r=>{r.target===e&&r.propertyName===t&&a({completed:!1,cancelled:!0})},a=_a(()=>{e.removeEventListener("transitionend",s),e.removeEventListener("transitioncancel",i),clearTimeout(o)},n);e.addEventListener("transitionend",s),e.addEventListener("transitioncancel",i);const o=setTimeout(()=>{a({completed:!0,cancelled:!1})},r+50)})}(o,r,l);return o.style.transition=u,p&&o.style.removeProperty(r),Object.assign(t,{it:o}),{element:o,property:r,fromValue:c,toValue:m,duration:l,completed:h.completed}}},$s(t,"TransitionCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Wa=Qs((()=>{let e,t,r=[Ys({description:"Measure DOM element dimensions, positions, and properties",syntax:["measure","measure <property>","measure <target> <property>"],examples:["measure","measure width","measure #element height","measure x and set dragX"],sideEffects:["data-mutation"]}),Xs({name:"measure",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,s,i;if(e.args?.length){const i=e.args[0];if("identifier"===i.type&&i.name){const a=i.name.toLowerCase();if("me"===a||"it"===a||"you"===a){const a=await t.evaluate(i,r);if(ei(a)&&(n=a,e.args.length>1)){const n=e.args[1];s="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else s=i.name}else{const a=await t.evaluate(i,r);if(ei(a)||"string"==typeof a&&/^[#.]/.test(a)){if(n=a,e.args.length>1){const n=e.args[1];s="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else"string"==typeof a&&(s=a)}}e.modifiers?.set&&(i=await t.evaluate(e.modifiers.set,r)+"");const a={};return void 0!==n&&(a.target=n),void 0!==s&&(a.property=s),void 0!==i&&(a.variable=i),a}async execute(e,t){const r=ri(e.target,t,"measure"),n=e.property||"width",s=this.getMeasurement(r,n);return e.variable&&t.locals&&t.locals.set(e.variable,s.value),Object.assign(t,{it:s.value}),{result:s.value,wasAsync:!1,element:r,property:n,value:s.value,unit:s.unit,stored:!!e.variable}}getMeasurement(e,t){const r=getComputedStyle(e);if(t.startsWith("*")){const e=r.getPropertyValue(t.substring(1)),n=parseFloat(e);if(!isNaN(n)){const t=e.match(/([a-zA-Z%]+)$/);return{value:n,unit:t?t[1]:""}}return{value:e,unit:""}}const n=t.toLowerCase(),s=e.getBoundingClientRect(),i={width:()=>s.width,height:()=>s.height,top:()=>s.top,left:()=>s.left,right:()=>s.right,bottom:()=>s.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(i[n])return{value:i[n](),unit:"px"};const a=r.getPropertyValue(t),o=parseFloat(a);if(!isNaN(o)){const e=a.match(/([a-zA-Z%]+)$/);return{value:o,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},$s(t,"MeasureCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Ja=Qs((()=>{let e,t,r=[Ys({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),Xs({name:"settle",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,s;if(e.args&&e.args.length>0){const s=await t.evaluate(e.args[0],r);(ei(s)||"string"==typeof s&&(s.startsWith("#")||s.startsWith(".")||"me"===s||"it"===s||"you"===s))&&(n=s)}e.modifiers?.for&&(s=await t.evaluate(e.modifiers.for,r));const i={};return void 0!==n&&(i.target=n),void 0!==s&&(i.timeout=s),i}async execute(e,t){const{target:r,timeout:n}=e,s=ri(r,t,"settle"),i=ki(n,5e3),a=Date.now(),o=getComputedStyle(s),l=xi(o.transitionDuration),c=xi(o.transitionDelay),u=xi(o.animationDuration),d=xi(o.animationDelay),m=Ci(l,c),p=Ci(u,d),h=Math.max(m,p),f=await(y=s,g=h,v=i,g>0?new Promise(e=>{const t=e=>{e.target===y&&n({completed:!0,type:"transition"})},r=e=>{e.target===y&&n({completed:!0,type:"animation"})},n=_a(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",r),clearTimeout(s),clearTimeout(i)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",r);const s=setTimeout(()=>{n({completed:!0,type:"timeout"})},g+50),i=setTimeout(()=>{n({completed:!1,type:"timeout"})},v)}):Promise.resolve({completed:!0,type:"timeout"}));var y,g,v;const b=Date.now()-a;return Object.assign(t,{it:s}),{element:s,settled:f.completed,timeout:i,duration:b}}},$s(t,"SettleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());const Ka=Qs((()=>{let e,t,r=[Ys({description:"Move classes, attributes, and properties from one element to another",syntax:["take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"]}),Xs({name:"take",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(3>e.args.length)throw Error('take requires property, "from", and source');const n=await t.evaluate(e.args[0],r)+"";if("from"!==await t.evaluate(e.args[1],r))throw Error("take syntax: take <property> from <source>");const s=await t.evaluate(e.args[2],r);let i;if(8>e.args.length)e.args.length>3&&(i=await t.evaluate(e.args[3],r));else{const n=await Promise.all([3,4,5,6].map(n=>t.evaluate(e.args[n],r)));"and"===n[0]&&"put"===n[1]&&"it"===n[2]&&"on"===n[3]&&e.args[7]&&(i=await t.evaluate(e.args[7],r))}return!i&&e.modifiers?.on&&(i=await t.evaluate(e.modifiers.on,r)),{property:n,source:s,target:i}}async execute(e,t){const r=ri(e.source,t,"take"),n=ri(e.target?e.target:void 0,t,"take"),s=this.takeProperty(r,e.property);return this.putProperty(n,e.property,s),{targetElement:n,property:e.property,value:s}}takeProperty(e,t){const r=t.trim(),n=r.toLowerCase();if("class"===n||"classes"===n){const t=Array.from(e.classList);return e.className="",t}if(r.startsWith(".")){const t=r.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(r.startsWith("@")){const t=r.substring(1),n=e.getAttribute(t);return e.removeAttribute(t),n}if(r.startsWith("data-")){const t=e.getAttribute(r);return e.removeAttribute(r),t}if("id"===n){const t=e.id;return e.id="",t}if("title"===n){const t=e.title;return e.title="",t}if("value"===n&&"value"in e){const t=e.value;return e.value="",t}const s=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(r.includes("-")||s in e.style||r in e.style){let t;return s in e.style?(t=e.style[s],e.style[s]=""):r in e.style?(t=e.style[r],e.style[r]=""):(t=e.style.getPropertyValue(r),e.style.removeProperty(r)),t}const i=e.getAttribute(t);return null!==i?(e.removeAttribute(t),i):null}putProperty(e,t,r){if(null==r)return;const n=t.trim(),s=n.toLowerCase();if("class"===s||"classes"===s)return void(Array.isArray(r)?r.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof r&&(e.className=r));if(n.startsWith("."))return void(r&&e.classList.add(n.substring(1)));if(n.startsWith("@"))return void e.setAttribute(n.substring(1),r+"");if(n.startsWith("data-"))return void e.setAttribute(n,r+"");if("id"===s)return void(e.id=r+"");if("title"===s)return void(e.title=r+"");if("value"===s&&"value"in e)return void(e.value=r+"");const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());n.includes("-")||i in e.style||n in e.style?i in e.style?e.style[i]=r+"":n in e.style?e.style[n]=r+"":e.style.setProperty(n,r+""):e.setAttribute(t,r+"")}},$s(t,"TakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Ga=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"log",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{values:[]}}async execute(e,t){const r="undefined"!=typeof window?window.console:console;0===e.values.length?r.log():r.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},$s(t,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Za=Qs((()=>{let e,t,r=[Ys({description:"Execute commands in the context of target elements",syntax:["tell <target> <command> [<command> ...]"],examples:["tell #sidebar hide","tell .buttons add .disabled","tell closest <form/> submit"],sideEffects:["context-switching","command-execution"]}),Xs({name:"tell",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],r),commands:e.args.slice(1)}}async execute(e,t){const{target:r,commands:n}=e,s=ni(r,t);if(0===s.length)throw Error("tell command found no target elements");const i=t.locals.get("_runtimeExecute"),a=[];for(const e of s){const r={...t,me:e,you:e};for(const e of n)try{const t=await this.executeCommand(e,r,i);a.push(t),Object.assign(r,{it:t})}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}}return{targetElements:s,commandResults:a,executionCount:s.length*n.length}}async executeCommand(e,t,r){if(e&&"object"==typeof e&&"command"===e.type&&r)return await r(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}},$s(t,"TellCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Xa=Qs((()=>{let e,t,r=[Ys({description:"Evaluate an expression and store the result in the it variable",syntax:["call <expression>"],examples:["call myFunction()",'call fetch("/api/data")',"call element.focus()"],sideEffects:["function-execution","context-mutation"]}),Xs({name:"call",category:"execution"})],n=[];return t=class{parseInput(e,t,r){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:r}=e,n=t.locals?.get("__evaluator"),s=n?await n.evaluate(r,t):await or(r,t);let i,a,o=!1;return"function"==typeof s?(a="function",i=s(),i instanceof Promise&&(o=!0,i=await i)):s instanceof Promise?(a="promise",o=!0,i=await s):(a="value",i=s),Object.assign(t,{it:i,result:i}),{result:i,wasAsync:o,expressionType:a}}},$s(t,"CallCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Ya=Qs((()=>{let e,t,r=[Ys({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"]}),Xs({name:"focus",category:"execution"})],n=[];return t=class{async parseInput(e,t,r){return{targets:await oi(e.args,t,r,"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=>ei(e))}},$s(t,"FocusCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),Qa=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"blur",category:"execution"})],n=[];return t=class{async parseInput(e,t,r){return{targets:await oi(e.args,t,r,"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=>ei(e))}},$s(t,"BlurCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());let eo=(()=>{let e,t,r=[Ys({description:"Copy text or element content to the clipboard",syntax:["copy <source>","copy <source> to clipboard"],examples:['copy "Hello World"',"copy #code-snippet","copy my textContent"],sideEffects:["clipboard-write","custom-events"]}),Xs({name:"copy",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("copy command requires a source (text or element)");const n=await t.evaluate(e.args[0],r);let s="text";if(e.modifiers?.format){const n=await t.evaluate(e.modifiers.format,r);"html"!==n&&"text"!==n||(s=n)}return{source:n,format:s}}async execute(e,t){const{source:r,format:n="text"}=e,s=this.extractText(r,n,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(s),this.dispatchCopyEvent(t,"copy:success",{text:s,method:"clipboard-api"}),{success:!0,text:s,format:n,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(s))return this.dispatchCopyEvent(t,"copy:success",{text:s,method:"execCommand"}),{success:!0,text:s,format:n,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:s,error:"All copy methods failed"}),{success:!1,text:s,format:n,method:"fallback"}}extractText(e,t,r){if("string"==typeof e)return e;if(ei(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&ei(r.me)){const e=r.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,r){if(ei(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},$s(t,"CopyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})();const to=Qs(eo);const ro=Qs((()=>{let e,t,r=[Ys({description:"Select from a collection (first/last/random/range/regex match)",syntax:["pick first <count> of <expr>","pick last <count> of <expr>","pick random [<count>] of <expr>","pick items <i> to <j> of <expr>","pick match of <regex> from <expr>","pick from <array>","pick <item1>, <item2>, ..."],examples:["pick first 3 of items","pick last 2 of items","pick random 2 of items","pick items 1 to 3 of items",'pick match of "[0-9]+" from text',"pick from colors",'pick "red", "green", "blue"'],sideEffects:["random-selection"]}),Xs({name:"pick",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){const n=e.modifiers?.variant,s=n?.value;if("first"===s||"last"===s){const n=await t.evaluate(e.args[0],r),i=await t.evaluate(e.modifiers.count,r);if(!Array.isArray(n))throw Error(`pick ${s}: source must be an array, got ${typeof n}`);if("number"!=typeof i||!Number.isFinite(i))throw Error(`pick ${s}: count must be a number, got ${typeof i}`);return{variant:s,array:n,count:i}}if("random"===s){const n=await t.evaluate(e.args[0],r);if(!Array.isArray(n))throw Error("pick random: source must be an array");let s;if(e.modifiers.count){const n=await t.evaluate(e.modifiers.count,r);if("number"!=typeof n||!Number.isFinite(n))throw Error("pick random: count must be a number, got "+typeof n);s=n}return{variant:"random",array:n,count:s}}if("range"===s){const n=await t.evaluate(e.args[0],r);if(!Array.isArray(n)&&"string"!=typeof n)throw Error("pick items: source must be an array or string");const s=e.modifiers.rangeStart,i="start"===s?.value?"start":await t.evaluate(e.modifiers.rangeStart,r),a="start"===i?"start":Number(i);let o;if(e.modifiers.rangeEnd)if("end"===e.modifiers.rangeEnd.value)o="end";else{const n=await t.evaluate(e.modifiers.rangeEnd,r);o=Number(n)}const l=e.modifiers.rangeMode;return{variant:"range",array:n,rangeStart:a,rangeEnd:o,rangeMode:l?.value??"default"}}if("match"===s||"matches"===s){const n=await t.evaluate(e.args[0],r);if("string"!=typeof n)throw Error(`pick ${s}: source must be a string, got ${typeof n}`);const i=await t.evaluate(e.modifiers.regex,r),a="string"==typeof i?i:i+"",o=e.modifiers.flags,l=o?.value;return{variant:s,source:n,regex:a,flags:l}}if(e.modifiers?.from){const n=await t.evaluate(e.modifiers.from,r);if(!Array.isArray(n))throw Error("pick from requires an array");if(0===n.length)throw Error("Cannot pick from empty array");return{variant:"random",array:n}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{variant:"random",items:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.variant??"random";if("first"===r){const r=e.array??[],n=r.slice(0,e.count??0);return Object.assign(t,{it:n}),{selectedItem:n,sourceLength:r.length,sourceType:"array",variant:"first"}}if("last"===r){const r=e.array??[],n=e.count??0,s=n>0?r.slice(-n):[];return Object.assign(t,{it:s}),{selectedItem:s,sourceLength:r.length,sourceType:"array",variant:"last"}}if("range"===r){const r=e.array??[];let n="start"===e.rangeStart?0:e.rangeStart??0,s=void 0===e.rangeEnd?n+1:"end"===e.rangeEnd?r.length:e.rangeEnd;"inclusive"===e.rangeMode?s++:"exclusive"===e.rangeMode&&n++;const i=r.slice(n,s);return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:r.length,sourceType:"array",variant:"range"}}if("match"===r){const r=e.source??"",n=RegExp(e.regex??"",e.flags).exec(r);return Object.assign(t,{it:n}),{selectedItem:n,sourceLength:r.length,sourceType:"string",variant:"match"}}if("matches"===r){const r=e.source??"",n=e.flags??"g",s=RegExp(e.regex??"",n.includes("g")?n:"g"+n),i=Array.from(r.matchAll(s));return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:r.length,sourceType:"string",variant:"matches"}}const n=e.items??e.array??[];if(0===n.length)throw Error("Cannot pick from empty collection");if(void 0===e.count){const r=Math.floor(Math.random()*n.length),s=n[r];return Object.assign(t,{it:s}),{selectedItem:s,selectedIndex:r,sourceLength:n.length,sourceType:e.items?"items":"array",variant:"random"}}const s=n.slice(),i=[];for(let t=0;e.count>t&&s.length>0;t++){const e=Math.floor(Math.random()*s.length);i.push(s.splice(e,1)[0])}return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:n.length,sourceType:e.items?"items":"array",variant:"random"}}},$s(t,"PickCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());const no=Qs((()=>{let e,t,r=[Ys({description:"Debug output for expressions with type information",syntax:["beep!","beep! <expression>","beep! <expression>, <expression>, ..."],examples:["beep!","beep! myValue","beep! me.id, me.className"],sideEffects:["console-output","debugging"]}),Xs({name:"beep",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return 0===e.args.length?{expressions:[]}:{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.expressions||[];if(0===r.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const n=[];console.group("🔔 beep! Debug Output");for(const e of r){const t=this.debugExpression(e);n.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:r.length,debugged:!0,outputs:n}}debugContext(e){console.group("🔔 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":ei(e)?"HTMLElement":e instanceof Element?"Element":e instanceof Node?"Node":e instanceof Error?"Error":e instanceof Date?"Date":e instanceof RegExp?"RegExp":typeof e}getRepresentation(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Array.isArray(e))return`Array(${e.length}) [${e.slice(0,3).map(e=>this.getRepresentation(e)).join(", ")}${e.length>3?"...":""}]`;if(ei(e)){const t=e;return`<${t.tagName.toLowerCase()}${t.id?"#"+t.id:""}${t.className?"."+t.className.split(" ").join("."):""}/>`}if(e instanceof Error)return"Error: "+e.message;if("string"==typeof e)return e.length>50?`"${e.substring(0,47)}..."`:`"${e}"`;if("object"==typeof e)try{const t=Object.keys(e);return`Object {${t.slice(0,3).join(", ")}${t.length>3?"...":""}}`}catch{return"[Object]"}return e+""}},$s(t,"BeepCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),so=Qs((()=>{let e,t,r=[Ys({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"]}),Xs({name:"breakpoint",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}},$s(t,"BreakpointCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),io=Qs((()=>{let e,t,r=[Ys({description:"Execute inline JavaScript code with access to hyperscript context",syntax:["js <code> end","js(param1, param2) <code> end"],examples:['js console.log("Hello") end',"js(x, y) return x + y end",'js me.style.color = "red" end'],sideEffects:["code-execution","data-mutation"]}),Xs({name:"js",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){let n,s;if(0===e.args.length)throw Error("js command requires JavaScript code");const i=e.args[0],a=e.args[1];if(i&&"literal"===i.type&&"string"==typeof i.value)n=i.value;else{if(!i||void 0===i.value)throw Error("js command requires JavaScript code");n=i.value+""}a&&"arrayLiteral"===a.type&&Array.isArray(a.elements)&&(s=a.elements.map(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const o={code:n};return s&&s.length>0&&(o.parameters=s),o}async execute(e,t){const{code:r,parameters:n=[]}=e;if(!r.trim())return{result:void 0,executed:!1,codeLength:r.length,parameters:n,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,n),s=Function(...Object.keys(e),r),i=await s(...Object.values(e));return void 0!==i&&Object.assign(t,{it:i}),{result:i,executed:!0,codeLength:r.length,parameters:n,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,r)=>{let n=e.locals?.get(r);return void 0===n&&(n=e.variables?.get(r)),void 0===n&&(n=e[r]),t[r]=n,t},{})}}},$s(t,"JsCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),ao=Qs((()=>{let e,t,r=[Ys({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),Xs({name:"async",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:r}=e,n=Date.now();try{const e=await this.executeCommandsAsync(t,r),s=Date.now()-n;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:r.length,results:e,executed:!0,duration:s}}catch(e){throw Error("Async command execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}async executeCommandsAsync(e,t){const r=[];for(let n=0;t.length>n;n++){const s=t[n];try{const t=await this.executeCommand(s,e);r.push(t),Object.assign(e,{it:t})}catch(e){const r=this.getCommandName(s);throw Error(`Command '${r}' (${n+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return r}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"execute"in e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},$s(t,"AsyncCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})()),oo=Qs((()=>{let e,t,r=[Ys({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"]}),Xs({name:"go",category:"navigation"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{args:[]}}async execute(e,t){const{args:r}=e;if(0===r.length)throw Error("Go command requires arguments");if("string"==typeof r[0]&&"back"===r[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(r))return{result:await this.navigateToUrl(r,t),type:"url"};const n=this.findBareUrl(r);return null!==n?{result:await this.navigateToBareUrl(n,r),type:"url"}:{result:await this.scrollToElement(r,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 r=e.findIndex(e=>"url"===e),n=e[r+1];if(!n)throw Error('URL is required after "url" keyword');const s="string"==typeof n?n:n+"",i=e.includes("new")&&e.includes("window");if(!this.isValidUrl(s))throw Error(`Invalid URL: "${s}"`);if(i){if("undefined"!=typeof window&&window.open){const e=window.open(s,"_blank");e?.focus&&e.focus()}}else s.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=s):"undefined"!=typeof window&&(window.location.assign?.(s)??(window.location.href=s));return s}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const r=this.parseScrollPosition(e),n=this.parseScrollTarget(e),s=this.parseScrollOffset(e),i=!e.includes("instantly"),a=this.resolveScrollTarget(n,t);if(!a)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==s){a.scrollIntoView?.({behavior:e,block:t,inline:n});const{x:i,y:o}=this.calculateScrollPosition(a,r,s);window.scrollTo?.({left:i,top:o,behavior:e})}else a.scrollIntoView?.({behavior:e,block:t,inline:n})}return a}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let s=!1,i=!1;for(const a of e)"string"==typeof a&&(r.includes(a)?(t.vertical=a,s=!0):n.includes(a)&&(t.horizontal=a,i=!0));return i&&!s&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let r=e[t+1];return"the"===r&&e.length>t+2&&(r=e[t+2]),r}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!r.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const r=e[t];if("string"==typeof r){const e=r.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===r||"-"===r)&&e.length>t+1){const n=e[t+1],s="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(s))return"-"===r?-s:s}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const r="string"==typeof e?e:e+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&ei(t.me))return t.me;if("it"===r&&ei(t.it))return t.it;if("you"===r&&ei(t.you))return t.you;const n=Gi(r,t);if(ei(n))return n;if("undefined"!=typeof document)try{const e=document.querySelector(r);if(e)return e}catch{try{const e=document.getElementsByTagName(r);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,r){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const n=e.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,a=window.innerWidth||800,o=window.innerHeight||600;let l=s,c=i;switch(t.horizontal){case"left":l=n.left+s;break;case"center":l=n.left+s+n.width/2-a/2;break;case"right":l=n.right+s-a}switch(t.vertical){case"top":c=n.top+i+r;break;case"middle":c=n.top+i+n.height/2-o/2+r;break;case"bottom":c=n.bottom+i-o+r}return{x:Math.max(0,l),y:Math.max(0,c)}}},$s(t,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());class lo{constructor(){this.name="install"}get metadata(){return lo.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("install command requires a behavior name");const n=e.args[0];let s,i,a;if(s="identifier"===n?.type&&"string"==typeof n.name?n.name:await t.evaluate(n,r)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(s))throw Error(`Behavior name must be PascalCase (start with uppercase): "${s}"`);if(e.args.length>=2){const n=await t.evaluate(e.args[1],r);if(n&&"object"==typeof n&&!Array.isArray(n)){i=n;for(const e of Object.keys(i))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(a=await t.evaluate(e.modifiers.on,r)),{behaviorName:s,parameters:i,target:a}}async execute(e,t){const{behaviorName:r,parameters:n={},target:s}=e;try{const e=this.resolveTarget(s,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(r,t))throw Error(`Behavior "${r}" is not defined. Define it using the 'behavior' keyword before installing.`);const i=[];for(const s of e){const e=await this.installBehavior(r,s,n,t);i.push(e)}return{success:!0,behaviorName:r,installedCount:i.length,instances:i}}catch(e){throw Error(`Failed to install behavior "${r}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(ei(e))return[e];throw Error('No target specified and "me" is not available in context')}if(ei(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>ei(e));if(0===t.length)throw Error("Target array contains no valid HTMLElements");return t}if("string"==typeof e){if("me"===e){const e=t.me||t.locals.get("me");if(ei(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),r=Array.from(t).filter(e=>ei(e));if(0===r.length)throw Error(`No elements found matching selector: "${e}"`);return r}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>ei(e));if(0===t.length)throw Error("Target collection contains no valid HTMLElements");return t}if("object"==typeof e&&"element"in e){const t=e.element;if(ei(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+e)}behaviorExists(e,t){const r=t.locals.get("_behaviors");if(r&&"object"==typeof r){const t=r;if(t.has(e))return!0;if(t.resolve&&t.resolve(e))return!0}if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors){if(t.behaviors.has(e))return!0;if(t.behaviors.resolve&&t.behaviors.resolve(e))return!0}}return!1}async installBehavior(e,t,r,n){const s=n.locals.get("_behaviors");if(s&&"object"==typeof s){const n=s;if(n.install&&"function"==typeof n.install)return await n.install(e,t,r)}if("undefined"!=typeof globalThis){const n=globalThis._hyperscript;if(n?.behaviors?.install)return await n.behaviors.install(e,t,r)}throw Error("Behavior system not available in context")}}lo.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};const co=Qs((()=>{let e,t,r=[Ys({description:"Add content to the end of a string, array, or HTML element",syntax:["append <content>","append <content> to <target>"],examples:['append "Hello"','append "World" to greeting',"append item to myArray",'append "<p>New</p>" to #content'],sideEffects:["data-mutation","dom-mutation"]}),Xs({name:"append",category:"content"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("append requires content");const n=await t.evaluate(e.args[0],r);let s;return e.modifiers?.to?s=await t.evaluate(e.modifiers.to,r):e.target&&(s=e.target),{content:n,target:s}}async execute(e,t){const{content:r,target:n}=e,s=r+"";if(!n)return Object.assign(t,void 0===t.it?{it:s}:{it:t.it+""+s}),{result:t.it,targetType:"result"};if("string"==typeof n){if(n.startsWith("#")||n.startsWith(".")||n.includes("[")){const e=this.resolveDOMElement(n);return e.innerHTML+=s,{result:e,targetType:"element",target:e}}if("me"===n||"it"===n||"you"===n){const e=this.resolveContextRef(n,t);if(ei(e))return e.innerHTML+=s,{result:e,targetType:"element",target:e}}const e=Gi(n,t);if(void 0!==e){if(Array.isArray(e))return e.push(r),{result:e,targetType:"array",target:n};const i=(null==e?"":e+"")+s;return Zi(n,i,t),{result:i,targetType:"variable",target:n}}return Zi(n,s,t),{result:s,targetType:"variable",target:n}}if(Array.isArray(n))return n.push(r),{result:n,targetType:"array"};if(ei(n))return n.innerHTML+=s,{result:n,targetType:"element",target:n};{const e=n+""+s;return Object.assign(t,{it:e}),{result:e,targetType:"string"}}}resolveDOMElement(e){if("undefined"==typeof document)throw Error("DOM not available");const t=document.querySelector(e);if(!t)throw Error("Element not found: "+e);return t}resolveContextRef(e,t){switch(e){case"me":return t.me;case"it":return t.it;case"you":return t.you;default:throw Error("Unknown context ref: "+e)}}},$s(t,"AppendCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;qs(null,e={value:t},r,{kind:"class",name:t.name,metadata:s},null,n),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ms(t,n)})(),t})());class uo{constructor(){this.name="render"}get metadata(){return uo.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("render command requires a template");const n=await t.evaluate(e.args[0],r);let s;if(e.args.length>=3&&"with"===await t.evaluate(e.args[1],r)){const n=await t.evaluate(e.args[2],r);n&&"object"==typeof n&&(s=n)}if(!s&&e.modifiers?.with){const n=await t.evaluate(e.modifiers.with,r);n&&"object"==typeof n&&(s=n)}return{template:n,variables:s}}async execute(e,t){const{template:r,variables:n={}}=e,s=this.extractTemplateContent(r,t),i=this.createTemplateContext(t,n),a=[],o=await this.processTemplate(s,i,a),l=this.createDOMElement(o);return Object.assign(t,{it:l}),{element:l,rendered:o,directivesProcessed:a}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let r=e;if(!r.includes("<")&&!r.includes("$")){const e=this.resolveVariable(r,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(r=e)}const n=r.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return n?n[1]:r}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,r){const n=e.split("\n"),s=[];let i=0;for(;n.length>i;){const e=n[i].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:a}=await this.processRepeatDirective(n,i,t);s.push(a),i=e,r.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:a}=await this.processIfDirective(n,i,t,r);s.push(a),i=e,r.push("@if")}else if("@else"===e||"@end"===e)i++;else{const r=this.processVariableInterpolation(e,t);s.push(r),i++}}return s.join("\n")}async processRepeatDirective(e,t,r){const n=e[t].trim(),s=n.match(/^@repeat\s+in\s+(.+)$/);if(!s)throw Error("Invalid @repeat syntax: "+n);const i=this.evaluateExpression(s[1],r),{endIndex:a,blockContent:o}=this.extractDirectiveBlock(e,t+1),l=[];if(Array.isArray(i))for(const e of i){const t={...r,locals:new Map([...r.locals.entries(),["it",e]])},n=await this.processTemplate(o.join("\n"),t,[]);l.push(n)}return{nextIndex:a+1,rendered:l.join("\n")}}async processIfDirective(e,t,r,n){const s=e[t].trim(),i=s.match(/^@if\s+(.+)$/);if(!i)throw Error("Invalid @if syntax: "+s);const a=!!this.evaluateExpression(i[1],r),{endIndex:o,blockContent:l,elseContent:c}=this.extractIfElseBlock(e,t+1);let u="";return a?u=await this.processTemplate(l.join("\n"),r,[]):c.length>0&&(u=await this.processTemplate(c.join("\n"),r,[]),n.push("@else")),{nextIndex:o+1,rendered:u}}extractDirectiveBlock(e,t){const r=[];let n=1,s=t;for(;e.length>s&&n>0;){const t=e[s].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(n++,r.push(e[s])):"@end"===t?(n--,n>0&&r.push(e[s])):r.push(e[s]),s++}return{endIndex:s-1,blockContent:r}}extractIfElseBlock(e,t){const r=[],n=[];let s=1,i=t,a=!1;for(;e.length>i&&s>0;){const t=e[i].trim();if(t.startsWith("@if "))s++;else{if("@else"===t&&1===s){a=!0,i++;continue}if("@end"===t&&(s--,0===s))break}a?n.push(e[i]):r.push(e[i]),i++}return{endIndex:i,blockContent:r,elseContent:n}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=r.trim();if(e.startsWith("unescaped ")){const r=e.substring(10).trim();return(this.evaluateExpression(r,t)||"")+""}const n=this.evaluateExpression(e,t);return this.escapeHtml((n||"")+"")}catch(t){return ue(`render: template interpolation error for ${r}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const r=Number(e);if(!isNaN(r)&&""!==e.trim())return r;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++){if("object"!=typeof n||null===n)return;n=n[r[e]]}return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}uo.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};class mo{constructor(){this.name="pseudo-command"}get metadata(){return mo.metadata}async parseInput(e,t,r){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const n=e.args[0].properties||[];let s,i,a="",o=[];for(const e of n){const n=e.value;switch(e.key?.name||e.key?.value){case"methodName":a=n?.value||await t.evaluate(n,r)+"";break;case"methodArgs":"arrayLiteral"===n?.type&&n.elements?o=await Promise.all(n.elements.map(e=>t.evaluate(e,r))):"literal"===n?.type&&Array.isArray(n.value)&&(o=await Promise.all(n.value.map(e=>t.evaluate(e,r))));break;case"preposition":const e=n?.value;e&&"null"!==e&&(s=e);break;case"target":case"targetExpression":i=await t.evaluate(n,r)}}if(!a)throw Error("pseudo-command requires method name");if(null==i)throw Error("pseudo-command requires a target expression");return{methodName:a,methodArgs:o,preposition:s,targetExpression:i}}if(2>e.args.length)throw Error("pseudo-command requires method name and target expression");const n=await t.evaluate(e.args[0],r)+"",s=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,r))):[];let i,a;const o=["from","on","with","into","at","to"];for(const n of o)if(e.modifiers?.[n]){a=n,i=await t.evaluate(e.modifiers[n],r);break}if(i||3>e.args.length||(i=await t.evaluate(e.args[2],r)),!i)throw Error("pseudo-command requires a target expression");return{methodName:n,methodArgs:s,preposition:a,targetExpression:i}}async execute(e,t){const{methodName:r,methodArgs:n,targetExpression:s}=e;try{const e=await this.resolveTarget(s,t);if(null==e)throw Error("Target expression resolved to "+e);const i=this.resolveMethod(e,r);if(!i)throw Error(`Method "${r}" not found on target object`);if("function"!=typeof i)throw Error(`"${r}" is not a function (it's a ${typeof i})`);const a=await this.executeMethod(i,e,n);return t.locals.set("result",a),Object.assign(t,{it:a}),{result:a,methodName:r,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const r=e.split(".");let n="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(r[0])?(n=t.locals.get(r[0]),r.shift()):t.variables?.has(r[0])?(n=t.variables.get(r[0]),r.shift()):t.globals.has(r[0])&&(n=t.globals.get(r[0]),r.shift());for(const e of r){if(null==n)return null;n=n[e]}return n}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const r=t.split(".");let n=e;for(let e=0;r.length>e;e++){const t=r[e];if(null==n)return null;if(!(t in n))return null;if(n=n[t],e===r.length-1&&"function"==typeof n)return n}return null}async executeMethod(e,t,r){try{const n=e.apply(t,r);return n&&"object"==typeof n&&"then"in n?await n:n}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}mo.metadata={description:"Treat a method on an object as a top-level command",syntax:["<method>(<args>) [(to|on|with|into|from|at)] <expression>"],examples:['getElementById("d1") from the document',"reload() the location of the window",'setAttribute("foo", "bar") on me',"foo() on me"],category:"execution",sideEffects:["method-execution"]};var po={to:"destination",into:"destination",from:"source",with:"style",by:"quantity",as:"method",on:"event",over:"duration",for:"duration"},ho=new Set(["to","from","into","with","at","in","of","as","by","before","after","without"]),fo=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","open","pick","process","push","put","remove","render","repeat","replace","reset","return","select","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),yo=new Set(["then","else","end","and","or","not","if","unless","for","while","until","forever","times","each","index","in","to","from","into","with","without","of","at","by","as","matches","contains","is","exists","on","when","every","event","init","def","behavior","global","local","the","a","an","first","last","start","before","after"]),go=new Set(["click","dblclick","mousedown","mouseup","mouseenter","mouseleave","mouseover","mouseout","mousemove","keydown","keyup","keypress","focus","blur","change","input","submit","reset","load","unload","resize","scroll","touchstart","touchend","touchmove","touchcancel","dragstart","dragend","dragenter","dragleave","dragover","drop","contextmenu","wheel","pointerdown","pointerup","pointermove","ms","s"]),vo=new Set(["and","or","not","is","exists","matches","contains","then","else"]),bo=new Set(["true","false","null","undefined","it","me","my","result"]),wo=new Set(["first","last","next","previous","prev","at","random","closest","parent","children","within","no","empty","some","starts with","ends with"]),ko=new Set(["if","unless","when","where","もし","時に","ときに","どこで","如果","当","إذا","عندما","حيث","si","cuando","donde","wenn","wann","wo","quand","lorsque","où","quando","onde","eğer","zaman","nerede","ketika","saat","dimana","때","어디서","maypi","wakati","wapi"]),Eo=new Set(["then","それから","那么","ثم","entonces","alors","dann","sonra","lalu","chayqa","kisha"]);function xo(e,t,r={}){const{allowEnglishFallback:n=!0}=r,s=new Map,i=new Map,a=new Map,o=new Map,l=new Map,c=new Map,u=new Map,d=new Map,m=new Map,p=new Map;function h(e,t,r=!1){for(const[n,s]of Object.entries(e)){const e=s.toLowerCase();t.set(e,n.toLowerCase()),!r&&m.has(e)||m.set(e,n.toLowerCase()),p.set(n.toLowerCase(),s.toLowerCase())}}e.commands&&h(e.commands,s,!0),e.logical&&h(e.logical,o,!0),e.events&&h(e.events,a),e.values&&h(e.values,c),e.temporal&&h(e.temporal,l),e.modifiers&&h(e.modifiers,i),e.attributes&&h(e.attributes,u),e.expressions&&h(e.expressions,d);const f=new Set(s.keys()),y=new Set(m.keys());if(n){for(const e of fo)f.add(e);for(const e of yo)y.add(e);for(const e of go)y.add(e)}return{locale:t,resolve(e){const t=e.toLowerCase(),r=m.get(t);if(void 0!==r)return r;if(n){if(fo.has(t)||yo.has(t))return t;if(go.has(t))return t}},isCommand(e){const t=e.toLowerCase();return!!s.has(t)||!(!n||!fo.has(t))},isKeyword(e){const t=e.toLowerCase();return!!(i.has(t)||o.has(t)||l.has(t)||c.has(t))||!(!n||!yo.has(t))},isEvent(e){const t=e.toLowerCase();return!!a.has(t)||!!go.has(t)},isModifier(e){const t=e.toLowerCase();return i.has(t)||n&&ho.has(t)},isLogical(e){const t=e.toLowerCase();return o.has(t)||n&&vo.has(t)},isValue(e){const t=e.toLowerCase();return c.has(t)||n&&bo.has(t)},isExpression(e){const t=e.toLowerCase();return d.has(t)||n&&wo.has(t)},getCommands:()=>Array.from(f),getKeywords:()=>Array.from(y),toLocale:e=>p.get(e.toLowerCase())}}function Co(){return{locale:"en",resolve(e){const t=e.toLowerCase();if(fo.has(t)||yo.has(t)||go.has(t))return t},isCommand:e=>fo.has(e.toLowerCase()),isKeyword:e=>yo.has(e.toLowerCase()),isEvent:e=>go.has(e.toLowerCase()),isModifier:e=>ho.has(e.toLowerCase()),isLogical:e=>vo.has(e.toLowerCase()),isValue:e=>bo.has(e.toLowerCase()),isExpression:e=>wo.has(e.toLowerCase()),getCommands:()=>Array.from(fo),getKeywords:()=>Array.from(yo),toLocale:e=>e.toLowerCase()}}var So={commands:{on:"en",tell:"decir",trigger:"disparar",send:"enviar",take:"tomar",put:"poner",set:"establecer",get:"obtener",add:"agregar",remove:"quitar",toggle:"alternar",hide:"ocultar",show:"mostrar",if:"si",unless:"menos",repeat:"repetir",for:"para",while:"mientras",until:"hasta",continue:"continuar",break:"romper",halt:"detener",wait:"esperar",fetch:"buscar",call:"llamar",return:"retornar",make:"hacer",log:"registrar",throw:"lanzar",catch:"atrapar",measure:"medir",transition:"transición",increment:"incrementar",decrement:"decrementar",default:"predeterminar",go:"ir",pushUrl:"pushUrl",replaceUrl:"reemplazarUrl",copy:"copiar",pick:"escoger",beep:"pitido",js:"js",async:"asíncrono",render:"renderizar",swap:"intercambiar",morph:"transformar",settle:"estabilizar",append:"añadir",exit:"salir",install:"instalar",breakpoint:"punto-interrupción",clear:"limpiar",close:"cerrar",open:"abrir",select:"seleccionar",clone:"clonar",prepend:"anteponer"},modifiers:{to:"a",from:"de",into:"en",with:"con",at:"en",in:"en",of:"de",as:"como",by:"por",before:"antes",after:"después",over:"sobre",under:"bajo",between:"entre",through:"través",without:"sin"},events:{click:"clic",dblclick:"dobleclic",mousedown:"ratónabajo",mouseup:"ratónarriba",mouseenter:"ratónentrar",mouseleave:"ratónsalir",mouseover:"ratónencima",mouseout:"ratónfuera",mousemove:"ratónmover",keydown:"teclaabajo",keyup:"teclaarriba",keypress:"teclapresar",focus:"enfocar",blur:"desenfocar",change:"cambiar",input:"entrada",submit:"enviar",reset:"reiniciar",load:"cargar",unload:"descargar",resize:"redimensionar",scroll:"desplazar",touchstart:"toqueempezar",touchend:"toqueterminar",touchmove:"toquemover",touchcancel:"toquecancelar"},logical:{when:"cuando",where:"donde",and:"y",or:"o",not:"no",is:"es",exists:"existe",matches:"coincide",contains:"contiene",includes:"incluye",equals:"iguala",has:"tiene",have:"tengo",then:"entonces",else:"sino",otherwise:"delocontrario",end:"fin",live:"vivo",changes:"cambia"},temporal:{seconds:"segundos",second:"segundo",milliseconds:"milisegundos",millisecond:"milisegundo",minutes:"minutos",minute:"minuto",hours:"horas",hour:"hora",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"verdadero",false:"falso",null:"nulo",undefined:"indefinido",it:"ello",its:"su",me:"yo",my:"mi",you:"tu",your:"tu",yourself:"ti mismo",myself:"yo mismo",element:"elemento",target:"objetivo",detail:"detalle",event:"evento",window:"ventana",document:"documento",body:"cuerpo",result:"resultado",value:"valor"},attributes:{class:"clase",classes:"clases",style:"estilo",styles:"estilos",attribute:"atributo",attributes:"atributos",property:"propiedad",properties:"propiedades"},expressions:{first:"primero",last:"último",next:"siguiente",previous:"anterior",prev:"ant",at:"en",random:"aleatorio",closest:"máscercano",parent:"padre",children:"hijos",within:"dentro",no:"ningún",empty:"vacío",some:"algún","starts with":"empieza con","ends with":"termina con","ignoring case":"ignorando mayúsculas","sorted by":"ordenado por","mapped to":"transformado a","split by":"dividido por","joined by":"unido por"}},Ao=xo(So,"es",{allowEnglishFallback:!0}),To={commands:{on:"で",tell:"伝える",trigger:"引き金",send:"送る",take:"取る",put:"置く",set:"設定",get:"取得",add:"追加",remove:"削除",toggle:"切り替え",hide:"隠す",show:"表示",if:"もし",unless:"でなければ",repeat:"繰り返し",for:"ために",while:"の間",until:"まで",continue:"続ける",break:"中断",halt:"停止",wait:"待つ",fetch:"取得",call:"呼び出し",return:"戻る",make:"作る",log:"記録",throw:"投げる",catch:"捕まえる",measure:"測定",transition:"遷移",increment:"増加",decrement:"減少",default:"既定",go:"移動",pushUrl:"URLプッシュ",replaceUrl:"URL置換",copy:"コピー",pick:"選択",beep:"ビープ",js:"JS実行",async:"非同期",render:"描画",swap:"交換",morph:"変形",settle:"安定",append:"末尾追加",exit:"終了",install:"インストール",breakpoint:"ブレークポイント",clear:"クリア",close:"閉じる",open:"開く",select:"選択",clone:"複製",prepend:"先頭追加"},modifiers:{to:"に",from:"から",into:"へ",with:"と",at:"で",in:"の中",of:"の",as:"として",by:"によって",before:"前に",after:"後に",over:"上に",under:"下に",between:"間に",through:"通して",without:"なしで"},events:{click:"クリック",dblclick:"ダブルクリック",mousedown:"マウス押下",mouseup:"マウス解放",mouseenter:"マウス入る",mouseleave:"マウス離れる",mouseover:"マウス上",mouseout:"マウス外",mousemove:"マウス移動",keydown:"キー押下",keyup:"キー解放",keypress:"キー押す",focus:"フォーカス",blur:"ぼかし",change:"変更",input:"入力",submit:"送信",reset:"リセット",load:"読み込み",unload:"読み込み解除",resize:"サイズ変更",scroll:"スクロール",touchstart:"タッチ開始",touchend:"タッチ終了",touchmove:"タッチ移動",touchcancel:"タッチキャンセル"},logical:{when:"とき",where:"どこ",and:"そして",or:"または",not:"ではない",is:"である",exists:"存在する",matches:"一致する",contains:"含む",includes:"含める",equals:"等しい",has:"ある",have:"ある",then:"それから",else:"そうでなければ",otherwise:"そうでなければ",end:"終わり",live:"ライブ",changes:"変わったら"},temporal:{seconds:"秒",second:"秒",milliseconds:"ミリ秒",millisecond:"ミリ秒",minutes:"分",minute:"分",hours:"時間",hour:"時間",ms:"ms",s:"秒",min:"分",h:"時"},values:{true:"真",false:"偽",null:"null",undefined:"未定義",it:"それ",its:"その",me:"私",my:"私の",you:"あなた",your:"あなたの",yourself:"あなた自身",myself:"私自身",element:"要素",target:"対象",detail:"詳細",event:"イベント",window:"ウィンドウ",document:"ドキュメント",body:"ボディ",result:"結果",value:"値"},attributes:{class:"クラス",classes:"クラス群",style:"スタイル",styles:"スタイル群",attribute:"属性",attributes:"属性群",property:"プロパティ",properties:"プロパティ群"},expressions:{first:"最初",last:"最後",next:"次",previous:"前",prev:"前",at:"で",random:"ランダム",closest:"最も近い",parent:"親",children:"子",within:"以内",no:"ない",empty:"空",some:"いくつか","starts with":"で始まる","ends with":"で終わる","ignoring case":"大文字小文字を無視","sorted by":"でソート","mapped to":"に変換","split by":"で分割","joined by":"で結合"}},Oo=xo(To,"ja",{allowEnglishFallback:!0}),Po={commands:{on:"sur",tell:"dire",trigger:"déclencher",send:"envoyer",take:"prendre",put:"mettre",set:"définir",get:"obtenir",add:"ajouter",remove:"supprimer",toggle:"basculer",hide:"cacher",show:"montrer",if:"si",unless:"saufsi",repeat:"répéter",for:"pour",while:"tantque",until:"jusquà",continue:"continuer",break:"arrêter",halt:"stopper",wait:"attendre",fetch:"récupérer",call:"appeler",return:"retourner",make:"créer",log:"enregistrer",throw:"lancer",catch:"attraper",measure:"mesurer",transition:"transition",increment:"incrémenter",decrement:"décrémenter",default:"défaut",go:"aller",pushUrl:"pousserUrl",replaceUrl:"remplacerUrl",copy:"copier",pick:"choisir",beep:"bip",js:"js",async:"asynchrone",render:"rendu",swap:"échanger",morph:"transformer",settle:"stabiliser",append:"ajouter",exit:"sortir",install:"installer",breakpoint:"point-arrêt",clear:"effacer",close:"fermer",open:"ouvrir",select:"sélectionner",clone:"cloner",prepend:"préfixer"},modifiers:{to:"à",from:"de",into:"dans",with:"avec",at:"à",in:"en",of:"de",as:"comme",by:"par",before:"avant",after:"après",over:"sur",under:"sous",between:"entre",through:"à travers",without:"sans"},events:{click:"clic",dblclick:"doubleclic",mousedown:"sourisappuyée",mouseup:"sourisrelâchée",mouseenter:"sourisentrer",mouseleave:"sourissortir",mouseover:"sourissur",mouseout:"sourisdehors",mousemove:"sourisbouger",keydown:"toucheappuyée",keyup:"toucherelâchée",keypress:"touchepressée",focus:"focus",blur:"flou",change:"changer",input:"saisie",submit:"soumettre",reset:"réinitialiser",load:"charger",unload:"décharger",resize:"redimensionner",scroll:"défiler",touchstart:"touchercommencer",touchend:"toucherfin",touchmove:"toucherbouger",touchcancel:"toucherannuler"},logical:{when:"quand",where:"où",and:"et",or:"ou",not:"non",is:"est",exists:"existe",matches:"correspond",contains:"contient",includes:"inclut",equals:"égale",has:"a",have:"ai",then:"alors",else:"sinon",otherwise:"autrement",end:"fin",live:"vif",changes:"change"},temporal:{seconds:"secondes",second:"seconde",milliseconds:"millisecondes",millisecond:"milliseconde",minutes:"minutes",minute:"minute",hours:"heures",hour:"heure",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"vrai",false:"faux",null:"nul",undefined:"indéfini",it:"ça",its:"son",me:"moi",my:"mon",you:"tu",your:"ton",yourself:"toi-même",myself:"moi-même",element:"élément",target:"cible",detail:"détail",event:"événement",window:"fenêtre",document:"document",body:"corps",result:"résultat",value:"valeur"},attributes:{class:"classe",classes:"classes",style:"style",styles:"styles",attribute:"attribut",attributes:"attributs",property:"propriété",properties:"propriétés"},expressions:{first:"premier",last:"dernier",next:"suivant",previous:"précédent",prev:"préc",at:"à",random:"aléatoire",closest:"plusproche",parent:"parent",children:"enfants",within:"dans",no:"aucun",empty:"vide",some:"quelques","starts with":"commence par","ends with":"finit par","ignoring case":"en ignorant la casse","sorted by":"trié par","mapped to":"transformé en","split by":"divisé par","joined by":"joint par"}},Lo=xo(Po,"fr",{allowEnglishFallback:!0}),No={commands:{on:"bei",tell:"sagen",trigger:"auslösen",send:"senden",take:"nehmen",put:"setzen",set:"festlegen",get:"erhalten",add:"hinzufügen",remove:"entfernen",toggle:"umschalten",hide:"verstecken",show:"zeigen",if:"wenn",unless:"wennnicht",repeat:"wiederholen",for:"für",while:"während",until:"bis",continue:"weiter",break:"unterbrechen",halt:"anhalten",wait:"warten",fetch:"holen",call:"aufrufen",return:"zurückgeben",make:"erstellen",log:"protokollieren",throw:"werfen",catch:"fangen",measure:"messen",transition:"übergang",increment:"erhöhen",decrement:"verringern",default:"standard",go:"gehen",pushUrl:"urlHinzufügen",replaceUrl:"urlErsetzen",copy:"kopieren",pick:"auswählen",beep:"piepton",js:"js",async:"asynchron",render:"rendern",swap:"tauschen",morph:"verwandeln",settle:"stabilisieren",append:"anhängen",exit:"beenden",install:"installieren",breakpoint:"haltepunkt",clear:"löschen",close:"schließen",open:"öffnen",select:"auswählen",clone:"klonen",prepend:"voranstellen"},modifiers:{to:"zu",from:"von",into:"in",with:"mit",at:"bei",in:"in",of:"von",as:"als",by:"durch",before:"vor",after:"nach",over:"über",under:"unter",between:"zwischen",through:"durch",without:"ohne"},events:{click:"klick",dblclick:"doppelklick",mousedown:"mausunten",mouseup:"mausoben",mouseenter:"mauseintreten",mouseleave:"mausverlassen",mouseover:"mausüber",mouseout:"maushinaus",mousemove:"mausbewegen",keydown:"tasteunten",keyup:"tasteoben",keypress:"tastedrücken",focus:"fokus",blur:"unscharf",change:"ändern",input:"eingabe",submit:"absenden",reset:"zurücksetzen",load:"laden",unload:"entladen",resize:"größeändern",scroll:"scrollen",touchstart:"berührungstart",touchend:"berührungend",touchmove:"berührungbewegen",touchcancel:"berührungabbrechen"},logical:{when:"wenn",where:"wo",and:"und",or:"oder",not:"nicht",is:"ist",exists:"existiert",matches:"passt",contains:"enthält",includes:"beinhaltet",equals:"gleicht",has:"hat",have:"habe",then:"dann",else:"sonst",otherwise:"andernfalls",end:"ende",live:"live",changes:"ändert"},temporal:{seconds:"sekunden",second:"sekunde",milliseconds:"millisekunden",millisecond:"millisekunde",minutes:"minuten",minute:"minute",hours:"stunden",hour:"stunde",ms:"ms",s:"s",min:"min",h:"std"},values:{true:"wahr",false:"falsch",null:"null",undefined:"undefiniert",it:"es",its:"sein",me:"ich",my:"mein",you:"du",your:"dein",yourself:"dich selbst",myself:"ich selbst",element:"element",target:"ziel",detail:"detail",event:"ereignis",window:"fenster",document:"dokument",body:"körper",result:"ergebnis",value:"wert"},attributes:{class:"klasse",classes:"klassen",style:"stil",styles:"stile",attribute:"attribut",attributes:"attribute",property:"eigenschaft",properties:"eigenschaften"},expressions:{first:"erste",last:"letzte",next:"nächste",previous:"vorherige",prev:"vorh",at:"bei",random:"zufällig",closest:"nächste",parent:"elternteil",children:"kinder",within:"innerhalb",no:"kein",empty:"leer",some:"einige","starts with":"beginnt mit","ends with":"endet mit","ignoring case":"ohne Groß-/Kleinschreibung","sorted by":"sortiert nach","mapped to":"zugeordnet zu","split by":"geteilt durch","joined by":"verbunden mit"}},Io=xo(No,"de",{allowEnglishFallback:!0}),jo={commands:{on:"على",tell:"أخبر",trigger:"تشغيل",send:"أرسل",take:"خذ",put:"ضع",set:"اضبط",get:"احصل",add:"أضف",remove:"احذف",toggle:"بدل",hide:"اخف",show:"اظهر",if:"إذا",unless:"إلا إذا",repeat:"كرر",for:"لكل",while:"بينما",until:"حتى",continue:"واصل",break:"توقف",halt:"أوقف",wait:"انتظر",fetch:"احضر",call:"استدع",return:"ارجع",make:"اصنع",log:"سجل",throw:"ارم",catch:"التقط",measure:"قس",transition:"انتقال",increment:"زِد",decrement:"أنقص",default:"افتراضي",go:"اذهب",pushUrl:"ادفع رابط",replaceUrl:"استبدل رابط",copy:"انسخ",pick:"اختر",beep:"صفّر",js:"جافاسكربت",async:"متزامن",render:"ارسم",swap:"بدّل",morph:"حوّل",settle:"استقر",append:"ألحق",exit:"اخرج",install:"ثبّت",breakpoint:"نقطة-توقف",clear:"امسح",close:"أغلق",open:"افتح",select:"اختر",clone:"استنسخ",prepend:"سبق"},modifiers:{to:"إلى",from:"من",into:"في",with:"مع",at:"عند",in:"في",of:"من",as:"كـ",by:"بواسطة",before:"قبل",after:"بعد",over:"فوق",under:"تحت",between:"بين",through:"عبر",without:"بدون"},events:{click:"نقر",dblclick:"نقر مزدوج",mousedown:"فأرة أسفل",mouseup:"فأرة أعلى",mouseenter:"فأرة دخول",mouseleave:"فأرة خروج",mouseover:"فأرة فوق",mouseout:"فأرة خارج",mousemove:"فأرة تحرك",keydown:"مفتاح أسفل",keyup:"مفتاح أعلى",keypress:"مفتاح ضغط",focus:"تركيز",blur:"ضبابية",change:"تغيير",input:"إدخال",submit:"إرسال",reset:"إعادة تعيين",load:"تحميل",unload:"إلغاء تحميل",resize:"تغيير حجم",scroll:"تمرير",touchstart:"بداية لمس",touchend:"نهاية لمس",touchmove:"تحرك لمس",touchcancel:"إلغاء لمس"},logical:{when:"عندما",where:"أين",and:"و",or:"أو",not:"ليس",is:"هو",exists:"موجود",matches:"يطابق",contains:"يحتوي",includes:"يشمل",equals:"يساوي",has:"لديه",have:"لدي",then:"ثم",else:"وإلا",otherwise:"خلاف ذلك",end:"النهاية",live:"حي",changes:"يتغير"},temporal:{seconds:"ثوانِ",second:"ثانية",milliseconds:"ميلي ثانية",millisecond:"ميلي ثانية",minutes:"دقائق",minute:"دقيقة",hours:"ساعات",hour:"ساعة",ms:"م.ث",s:"ث",min:"د",h:"س"},values:{true:"صحيح",false:"خطأ",null:"فارغ",undefined:"غير معرف",it:"هو",its:"له",me:"أنا",my:"لي",myself:"نفسي",you:"أنت",your:"لك",yourself:"نفسك",element:"عنصر",target:"هدف",detail:"تفاصيل",event:"حدث",window:"نافذة",document:"وثيقة",body:"جسم",result:"نتيجة",value:"قيمة"},attributes:{class:"فئة",classes:"فئات",style:"أسلوب",styles:"أساليب",attribute:"خاصية",attributes:"خصائص",property:"خاصية",properties:"خصائص"},expressions:{first:"أول",last:"آخر",next:"التالي",previous:"السابق",prev:"سابق",at:"عند",random:"عشوائي",closest:"الأقرب",parent:"والد",children:"أطفال",within:"داخل",no:"لا يوجد",empty:"فارغ",some:"بعض","starts with":"يبدأ بـ","ends with":"ينتهي بـ","ignoring case":"مع تجاهل الحالة","sorted by":"مرتب حسب","mapped to":"محول إلى","split by":"مقسم بواسطة","joined by":"مدموج بواسطة"}},Ro=xo(jo,"ar",{allowEnglishFallback:!0}),_o={commands:{on:"에",tell:"말하다",trigger:"트리거",send:"보내다",take:"가져오다",put:"넣다",set:"설정",get:"얻다",add:"추가",remove:"제거",toggle:"토글",hide:"숨기다",show:"보이다",if:"만약",unless:"아니면",repeat:"반복",for:"동안",while:"동안",until:"까지",continue:"계속",break:"중단",halt:"정지",wait:"대기",fetch:"가져오기",call:"호출",return:"반환",make:"만들다",log:"로그",throw:"던지다",catch:"잡다",measure:"측정",transition:"전환",increment:"증가",decrement:"감소",default:"기본값",go:"이동",pushUrl:"URL푸시",replaceUrl:"URL교체",copy:"복사",pick:"선택",beep:"비프",js:"JS실행",async:"비동기",render:"렌더링",swap:"교환",morph:"변형",settle:"안정",append:"추가",exit:"종료",install:"설치",breakpoint:"중단점",clear:"지우기",close:"닫기",open:"열기",select:"선택",clone:"복제",prepend:"앞에추가"},modifiers:{to:"에",from:"에서",into:"으로",with:"와",at:"에",in:"안에",of:"의",as:"로",by:"에의해",before:"전에",after:"후에",over:"위에",under:"아래",between:"사이",through:"통해",without:"없이"},events:{click:"클릭",dblclick:"더블클릭",mousedown:"마우스다운",mouseup:"마우스업",mouseenter:"마우스엔터",mouseleave:"마우스리브",mouseover:"마우스오버",mouseout:"마우스아웃",mousemove:"마우스무브",keydown:"키다운",keyup:"키업",keypress:"키프레스",focus:"포커스",blur:"블러",change:"변경",input:"입력",submit:"제출",reset:"리셋",load:"로드",unload:"언로드",resize:"리사이즈",scroll:"스크롤",touchstart:"터치시작",touchend:"터치종료",touchmove:"터치이동",touchcancel:"터치취소"},logical:{when:"때",where:"어디",and:"그리고",or:"또는",not:"아니",is:"이다",exists:"존재",matches:"일치",contains:"포함",includes:"포함하다",equals:"같다",has:"있다",have:"있다",then:"그러면",else:"아니면",otherwise:"그렇지않으면",end:"끝",live:"라이브",changes:"변경되면"},temporal:{seconds:"초",second:"초",milliseconds:"밀리초",millisecond:"밀리초",minutes:"분",minute:"분",hours:"시간",hour:"시간",ms:"ms",s:"초",min:"분",h:"시"},values:{true:"참",false:"거짓",null:"널",undefined:"정의안됨",it:"그것",its:"그것의",me:"나",my:"내",myself:"나자신",you:"너",your:"네",yourself:"너자신",element:"요소",target:"대상",detail:"세부",event:"이벤트",window:"창",document:"문서",body:"바디",result:"결과",value:"값"},attributes:{class:"클래스",classes:"클래스들",style:"스타일",styles:"스타일들",attribute:"속성",attributes:"속성들",property:"프로퍼티",properties:"프로퍼티들"},expressions:{first:"첫번째",last:"마지막",next:"다음",previous:"이전",prev:"이전",at:"에서",random:"무작위",closest:"가장가까운",parent:"부모",children:"자식",within:"이내",no:"없음",empty:"비어있는",some:"일부","starts with":"로시작","ends with":"로끝나는","ignoring case":"대소문자_무시","sorted by":"로_정렬","mapped to":"로_변환","split by":"로_분할","joined by":"로_결합"}},qo=xo(_o,"ko",{allowEnglishFallback:!0}),Mo={commands:{on:"当",tell:"告诉",trigger:"触发",send:"发送",take:"获取",put:"放置",set:"设置",get:"获得",add:"添加",remove:"移除",toggle:"切换",hide:"隐藏",show:"显示",if:"如果",unless:"除非",repeat:"重复",for:"为",while:"当",until:"直到",continue:"继续",break:"中断",halt:"停止",wait:"等待",fetch:"获取",call:"调用",return:"返回",make:"制作",log:"日志",throw:"抛出",catch:"捕获",measure:"测量",transition:"过渡",increment:"增加",decrement:"减少",default:"默认",go:"前往",pushUrl:"推送网址",replaceUrl:"替换网址",copy:"复制",pick:"选取",beep:"蜂鸣",js:"JS执行",async:"异步",render:"渲染",swap:"交换",morph:"变形",settle:"稳定",append:"追加",exit:"退出",install:"安装",breakpoint:"断点",clear:"清除",close:"关闭",open:"打开",select:"选择",clone:"克隆",prepend:"前置"},modifiers:{to:"到",from:"从",into:"进入",with:"与",at:"在",in:"在",of:"的",as:"作为",by:"通过",before:"之前",after:"之后",over:"在上",under:"在下",between:"之间",through:"通过",without:"没有"},events:{click:"点击",dblclick:"双击",mousedown:"鼠标按下",mouseup:"鼠标抬起",mouseenter:"鼠标进入",mouseleave:"鼠标离开",mouseover:"鼠标悬停",mouseout:"鼠标移出",mousemove:"鼠标移动",keydown:"按键按下",keyup:"按键抬起",keypress:"按键",focus:"聚焦",blur:"失焦",change:"改变",input:"输入",submit:"提交",reset:"重置",load:"加载",unload:"卸载",resize:"调整大小",scroll:"滚动",touchstart:"触摸开始",touchend:"触摸结束",touchmove:"触摸移动",touchcancel:"触摸取消"},logical:{when:"当",where:"哪里",and:"和",or:"或",not:"非",is:"是",exists:"存在",matches:"匹配",contains:"包含",includes:"包括",equals:"等于",has:"有",have:"有",then:"那么",else:"否则",otherwise:"要不然",end:"结束",live:"实时",changes:"改变时"},temporal:{seconds:"秒",second:"秒",milliseconds:"毫秒",millisecond:"毫秒",minutes:"分钟",minute:"分钟",hours:"小时",hour:"小时",ms:"毫秒",s:"秒",min:"分",h:"时"},values:{true:"真",false:"假",null:"空",undefined:"未定义",it:"它",its:"它的",me:"我",my:"我的",myself:"我自己",you:"你",your:"你的",yourself:"你自己",element:"元素",target:"目标",detail:"详情",event:"事件",window:"窗口",document:"文档",body:"主体",result:"结果",value:"值"},attributes:{class:"类",classes:"类别",style:"样式",styles:"样式集",attribute:"属性",attributes:"属性集",property:"特性",properties:"特性集"},expressions:{first:"第一个",last:"最后一个",next:"下一个",previous:"上一个",prev:"上个",at:"在",random:"随机",closest:"最近的",parent:"父级",children:"子级",within:"之内",no:"没有",empty:"空的",some:"一些","starts with":"以开头","ends with":"以结尾","ignoring case":"忽略大小写","sorted by":"按_排序","mapped to":"映射为","split by":"按_分割","joined by":"用_连接"}},$o=xo(Mo,"zh",{allowEnglishFallback:!0}),Vo={commands:{on:"üzerinde",tell:"söyle",trigger:"tetikle",send:"gönder",take:"al",put:"koy",set:"ayarla",get:"al",add:"ekle",remove:"kaldır",toggle:"değiştir",hide:"gizle",show:"göster",if:"eğer",unless:"değilse",repeat:"tekrarla",for:"için",while:"iken",until:"kadar",continue:"devam",break:"dur",halt:"durdur",wait:"bekle",fetch:"getir",call:"çağır",return:"dön",make:"yap",log:"kaydet",throw:"fırlat",catch:"yakala",measure:"ölç",transition:"geçiş",increment:"artır",decrement:"azalt",default:"varsayılan",go:"git",pushUrl:"urlEkle",replaceUrl:"urlDeğiştir",copy:"kopyala",pick:"seç",beep:"bip",js:"js",async:"asenkron",render:"render",swap:"takas",morph:"dönüştür",settle:"sabitlen",append:"ekle",exit:"çık",install:"kur",breakpoint:"kesme-noktası",clear:"temizle",close:"kapat",open:"aç",select:"seç",clone:"klonla",prepend:"başınaekle"},modifiers:{to:"e",from:"den",into:"içine",with:"ile",at:"de",in:"içinde",of:"nin",as:"olarak",by:"tarafından",before:"önce",after:"sonra",over:"üzerinde",under:"altında",between:"arasında",through:"boyunca",without:"olmadan"},events:{click:"tıklama",dblclick:"çift_tıklama",mousedown:"fare_bas",mouseup:"fare_bırak",mouseenter:"fare_gir",mouseleave:"fare_çık",mouseover:"fare_üstü",mouseout:"fare_dışı",mousemove:"fare_hareket",keydown:"tuş_bas",keyup:"tuş_bırak",keypress:"tuş_basım",focus:"odak",blur:"bulanık",change:"değişim",input:"giriş",submit:"gönder",reset:"sıfırla",load:"yükle",unload:"yükle_kaldır",resize:"boyut_değiştir",scroll:"kaydır",touchstart:"dokunma_başla",touchend:"dokunma_bitir",touchmove:"dokunma_hareket",touchcancel:"dokunma_iptal"},logical:{when:"iken",where:"nerede",and:"ve",or:"veya",not:"değil",is:"dir",exists:"var",matches:"eşleşir",contains:"içerir",includes:"dahil",equals:"eşittir",has:"var",have:"var",then:"sonra",else:"yoksa",otherwise:"aksi_halde",end:"son",live:"canlı",changes:"değiştiğinde"},temporal:{seconds:"saniye",second:"saniye",milliseconds:"milisaniye",millisecond:"milisaniye",minutes:"dakika",minute:"dakika",hours:"saat",hour:"saat",ms:"ms",s:"s",min:"dk",h:"sa"},values:{true:"doğru",false:"yanlış",null:"boş",undefined:"tanımsız",it:"o",its:"onun",me:"ben",my:"benim",myself:"kendim",you:"sen",your:"senin",yourself:"kendin",element:"öğe",target:"hedef",detail:"detay",event:"olay",window:"pencere",document:"belge",body:"gövde",result:"sonuç",value:"değer"},attributes:{class:"sınıf",classes:"sınıflar",style:"stil",styles:"stiller",attribute:"özellik",attributes:"özellikler",property:"özellik",properties:"özellikler"},expressions:{first:"ilk",last:"son",next:"sonraki",previous:"önceki",prev:"önc",at:"de",random:"rastgele",closest:"en_yakın",parent:"ebeveyn",children:"çocuklar",within:"içinde",no:"yok",empty:"boş",some:"bazı","starts with":"ile başlar","ends with":"ile biter","ignoring case":"büyük küçük harf duyarsız","sorted by":"göre sıralı","mapped to":"ye dönüştürülmüş","split by":"ile bölünmüş","joined by":"ile birleştirilmiş"}},Do=xo(Vo,"tr",{allowEnglishFallback:!0}),zo={commands:{on:"pada",tell:"katakan",trigger:"picu",send:"kirim",take:"ambil",put:"taruh",set:"atur",get:"dapatkan",add:"tambah",remove:"hapus",toggle:"ganti",hide:"sembunyikan",show:"tampilkan",if:"jika",unless:"kecuali",repeat:"ulangi",for:"untuk",while:"selama",until:"sampai",continue:"lanjutkan",break:"hentikan",halt:"berhenti",wait:"tunggu",fetch:"ambil",call:"panggil",return:"kembali",make:"buat",log:"catat",throw:"lempar",catch:"tangkap",measure:"ukur",transition:"transisi",increment:"tambahkan",decrement:"kurangi",default:"bawaan",go:"pergi",pushUrl:"tambahUrl",replaceUrl:"gantiUrl",copy:"salin",pick:"pilih",beep:"bunyi",js:"js",async:"asinkron",render:"tampilkan",swap:"tukar",morph:"ubah_bentuk",settle:"stabil",append:"tambah_akhir",exit:"keluar",install:"pasang",breakpoint:"titik-henti",clear:"hapus",close:"tutup",open:"buka",select:"pilih",clone:"klon",prepend:"awali"},modifiers:{to:"ke",from:"dari",into:"ke_dalam",with:"dengan",at:"di",in:"dalam",of:"dari",as:"sebagai",by:"oleh",before:"sebelum",after:"setelah",over:"di_atas",under:"di_bawah",between:"antara",through:"melalui",without:"tanpa"},events:{click:"klik",dblclick:"klik_ganda",mousedown:"tekan_mouse",mouseup:"lepas_mouse",mouseenter:"mouse_masuk",mouseleave:"mouse_keluar",mouseover:"mouse_atas",mouseout:"mouse_luar",mousemove:"gerak_mouse",keydown:"tekan_tombol",keyup:"lepas_tombol",keypress:"pencet_tombol",focus:"fokus",blur:"blur",change:"ubah",input:"masukan",submit:"kirim",reset:"reset",load:"muat",unload:"bongkar",resize:"ubah_ukuran",scroll:"gulir",touchstart:"mulai_sentuh",touchend:"akhir_sentuh",touchmove:"gerak_sentuh",touchcancel:"batal_sentuh"},logical:{when:"ketika",where:"di_mana",and:"dan",or:"atau",not:"bukan",is:"adalah",exists:"ada",matches:"cocok",contains:"berisi",includes:"termasuk",equals:"sama",has:"punya",have:"punya",then:"lalu",else:"lainnya",otherwise:"sebaliknya",end:"akhir",live:"langsung",changes:"berubah"},temporal:{seconds:"detik",second:"detik",milliseconds:"milidetik",millisecond:"milidetik",minutes:"menit",minute:"menit",hours:"jam",hour:"jam",ms:"ms",s:"d",min:"mnt",h:"j"},values:{true:"benar",false:"salah",null:"kosong",undefined:"tidak_terdefinisi",it:"itu",its:"miliknya",me:"saya",my:"saya punya",myself:"saya sendiri",you:"kamu",your:"kamu punya",yourself:"kamu sendiri",element:"elemen",target:"target",detail:"detail",event:"peristiwa",window:"jendela",document:"dokumen",body:"badan",result:"hasil",value:"nilai"},attributes:{class:"kelas",classes:"kelas_kelas",style:"gaya",styles:"gaya_gaya",attribute:"atribut",attributes:"atribut_atribut",property:"properti",properties:"properti_properti"},expressions:{first:"pertama",last:"terakhir",next:"berikutnya",previous:"sebelumnya",prev:"sblm",at:"di",random:"acak",closest:"terdekat",parent:"induk",children:"anak_anak",within:"dalam",no:"tidak_ada",empty:"kosong",some:"beberapa","starts with":"dimulai dengan","ends with":"diakhiri dengan","ignoring case":"abaikan kapital","sorted by":"diurutkan berdasarkan","mapped to":"dipetakan ke","split by":"dipisah oleh","joined by":"digabung oleh"}},Fo=xo(zo,"id",{allowEnglishFallback:!0}),Bo={commands:{on:"kaqpi",tell:"niy",trigger:"kichay",send:"kachay",take:"hurquy",put:"churay",set:"churay",get:"chaskiy",add:"yapay",remove:"qichuy",toggle:"tikray",hide:"pakay",show:"rikuchiy",if:"sichus",unless:"mana_sichus",repeat:"kutichiy",for:"rayku",while:"kay_kaq",until:"hayk_akama",continue:"purichiy",break:"p_akiy",halt:"sayay",wait:"suyay",fetch:"apamuy",call:"qayay",return:"kutimuy",make:"ruray",log:"qillqay",throw:"wikchuy",catch:"hapsiy",measure:"tupuy",transition:"tikray",increment:"yapay",decrement:"pisiyachiy",default:"ñawpaq_kaq",go:"riy",pushUrl:"url_tanqay",replaceUrl:"url_tikray",copy:"qillqay",pick:"akllay",beep:"waqay",js:"js",async:"mana_suyaspa",render:"rikuchiy",swap:"rantin_tikray",morph:"tikrachiy",settle:"tiyay",append:"qhipaman_yapay",exit:"lluqsiy",install:"churay",breakpoint:"sayachinay",clear:"pichay",close:"wichqay",open:"kichay",select:"akllay",clone:"kikinchay",prepend:"ñawpachiy"},modifiers:{to:"man",from:"manta",into:"ukupi",with:"wan",at:"pi",in:"ukupi",of:"pa",as:"hina",by:"rayku",before:"ñawpaqpi",after:"qhepapi",over:"hawapi",under:"urapi",between:"chawpipi",through:"pasaspa",without:"mana"},events:{click:"ñitiy",dblclick:"iskay_ñitiy",mousedown:"rat_ñitiy",mouseup:"rat_huqariy",mouseenter:"rat_yaykuy",mouseleave:"rat_lluqsiy",mouseover:"rat_hawapi",mouseout:"rat_hawamanta",mousemove:"rat_kuyuy",keydown:"yupana_ñitiy",keyup:"yupana_huqariy",keypress:"yupana_ñitana",focus:"qhaway",blur:"paqariy",change:"tikray",input:"yaykuchiy",submit:"kachay",reset:"qallariy",load:"apakuy",unload:"urmay",resize:"hatun_kay",scroll:"kunray",touchstart:"llamiy_qallay",touchend:"llamiy_tukuy",touchmove:"llamiy_kuyuy",touchcancel:"llamiy_hark_ay"},logical:{when:"maykama",where:"maypi",and:"chaymanta",or:"utaq",not:"mana",is:"kanqa",exists:"tiyan",matches:"tupan",contains:"ukupi_kan",includes:"churasqa",equals:"kikin",has:"kachkan",have:"kachkani",then:"chayqa",else:"mana_chayqa",otherwise:"huk_kaqpi",end:"tukuy",live:"kawsay",changes:"tukurikun"},temporal:{seconds:"sikundukuna",second:"sikundu",milliseconds:"iskay_paqta_sikundukuna",millisecond:"iskay_paqta_sikundu",minutes:"minutukuna",minute:"minutu",hours:"horakuna",hour:"hora",ms:"ms",s:"s",min:"m",h:"h"},values:{true:"cheqaq",false:"llulla",null:"ch_usaq",undefined:"mana_riqsisqa",it:"chay",its:"chaypaq",me:"noqa",my:"noqaq",myself:"noqa killa",you:"qam",your:"qampaq",yourself:"qam killa",element:"raku",target:"punta",detail:"sut_iy",event:"ruway",window:"k_iri",document:"qillqa",body:"kurku",result:"lluqsiy",value:"chanin"},attributes:{class:"ayllu",classes:"ayllukuna",style:"sami",styles:"samikuna",attribute:"kaq",attributes:"kaqkuna",property:"kanay",properties:"kanaykuna"},expressions:{first:"ñawpaq",last:"qhipa",next:"qhipantin",previous:"ñawpaqnin",prev:"ñawpaq",at:"pi",random:"imaymanata",closest:"aswan_kaylla",parent:"mama_tayta",children:"wawakuna",within:"ukupi",no:"mana_kanchu",empty:"ch_usaq",some:"wakin","starts with":"qallarisqa wan","ends with":"tukusqa wan","ignoring case":"hatun-huchuy qillqata-saqiy","sorted by":"niqpi ruwasqa","mapped to":"kay kaqman","split by":"rakisqa","joined by":"huñusqa"}},Ho=xo(Bo,"qu",{allowEnglishFallback:!0}),Uo={commands:{on:"kwenye",tell:"ambia",trigger:"chochea",send:"tuma",take:"chukua",put:"weka",set:"weka",get:"pata",add:"ongeza",remove:"ondoa",toggle:"badilisha",hide:"ficha",show:"onyesha",if:"kama",unless:"isipokuwa",repeat:"rudia",for:"kwa",while:"wakati",until:"hadi",continue:"endelea",break:"vunja",halt:"simama",wait:"ngoja",fetch:"leta",call:"ita",return:"rudi",make:"fanya",log:"andika",throw:"tupa",catch:"shika",measure:"pima",transition:"mpito",increment:"ongeza",decrement:"punguza",default:"msingi",go:"nenda",pushUrl:"sukumaUrl",replaceUrl:"badilishaUrl",copy:"nakili",pick:"chagua",beep:"lia",js:"js",async:"sainkroni",render:"chora",swap:"badilishana",morph:"badilishaUmbo",settle:"tulia",append:"ongezaMwisho",exit:"toka",install:"sakinisha",breakpoint:"nukta-simama",clear:"futa",close:"funga",open:"fungua",select:"chagua",clone:"nakili",prepend:"tanguliza"},modifiers:{to:"kwa",from:"kutoka",into:"ndani",with:"na",at:"katika",in:"ndani",of:"ya",as:"kama",by:"na",before:"kabla",after:"baada",over:"juu",under:"chini",between:"kati",through:"kupitia",without:"bila"},events:{click:"bonyeza",dblclick:"bonyeza_mara_mbili",mousedown:"panya_shuka",mouseup:"panya_juu",mouseenter:"panya_ingia",mouseleave:"panya_toka",mouseover:"panya_juu",mouseout:"panya_nje",mousemove:"panya_sogea",keydown:"kitufe_shuka",keyup:"kitufe_juu",keypress:"kitufe_bonyeza",focus:"zingatia",blur:"poteza_macho",change:"badilisha",input:"ingizo",submit:"wasilisha",reset:"weka_upya",load:"pakia",unload:"shuka",resize:"badilisha_ukubwa",scroll:"sogeza",touchstart:"gusa_anza",touchend:"gusa_mwisho",touchmove:"gusa_sogea",touchcancel:"gusa_ghairi"},logical:{when:"wakati",where:"wapi",and:"na",or:"au",not:"si",is:"ni",exists:"ipo",matches:"inafanana",contains:"ina",includes:"pamoja",equals:"sawa",has:"ana",have:"nina",then:"kisha",else:"sivyo",otherwise:"vinginevyo",end:"mwisho",live:"moja_kwa_moja",changes:"inabadilika"},temporal:{seconds:"sekunde",second:"sekunde",milliseconds:"millisekunde",millisecond:"millisekunde",minutes:"dakika",minute:"dakika",hours:"masaa",hour:"saa",ms:"ms",s:"s",min:"dk",h:"sa"},values:{true:"kweli",false:"uongo",null:"tupu",undefined:"haijafafanuliwa",it:"hiyo",its:"yake",me:"mimi",my:"yangu",myself:"mimi mwenyewe",you:"wewe",your:"yako",yourself:"wewe mwenyewe",element:"kipengele",target:"lengo",detail:"maelezo",event:"tukio",window:"dirisha",document:"hati",body:"mwili",result:"matokeo",value:"thamani"},attributes:{class:"darasa",classes:"madarasa",style:"mtindo",styles:"mitindo",attribute:"sifa",attributes:"sifa",property:"mali",properties:"mali"},expressions:{first:"kwanza",last:"mwisho",next:"ijayo",previous:"iliyopita",prev:"awali",at:"katika",random:"nasibu",closest:"karibu_zaidi",parent:"mzazi",children:"watoto",within:"ndani_ya",no:"hakuna",empty:"tupu",some:"baadhi","starts with":"huanza na","ends with":"huisha na","ignoring case":"puuza herufi kubwa ndogo","sorted by":"kupangwa kwa","mapped to":"kubadilishwa kuwa","split by":"kugawanywa kwa","joined by":"kuunganishwa kwa"}},Wo=xo(Uo,"sw",{allowEnglishFallback:!0}),Jo={commands:{on:"em",tell:"dizer",trigger:"disparar",send:"enviar",take:"pegar",put:"colocar",set:"definir",get:"obter",add:"adicionar",remove:"remover",toggle:"alternar",hide:"esconder",show:"mostrar",if:"se",unless:"a_menos",repeat:"repetir",for:"para",while:"enquanto",until:"até",continue:"continuar",break:"parar",halt:"interromper",wait:"esperar",fetch:"buscar",call:"chamar",return:"retornar",make:"fazer",log:"registrar",throw:"lançar",catch:"capturar",measure:"medir",transition:"transição",increment:"incrementar",decrement:"decrementar",default:"padrão",go:"ir",pushUrl:"pushUrl",replaceUrl:"substituirUrl",copy:"copiar",pick:"escolher",beep:"apitar",js:"js",async:"assíncrono",render:"renderizar",swap:"trocar",morph:"transformar",settle:"estabilizar",append:"anexar",exit:"sair",install:"instalar",breakpoint:"ponto-interrupção",clear:"limpar",close:"fechar",open:"abrir",select:"selecionar",clone:"clonar",prepend:"preceder"},modifiers:{to:"para",from:"de",into:"em",with:"com",at:"em",in:"dentro",of:"de",as:"como",by:"por",before:"antes",after:"depois",over:"sobre",under:"sob",between:"entre",through:"através",without:"sem"},events:{click:"clique",dblclick:"duploClique",mousedown:"mouseBaixo",mouseup:"mouseCima",mouseenter:"mouseEntrar",mouseleave:"mouseSair",mouseover:"mouseSobre",mouseout:"mouseFora",mousemove:"mouseMover",keydown:"teclaBaixo",keyup:"teclaCima",keypress:"teclaPressionar",focus:"foco",blur:"desfoque",change:"mudança",input:"entrada",submit:"envio",reset:"reiniciar",load:"carregar",unload:"descarregar",resize:"redimensionar",scroll:"rolar",touchstart:"toqueInício",touchend:"toqueFim",touchmove:"toqueMover",touchcancel:"toqueCancelar"},logical:{when:"quando",where:"onde",and:"e",or:"ou",not:"não",is:"é",exists:"existe",matches:"corresponde",contains:"contém",includes:"inclui",equals:"igual",has:"tem",have:"tenho",then:"então",else:"senão",otherwise:"caso_contrário",end:"fim",live:"vivo",changes:"muda"},temporal:{seconds:"segundos",second:"segundo",milliseconds:"milissegundos",millisecond:"milissegundo",minutes:"minutos",minute:"minuto",hours:"horas",hour:"hora",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"verdadeiro",false:"falso",null:"nulo",undefined:"indefinido",it:"isso",its:"seu",me:"eu",my:"meu",myself:"eu mesmo",you:"você",your:"seu",yourself:"você mesmo",element:"elemento",target:"alvo",detail:"detalhe",event:"evento",window:"janela",document:"documento",body:"corpo",result:"resultado",value:"valor"},attributes:{class:"classe",classes:"classes",style:"estilo",styles:"estilos",attribute:"atributo",attributes:"atributos",property:"propriedade",properties:"propriedades"},expressions:{first:"primeiro",last:"último",next:"próximo",previous:"anterior",prev:"ant",at:"em",random:"aleatório",closest:"mais_próximo",parent:"pai",children:"filhos",within:"dentro",no:"nenhum",empty:"vazio",some:"algum","starts with":"começa com","ends with":"termina com","ignoring case":"ignorando maiúsculas","sorted by":"ordenado por","mapped to":"mapeado para","split by":"dividido por","joined by":"unido por"}},Ko=xo(Jo,"pt",{allowEnglishFallback:!0}),Go={commands:{on:"su",tell:"dire",trigger:"scatenare",send:"inviare",take:"prendere",put:"mettere",set:"impostare",get:"ottenere",add:"aggiungere",remove:"rimuovere",toggle:"commutare",hide:"nascondere",show:"mostrare",if:"se",unless:"a meno che",repeat:"ripetere",for:"per",while:"mentre",until:"fino",continue:"continuare",break:"interrompere",halt:"fermare",wait:"aspettare",fetch:"recuperare",call:"chiamare",return:"ritornare",make:"fare",log:"registrare",throw:"lanciare",catch:"catturare",measure:"misurare",transition:"transizione",increment:"incrementare",decrement:"decrementare",default:"predefinito",go:"andare",pushUrl:"pushUrl",replaceUrl:"sostituireUrl",copy:"copiare",pick:"scegliere",beep:"beep",js:"js",async:"asincrono",render:"renderizzare",swap:"scambiare",morph:"trasformare",settle:"stabilizzare",append:"aggiungere",exit:"uscire",install:"installare",breakpoint:"punto-interruzione",clear:"cancellare",close:"chiudere",open:"aprire",select:"selezionare",clone:"clonare",prepend:"anteporre"},modifiers:{to:"a",from:"da",into:"in",with:"con",at:"a",in:"in",of:"di",as:"come",by:"per",before:"prima",after:"dopo",over:"sopra",under:"sotto",between:"tra",through:"attraverso",without:"senza"},events:{click:"clic",dblclick:"doppioclic",mousedown:"mousegiù",mouseup:"mousesu",mouseenter:"mouseentra",mouseleave:"mouseesce",mouseover:"mousesopra",mouseout:"mousefuori",mousemove:"mousemuovi",keydown:"tastogiù",keyup:"tastosu",keypress:"tastopremi",focus:"fuoco",blur:"sfuocatura",change:"cambio",input:"input",submit:"invio",reset:"reset",load:"carica",unload:"scarica",resize:"ridimensiona",scroll:"scorrimento",touchstart:"toccoinizia",touchend:"toccofine",touchmove:"toccomuovi",touchcancel:"toccoannulla"},logical:{when:"quando",where:"dove",and:"e",or:"o",not:"non",is:"è",exists:"esiste",matches:"corrisponde",contains:"contiene",includes:"include",equals:"uguale",has:"ha",have:"ho",then:"allora",else:"altrimenti",otherwise:"altrimenti",end:"fine",live:"vivo",changes:"cambia"},temporal:{seconds:"secondi",second:"secondo",milliseconds:"millisecondi",millisecond:"millisecondo",minutes:"minuti",minute:"minuto",hours:"ore",hour:"ora",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"vero",false:"falso",null:"nullo",undefined:"indefinito",it:"esso",its:"suo",me:"io",my:"mio",you:"tu",your:"tuo",yourself:"te stesso",myself:"me stesso",element:"elemento",target:"obiettivo",detail:"dettaglio",event:"evento",window:"finestra",document:"documento",body:"corpo",result:"risultato",value:"valore"},attributes:{class:"classe",classes:"classi",style:"stile",styles:"stili",attribute:"attributo",attributes:"attributi",property:"proprietà",properties:"proprietà"},expressions:{first:"primo",last:"ultimo",next:"prossimo",previous:"precedente",prev:"prec",at:"a",random:"casuale",closest:"piùvicino",parent:"genitore",children:"figli",within:"dentro",no:"nessun",empty:"vuoto",some:"qualche","starts with":"inizia con","ends with":"finisce con","ignoring case":"ignorando maiuscole","sorted by":"ordinato per","mapped to":"trasformato in","split by":"diviso per","joined by":"unito per"}};xo(Go,"it",{allowEnglishFallback:!0});var Zo={commands:{on:"khi",tell:"nói với",trigger:"kích hoạt",send:"gửi",take:"lấy",put:"đặt",set:"gán",get:"lấy giá trị",add:"thêm",remove:"xóa",toggle:"chuyển đổi",hide:"ẩn",show:"hiển thị",if:"nếu",unless:"trừ khi",repeat:"lặp lại",for:"với mỗi",while:"trong khi",until:"cho đến khi",continue:"tiếp tục",break:"dừng",halt:"dừng lại",wait:"chờ",fetch:"tải",call:"gọi",return:"trả về",make:"tạo",log:"in ra",throw:"ném",catch:"bắt",measure:"đo lường",transition:"chuyển tiếp",increment:"tăng",decrement:"giảm",default:"mặc định",go:"đi đến",pushUrl:"pushUrl",replaceUrl:"thayThếUrl",copy:"sao chép",pick:"chọn",beep:"beep",js:"js",async:"bất đồng bộ",render:"hiển thị",swap:"hoán đổi",morph:"biến đổi",settle:"ổn định",append:"nối",exit:"thoát",focus:"tập trung",blur:"mất tập trung",init:"khởi tạo",behavior:"hành vi",install:"cài đặt",clone:"sao chép",prepend:"thêm đầu",else:"không thì",breakpoint:"điểm-dừng",clear:"xóa",close:"đóng",open:"mở",select:"chọn"},modifiers:{into:"vào",before:"trước",after:"sau",then:"rồi",end:"kết thúc",from:"từ",to:"đến",with:"với",as:"như",by:"bởi",on:"trên",in:"trong",at:"tại",of:"của",between:"giữa",the:"",times:"lần"},events:{click:"nhấp",dblclick:"nhấp đúp",input:"nhập",change:"thay đổi",submit:"gửi",keydown:"phím xuống",keyup:"phím lên",keypress:"nhấn phím",mouseover:"chuột vào",mouseout:"chuột ra",mouseenter:"chuột vào",mouseleave:"chuột rời",focus:"tập trung",blur:"mất tập trung",reset:"đặt-lại",load:"tải",scroll:"cuộn",resize:"đổi kích thước"},logical:{when:"khi",where:"ở_đâu",and:"và",or:"hoặc",not:"không",is:"là",equals:"bằng",contains:"chứa",matches:"khớp",exists:"tồn tại",has:"có",have:"có",empty:"trống",true:"đúng",false:"sai",null:"rỗng",else:"không thì",end:"kết thúc",then:"rồi",live:"trực tiếp",changes:"thay đổi"},temporal:{now:"bây giờ",today:"hôm nay",tomorrow:"ngày mai",yesterday:"hôm qua",always:"luôn luôn",never:"không bao giờ",sometimes:"đôi khi",once:"một lần",twice:"hai lần",forever:"mãi mãi"},values:{true:"đúng",false:"sai",null:"rỗng",undefined:"không xác định",none:"không có",all:"tất cả",any:"bất kỳ",some:"một số",each:"mỗi",every:"tất cả",body:"body",event:"sự kiện",it:"nó",its:"của nó",me:"tôi",my:"của tôi",result:"kết quả",target:"mục tiêu",you:"bạn",your:"của bạn"},attributes:{id:"id",class:"lớp",style:"kiểu",value:"giá trị",text:"văn bản",html:"html",src:"nguồn",href:"liên kết",disabled:"vô hiệu",hidden:"ẩn",checked:"được chọn",selected:"được chọn"},expressions:{me:"tôi",my:"của tôi",it:"nó",its:"của nó",result:"kết quả",event:"sự kiện",target:"mục tiêu",first:"đầu tiên",last:"cuối cùng",next:"tiếp theo",previous:"trước đó",parent:"cha",children:"con",closest:"gần nhất",empty:"làm-rỗng","starts with":"bắt đầu bằng","ends with":"kết thúc bằng","ignoring case":"không phân biệt hoa thường","sorted by":"sắp xếp theo","mapped to":"ánh xạ thành","split by":"tách bởi","joined by":"nối bởi"}};xo(Zo,"vi",{allowEnglishFallback:!0});var Xo={commands:{on:"gdy",tell:"powiedz",trigger:"wywołaj",send:"wyślij",take:"weź",put:"umieść",set:"ustaw",get:"pobierz",add:"dodaj",remove:"usuń",toggle:"przełącz",hide:"ukryj",show:"pokaż",if:"jeśli",unless:"chyba",repeat:"powtórz",for:"dla",while:"dopóki",until:"aż",continue:"kontynuuj",break:"przerwij",halt:"zatrzymaj",wait:"czekaj",fetch:"pobierz",call:"wywołaj",return:"zwróć",make:"utwórz",log:"loguj",throw:"rzuć",catch:"złap",measure:"zmierz",transition:"animuj",increment:"zwiększ",decrement:"zmniejsz",default:"domyślnie",go:"idź",pushUrl:"dodajUrl",replaceUrl:"zamieńUrl",copy:"kopiuj",pick:"wybierz",beep:"sygnał",js:"js",async:"async",render:"renderuj",swap:"zamień",morph:"przekształć",settle:"ustabilizuj",append:"dołącz",exit:"wyjdź",install:"zainstaluj",breakpoint:"punkt-przerwania",clear:"wyczyść",close:"zamknij",open:"otwórz",select:"wybierz",clone:"sklonuj",prepend:"poprzedź"},modifiers:{to:"do",from:"z",into:"do",with:"z",at:"przy",in:"w",of:"z",as:"jako",by:"przez",before:"przed",after:"po",over:"nad",under:"pod",between:"między",through:"przez",without:"bez"},events:{click:"kliknięcie",dblclick:"podwójnekliknięcie",mousedown:"myszdół",mouseup:"myszgóra",mouseenter:"myszwejście",mouseleave:"myszwyjście",mouseover:"mysznad",mouseout:"myszpoza",mousemove:"myszruch",keydown:"klawiszdół",keyup:"klawiszgóra",keypress:"klawisznaciśnięcie",focus:"fokus",blur:"rozmycie",change:"zmiana",input:"wejście",submit:"wyślij",reset:"resetuj",load:"załaduj",unload:"wyładuj",resize:"zmieńrozmiar",scroll:"przewiń",touchstart:"dotykstart",touchend:"dotykkoniec",touchmove:"dotykruch",touchcancel:"dotykanuluj"},logical:{when:"kiedy",where:"gdzie",and:"i",or:"lub",not:"nie",is:"jest",exists:"istnieje",matches:"pasuje",contains:"zawiera",includes:"obejmuje",equals:"równa się",has:"ma",have:"mam",then:"wtedy",else:"inaczej",otherwise:"wpp",end:"koniec",live:"żywy",changes:"zmienia"},temporal:{seconds:"sekundy",second:"sekunda",milliseconds:"milisekundy",millisecond:"milisekunda",minutes:"minuty",minute:"minuta",hours:"godziny",hour:"godzina",ms:"ms",s:"s",min:"min",h:"godz"},values:{true:"prawda",false:"fałsz",null:"null",undefined:"niezdefiniowane",it:"to",its:"jego",me:"ja",my:"mój",you:"ty",your:"twój",yourself:"ty sam",myself:"ja sam",element:"element",target:"cel",detail:"szczegół",event:"zdarzenie",window:"okno",document:"dokument",body:"body",result:"wynik",value:"wartość"},attributes:{class:"klasa",classes:"klasy",style:"styl",styles:"style",attribute:"atrybut",attributes:"atrybuty",property:"właściwość",properties:"właściwości"},expressions:{first:"pierwszy",last:"ostatni",next:"następny",previous:"poprzedni",prev:"poprz",at:"przy",random:"losowy",closest:"najbliższy",parent:"rodzic",children:"dzieci",within:"wewnątrz",no:"brak",empty:"pusty",some:"jakiś","starts with":"zaczyna się od","ends with":"kończy się na","ignoring case":"ignorując wielkość liter","sorted by":"sortowane według","mapped to":"przekształcone na","split by":"podzielone przez","joined by":"połączone przez"}};xo(Xo,"pl",{allowEnglishFallback:!0});var Yo={commands:{on:"при",tell:"сказать",trigger:"вызвать",send:"отправить",take:"взять",put:"положить",set:"установить",get:"получить",add:"добавить",remove:"удалить",toggle:"переключить",hide:"скрыть",show:"показать",if:"если",unless:"если_не",repeat:"повторить",for:"для",while:"пока",until:"до",continue:"продолжить",break:"прервать",halt:"остановить",wait:"ждать",fetch:"загрузить",call:"вызвать",return:"вернуть",make:"создать",log:"записать",throw:"бросить",catch:"поймать",measure:"измерить",transition:"анимировать",increment:"увеличить",decrement:"уменьшить",default:"по_умолчанию",go:"перейти",pushUrl:"добавить_url",replaceUrl:"заменить_url",copy:"копировать",pick:"выбрать",beep:"звук",js:"js",async:"асинхронно",render:"отобразить",swap:"поменять",morph:"трансформировать",settle:"стабилизировать",append:"добавить_в_конец",exit:"выйти",else:"иначе",install:"установить",init:"инициализировать",behavior:"поведение",focus:"сфокусировать",blur:"размыть",clone:"клонировать",prepend:"добавить_в_начало",breakpoint:"точка-останова",clear:"очистить",close:"закрыть",open:"открыть",select:"выбрать"},modifiers:{to:"к",from:"из",into:"в",with:"с",at:"у",in:"в",of:"из",as:"как",by:"на",before:"до",after:"после",over:"над",under:"под",between:"между",through:"через",without:"без",on:"на"},events:{click:"клик",dblclick:"двойной_клик",mousedown:"мышь_вниз",mouseup:"мышь_вверх",mouseenter:"мышь_вход",mouseleave:"мышь_выход",mouseover:"наведение",mouseout:"уход",mousemove:"движение_мыши",keydown:"клавиша_вниз",keyup:"клавиша_вверх",keypress:"нажатие_клавиши",focus:"фокус",blur:"потеря_фокуса",change:"изменение",input:"ввод",submit:"отправка",reset:"сброс",load:"загрузка",unload:"выгрузка",resize:"изменение_размера",scroll:"прокрутка",touchstart:"касание_начало",touchend:"касание_конец",touchmove:"касание_движение",touchcancel:"касание_отмена"},logical:{when:"когда",where:"где",and:"и",or:"или",not:"не",is:"есть",exists:"существует",matches:"соответствует",contains:"содержит",includes:"включает",equals:"равно",then:"затем",else:"иначе",otherwise:"в_противном_случае",end:"конец",live:"живой",changes:"изменяется",has:"имеет",have:"имею",isNot:"не_есть",empty:"пустой"},temporal:{seconds:"секунд",second:"секунда",milliseconds:"миллисекунд",millisecond:"миллисекунда",minutes:"минут",minute:"минута",hours:"часов",hour:"час",ms:"мс",s:"с",min:"мин",h:"ч",forever:"всегда",once:"однажды",every:"каждый",until:"до"},values:{true:"истина",false:"ложь",null:"ничего",undefined:"неопределено",it:"это",its:"его",me:"я",my:"мой",you:"ты",your:"твой",yourself:"сам",myself:"я_сам",element:"элемент",target:"цель",detail:"детали",event:"событие",window:"окно",document:"документ",body:"тело",result:"результат",value:"значение",first:"первый",last:"последний",next:"следующий",previous:"предыдущий",closest:"ближайший",parent:"родитель"},attributes:{class:"класс",classes:"классы",style:"стиль",styles:"стили",attribute:"атрибут",attributes:"атрибуты",property:"свойство",properties:"свойства",disabled:"отключено",hidden:"скрыто",checked:"отмечено",selected:"выбрано",readonly:"только_чтение",required:"обязательно",text:"текст",html:"html"},expressions:{first:"первый",last:"последний",next:"следующий",previous:"предыдущий",prev:"пред",at:"в",random:"случайный",closest:"ближайший",parent:"родитель",children:"дети",within:"внутри",no:"нет",empty:"пустой",some:"некоторые","starts with":"начинается_с","ends with":"заканчивается_на","ignoring case":"без_учёта_регистра","sorted by":"сортировано_по","mapped to":"преобразовано_в","split by":"разделено_по","joined by":"объединено_через"}};xo(Yo,"ru",{allowEnglishFallback:!0});var Qo={commands:{on:"при",tell:"сказати",trigger:"викликати",send:"надіслати",take:"взяти",put:"покласти",set:"встановити",get:"отримати",add:"додати",remove:"видалити",toggle:"перемкнути",hide:"сховати",show:"показати",if:"якщо",unless:"якщо_не",repeat:"повторити",for:"для",while:"поки",until:"до",continue:"продовжити",break:"перервати",halt:"зупинити",wait:"чекати",fetch:"завантажити",call:"викликати",return:"повернути",make:"створити",log:"записати",throw:"кинути",catch:"зловити",measure:"виміряти",transition:"анімувати",increment:"збільшити",decrement:"зменшити",default:"за_замовчуванням",go:"перейти",pushUrl:"додати_url",replaceUrl:"замінити_url",copy:"копіювати",pick:"вибрати",beep:"звук",js:"js",async:"асинхронно",render:"відобразити",swap:"поміняти",morph:"трансформувати",settle:"стабілізувати",append:"додати_в_кінець",exit:"вийти",else:"інакше",install:"встановити",init:"ініціалізувати",behavior:"поведінка",focus:"сфокусувати",blur:"розфокусувати",clone:"клонувати",prepend:"додати_на_початок",breakpoint:"точка-зупинки",clear:"очистити",close:"закрити",open:"відкрити",select:"вибрати"},modifiers:{to:"до",from:"з",into:"в",with:"з",at:"в",in:"у",of:"з",as:"як",by:"на",before:"до",after:"після",over:"над",under:"під",between:"між",through:"через",without:"без",on:"на"},events:{click:"клік",dblclick:"подвійний_клік",mousedown:"миша_вниз",mouseup:"миша_вгору",mouseenter:"миша_вхід",mouseleave:"миша_вихід",mouseover:"наведення",mouseout:"відведення",mousemove:"рух_миші",keydown:"клавіша_вниз",keyup:"клавіша_вгору",keypress:"натискання_клавіші",focus:"фокус",blur:"розфокус",change:"зміна",input:"введення",submit:"надсилання",reset:"скидання",load:"завантаження",unload:"вивантаження",resize:"зміна_розміру",scroll:"прокрутка",touchstart:"дотик_початок",touchend:"дотик_кінець",touchmove:"дотик_рух",touchcancel:"дотик_скасування"},logical:{when:"коли",where:"де",and:"і",or:"або",not:"не",is:"є",exists:"існує",matches:"відповідає",contains:"містить",includes:"включає",equals:"дорівнює",then:"тоді",else:"інакше",otherwise:"в_іншому_випадку",end:"кінець",live:"живий",changes:"змінюється",has:"має",have:"маю",isNot:"не_є",empty:"порожній"},temporal:{seconds:"секунд",second:"секунда",milliseconds:"мілісекунд",millisecond:"мілісекунда",minutes:"хвилин",minute:"хвилина",hours:"годин",hour:"година",ms:"мс",s:"с",min:"хв",h:"год",forever:"завжди",once:"один_раз",every:"кожний",until:"до"},values:{true:"істина",false:"хибність",null:"нічого",undefined:"невизначено",it:"це",its:"його",me:"я",my:"мій",you:"ти",your:"твій",yourself:"сам",myself:"я_сам",element:"елемент",target:"ціль",detail:"деталі",event:"подія",window:"вікно",document:"документ",body:"тіло",result:"результат",value:"значення",first:"перший",last:"останній",next:"наступний",previous:"попередній",closest:"найближчий",parent:"батьківський"},attributes:{class:"клас",classes:"класи",style:"стиль",styles:"стилі",attribute:"атрибут",attributes:"атрибути",property:"властивість",properties:"властивості",disabled:"вимкнено",hidden:"приховано",checked:"позначено",selected:"вибрано",readonly:"лише_читання",required:"обов'язково",text:"текст",html:"html"},expressions:{first:"перший",last:"останній",next:"наступний",previous:"попередній",prev:"попер",at:"в",random:"випадковий",closest:"найближчий",parent:"батьківський",children:"діти",within:"всередині",no:"ні",empty:"порожній",some:"деякі","starts with":"починається_з","ends with":"закінчується_на","ignoring case":"без_урахування_регістру","sorted by":"відсортовано_за","mapped to":"перетворено_на","split by":"розділено_за","joined by":"об'єднано_через"}};xo(Qo,"uk",{allowEnglishFallback:!0});var el={commands:{on:"पर",tell:"बताएं",trigger:"ट्रिगर",send:"भेजें",take:"लें",put:"रखें",set:"सेट",get:"प्राप्त",add:"जोड़ें",remove:"हटाएं",toggle:"टॉगल",hide:"छिपाएं",show:"दिखाएं",if:"अगर",unless:"जब_तक_नहीं",repeat:"दोहराएं",for:"के_लिए",while:"जब_तक",until:"तक",continue:"जारी",break:"रोकें",halt:"रोकें",wait:"प्रतीक्षा",fetch:"लाएं",call:"कॉल",return:"लौटाएं",make:"बनाएं",log:"लॉग",throw:"फेंकें",catch:"पकड़ें",measure:"मापें",transition:"संक्रमण",increment:"बढ़ाएं",decrement:"घटाएं",default:"डिफ़ॉल्ट",go:"जाएं",pushUrl:"url_जोड़ें",replaceUrl:"url_बदलें",copy:"कॉपी",pick:"चुनें",beep:"बीप",js:"जेएस",async:"असिंक",render:"रेंडर",swap:"बदलें",morph:"रूपांतर",settle:"स्थिर",append:"जोड़ें_अंत",exit:"बाहर",else:"वरना",install:"इंस्टॉल",init:"प्रारंभ",behavior:"व्यवहार",focus:"फोकस",blur:"धुंधला",clone:"कॉपी",prepend:"जोड़ें_शुरू",breakpoint:"ब्रेकप्वाइंट",clear:"साफ़-करें",close:"बंद-करें",open:"खोलें",select:"चुनें"},modifiers:{to:"को",from:"से",into:"में",with:"के_साथ",at:"पर",in:"में",of:"का",as:"के_रूप_में",by:"द्वारा",before:"से_पहले",after:"के_बाद",over:"के_ऊपर",under:"के_नीचे",between:"के_बीच",through:"के_माध्यम_से",without:"के_बिना",on:"पर"},events:{click:"क्लिक",dblclick:"डबल_क्लिक",mousedown:"माउस_नीचे",mouseup:"माउस_ऊपर",mouseenter:"माउस_प्रवेश",mouseleave:"माउस_बाहर",mouseover:"माउस_ओवर",mouseout:"माउस_आउट",mousemove:"माउस_मूव",keydown:"की_नीचे",keyup:"की_ऊपर",keypress:"की_प्रेस",focus:"फोकस",blur:"धुंधला",change:"परिवर्तन",input:"इनपुट",submit:"जमा",reset:"रीसेट",load:"लोड",unload:"अनलोड",resize:"आकार_बदलें",scroll:"स्क्रॉल",touchstart:"टच_शुरू",touchend:"टच_समाप्त",touchmove:"टच_मूव",touchcancel:"टच_रद्द"},logical:{when:"जब",where:"कहाँ",and:"और",or:"या",not:"नहीं",is:"है",exists:"मौजूद",matches:"मेल_खाता",contains:"शामिल",includes:"में_है",equals:"बराबर",then:"फिर",else:"वरना",otherwise:"अन्यथा",end:"समाप्त",live:"लाइव",changes:"बदलने पर",has:"है",have:"है",isNot:"नहीं_है",empty:"खाली"},temporal:{seconds:"सेकंड",second:"सेकंड",milliseconds:"मिलीसेकंड",millisecond:"मिलीसेकंड",minutes:"मिनट",minute:"मिनट",hours:"घंटे",hour:"घंटा",ms:"मिसे",s:"से",min:"मि",h:"घं",forever:"हमेशा",once:"एक_बार",every:"हर",until:"तक"},values:{true:"सच",false:"झूठ",null:"खाली",undefined:"अपरिभाषित",it:"यह",its:"इसका",me:"मैं",my:"मेरा",you:"आप",your:"आपका",yourself:"स्वयं",myself:"मैं_स्वयं",element:"तत्व",target:"लक्ष्य",detail:"विवरण",event:"घटना",window:"विंडो",document:"दस्तावेज़",body:"बॉडी",result:"परिणाम",value:"मान",first:"पहला",last:"अंतिम",next:"अगला",previous:"पिछला",closest:"निकटतम",parent:"मूल"},attributes:{class:"क्लास",classes:"क्लासेस",style:"स्टाइल",styles:"स्टाइल्स",attribute:"गुण",attributes:"गुण",property:"संपत्ति",properties:"संपत्तियाँ",disabled:"अक्षम",hidden:"छिपा",checked:"चेक",selected:"चयनित",readonly:"केवल_पढ़ने",required:"आवश्यक",text:"पाठ",html:"html"},expressions:{first:"पहला",last:"अंतिम",next:"अगला",previous:"पिछला",prev:"पिछ",at:"पर",random:"यादृच्छिक",closest:"निकटतम",parent:"मूल",children:"बच्चे",within:"के_अंदर",no:"नहीं",empty:"खाली",some:"कुछ","starts with":"से_शुरू","ends with":"पर_समाप्त","ignoring case":"केस_अनदेखा","sorted by":"द्वारा_क्रमबद्ध","mapped to":"में_परिवर्तित","split by":"द्वारा_विभाजित","joined by":"द्वारा_जुड़ा"}};xo(el,"hi",{allowEnglishFallback:!0});var tl={commands:{on:"তে",toggle:"টগল",add:"যোগ",remove:"সরান",set:"সেট",get:"পান",put:"রাখুন",take:"নিন",show:"দেখান",hide:"লুকান",increment:"বৃদ্ধি",decrement:"হ্রাস",if:"যদি",else:"নতুবা",repeat:"পুনরাবৃত্তি",for:"জন্য",while:"যতক্ষণ",wait:"অপেক্ষা",fetch:"আনুন",call:"কল",return:"ফিরুন",log:"লগ",trigger:"ট্রিগার",send:"পাঠান",go:"যান",halt:"থামুন",throw:"নিক্ষেপ",continue:"চালিয়ে যান",make:"তৈরি করুন",append:"শেষে যোগ",prepend:"শুরুতে যোগ",focus:"ফোকাস",blur:"ঝাপসা",transition:"সংক্রমণ",settle:"স্থির",measure:"মাপুন",async:"অ্যাসিঙ্ক",tell:"বলুন",default:"ডিফল্ট",init:"শুরু",behavior:"আচরণ",install:"ইনস্টল",clone:"কপি",swap:"বদল",morph:"রূপান্তর",beep:"বীপ",break:"ভাঙুন",copy:"কপি",exit:"বের",js:"জেএস",pick:"বাছুন",render:"রেন্ডার",until:"পর্যন্ত",breakpoint:"ব্রেকপয়েন্ট",clear:"পরিষ্কার",close:"বন্ধ",open:"খুলুন",select:"নির্বাচন"},modifiers:{to:"কে",from:"থেকে",into:"তে",on:"তে",with:"সাথে",by:"দ্বারা",as:"হিসাবে",before:"আগে",after:"পরে",at:"এ",in:"এ",over:"উপর",between:"মধ্যে",then:"তারপর",and:"এবং",end:"শেষ",until:"পর্যন্ত",of:"র"},events:{click:"ক্লিক",change:"পরিবর্তন",input:"ইনপুট",submit:"জমা",load:"লোড",focus:"ফোকাস",blur:"ঝাপসা",reset:"রিসেট",keydown:"কি-ডাউন",keyup:"কি-আপ",mouseover:"মাউস-ওভার",mouseout:"মাউস-আউট",scroll:"স্ক্রোল",resize:"রিসাইজ",every:"প্রতি"},logical:{if:"যদি",when:"যখন",where:"কোথায়",else:"নতুবা",not:"না",and:"এবং",or:"অথবা",is:"হয়",exists:"আছে",has:"আছে",have:"আছি",empty:"খালি",true:"সত্য",false:"মিথ্যা",null:"শূন্য",undefined:"অনির্ধারিত",end:"শেষ",then:"তারপর",live:"লাইভ",changes:"পরিবর্তিত হলে"},temporal:{now:"এখন",seconds:"সেকেন্ড",milliseconds:"মিলিসেকেন্ড",minutes:"মিনিট",hours:"ঘণ্টা",forever:"চিরকাল",times:"বার",s:"সে",ms:"মিসে"},values:{me:"আমি",my:"আমার",it:"এটি",its:"এর",result:"ফলাফল",event:"ঘটনা",target:"লক্ষ্য",body:"বডি",you:"আপনি",your:"তোমার"},attributes:{class:"শ্রেণি",id:"আইডি",style:"শৈলী",value:"মান",text:"পাঠ্য",html:"এইচটিএমএল",disabled:"অক্ষম",checked:"চেক করা"},expressions:{first:"প্রথম",last:"শেষ",next:"পরবর্তী",previous:"আগের",closest:"নিকটতম",parent:"মূল",children:"সন্তান",random:"এলোমেলো",length:"দৈর্ঘ্য",index:"সূচক",empty:"খালি-করুন","starts with":"দিয়ে_শুরু","ends with":"দিয়ে_শেষ","ignoring case":"কেস_উপেক্ষা","sorted by":"দ্বারা_সাজানো","mapped to":"তে_রূপান্তরিত","split by":"দ্বারা_বিভক্ত","joined by":"দ্বারা_যুক্ত"}};xo(tl,"bn",{allowEnglishFallback:!0});var rl={commands:{on:"เมื่อ",toggle:"สลับ",add:"เพิ่ม",remove:"ลบ",set:"ตั้ง",get:"รับค่า",put:"ใส่",take:"รับ",show:"แสดง",hide:"ซ่อน",increment:"เพิ่มค่า",decrement:"ลดค่า",if:"ถ้า",else:"ไม่งั้น",repeat:"ทำซ้ำ",for:"สำหรับ",while:"ในขณะที่",wait:"รอ",fetch:"ดึงข้อมูล",call:"เรียก",return:"คืนค่า",log:"บันทึก",trigger:"ทริกเกอร์",send:"ส่ง",go:"ไป",halt:"หยุด",throw:"โยน",continue:"ต่อไป",make:"สร้าง",append:"เพิ่มท้าย",prepend:"เพิ่มหน้า",focus:"โฟกัส",blur:"เบลอ",transition:"เปลี่ยน",settle:"คงที่",measure:"วัด",async:"อะซิงค์",tell:"บอก",default:"ค่าเริ่มต้น",init:"เริ่มต้น",behavior:"พฤติกรรม",install:"ติดตั้ง",clone:"คัดลอก",swap:"สลับที่",morph:"แปลงร่าง",beep:"บี๊บ",break:"ขัดจังหวะ",copy:"คัดลอก",exit:"ออก",js:"เจเอส",pick:"เลือก",render:"แสดงผล",until:"จนถึง",breakpoint:"จุดพัก",clear:"เคลียร์",close:"ปิด",open:"เปิด",select:"เลือก"},modifiers:{to:"ไปยัง",from:"จาก",into:"ใน",on:"เมื่อ",with:"ด้วย",by:"โดย",as:"เป็น",before:"ก่อน",after:"หลัง",at:"ที่",in:"ใน",over:"เหนือ",between:"ระหว่าง",then:"แล้ว",and:"และ",end:"จบ",until:"จนถึง",of:"ของ"},events:{click:"คลิก",change:"เปลี่ยนแปลง",input:"อินพุต",submit:"ส่ง",load:"โหลด",focus:"โฟกัส",blur:"เบลอ",reset:"รีเซ็ต",keydown:"กดคีย์",keyup:"ปล่อยคีย์",mouseover:"เมาส์เข้า",mouseout:"เมาส์ออก",scroll:"เลื่อน",resize:"ปรับขนาด",every:"ทุก"},logical:{if:"ถ้า",when:"เมื่อ",where:"ที่ไหน",else:"ไม่งั้น",not:"ไม่",and:"และ",or:"หรือ",is:"เป็น",exists:"มีอยู่",has:"มี",have:"มี",empty:"ว่าง",true:"จริง",false:"เท็จ",null:"ว่าง",undefined:"ไม่กำหนด",end:"จบ",then:"แล้ว",live:"สด",changes:"เปลี่ยน"},temporal:{now:"ตอนนี้",seconds:"วินาที",milliseconds:"มิลลิวินาที",minutes:"นาที",hours:"ชั่วโมง",forever:"ตลอดไป",times:"ครั้ง",s:"วิ",ms:"มว"},values:{me:"ฉัน",my:"ของฉัน",it:"มัน",its:"ของมัน",result:"ผลลัพธ์",event:"เหตุการณ์",target:"เป้าหมาย",body:"บอดี้",you:"คุณ",your:"ของคุณ"},attributes:{class:"คลาส",id:"ไอดี",style:"สไตล์",value:"ค่า",text:"ข้อความ",html:"เอชทีเอ็มแอล",disabled:"ปิดใช้งาน",checked:"เลือกแล้ว"},expressions:{first:"แรก",last:"สุดท้าย",next:"ถัดไป",previous:"ก่อนหน้า",closest:"ใกล้สุด",parent:"ต้นทาง",children:"ลูก",random:"สุ่ม",length:"ความยาว",index:"ดัชนี",empty:"ล้าง","starts with":"ขึ้นต้นด้วย","ends with":"ลงท้ายด้วย","ignoring case":"ไม่สนตัวพิมพ์","sorted by":"เรียงตาม","mapped to":"แปลงเป็น","split by":"แยกด้วย","joined by":"รวมด้วย"}};xo(rl,"th",{allowEnglishFallback:!0});var nl={commands:{on:"apabila",tell:"beritahu",trigger:"cetuskan",send:"hantar",take:"ambil",put:"letak",set:"tetapkan",get:"dapatkan",add:"tambah",remove:"buang",toggle:"togol",hide:"sembunyi",show:"tunjuk",if:"jika",unless:"kecuali",repeat:"ulang",for:"untuk",while:"selagi",until:"sehingga",continue:"teruskan",break:"henti",halt:"henti",wait:"tunggu",fetch:"ambil_dari",call:"panggil",return:"pulang",make:"buat",log:"catat",throw:"lempar",catch:"tangkap",measure:"ukur",transition:"peralihan",increment:"tambah_satu",decrement:"kurang_satu",default:"lalai",go:"pergi",pushUrl:"tolak_url",replaceUrl:"ganti_url",copy:"salin",pick:"pilih",beep:"bunyi",js:"js",async:"tak_segerak",render:"papar",swap:"tukar_tempat",morph:"ubah_bentuk",settle:"selesai",append:"tambah_hujung",prepend:"tambah_mula",exit:"keluar",else:"kalau_tidak",focus:"fokus",blur:"kabur",install:"pasang",behavior:"kelakuan",init:"mula",clone:"klon",breakpoint:"titik-henti",clear:"padam",close:"tutup",open:"buka",select:"pilih"},modifiers:{to:"ke",from:"dari",into:"ke_dalam",with:"dengan",at:"di",in:"dalam",of:"daripada",as:"sebagai",by:"oleh",before:"sebelum",after:"selepas",over:"atas",under:"bawah",between:"antara",through:"melalui",without:"tanpa",on:"pada",then:"kemudian",and:"dan",end:"tamat",until:"sehingga"},events:{click:"click",dblclick:"dblclick",mousedown:"mousedown",mouseup:"mouseup",mouseenter:"mouseenter",mouseleave:"mouseleave",mouseover:"mouseover",mouseout:"mouseout",mousemove:"mousemove",keydown:"keydown",keyup:"keyup",keypress:"keypress",focus:"focus",blur:"blur",change:"change",input:"input",submit:"submit",reset:"reset",load:"load",unload:"unload",resize:"resize",scroll:"scroll",touchstart:"touchstart",touchend:"touchend",touchmove:"touchmove",touchcancel:"touchcancel",every:"setiap"},logical:{when:"apabila",where:"di_mana",and:"dan",or:"atau",not:"bukan",is:"adalah",exists:"wujud",matches:"sepadan",contains:"mengandungi",includes:"termasuk",equals:"sama",has:"ada",have:"ada",then:"kemudian",else:"kalau_tidak",otherwise:"jika_tidak",end:"tamat",live:"langsung",changes:"berubah",if:"jika",empty:"kosong",true:"benar",false:"salah",null:"null",undefined:"tidak_ditakrifkan"},temporal:{seconds:"saat",second:"saat",milliseconds:"milisaat",millisecond:"milisaat",minutes:"minit",minute:"minit",hours:"jam",hour:"jam",ms:"ms",s:"s",min:"min",h:"j",now:"sekarang",forever:"selamanya",times:"kali"},values:{true:"benar",false:"salah",null:"null",undefined:"tidak_ditakrifkan",it:"ia",its:"nya",me:"saya",my:"saya_punya",myself:"diri_saya",you:"kamu",your:"kamu_punya",yourself:"diri_kamu",element:"elemen",target:"sasaran",detail:"perincian",event:"peristiwa",window:"tetingkap",document:"dokumen",body:"badan",result:"hasil",value:"nilai"},attributes:{class:"kelas",classes:"kelas_kelas",style:"gaya",styles:"gaya_gaya",attribute:"atribut",attributes:"atribut_atribut",property:"sifat",properties:"sifat_sifat",id:"id",value:"nilai",text:"teks",html:"html",disabled:"dilumpuhkan",checked:"ditanda"},expressions:{first:"pertama",last:"terakhir",next:"seterusnya",previous:"sebelumnya",prev:"sebelum",at:"di",random:"rawak",closest:"terdekat",parent:"induk",children:"anak_anak",within:"dalam",no:"tiada",empty:"kosong",some:"beberapa","starts with":"bermula_dengan","ends with":"berakhir_dengan","ignoring case":"abaikan_huruf_besar_kecil","sorted by":"disusun_mengikut","mapped to":"dipetakan_ke","split by":"dipecah_oleh","joined by":"digabung_oleh",length:"panjang",index:"indeks"}};xo(nl,"ms",{allowEnglishFallback:!0});var sl={commands:{on:"kapag",tell:"sabihin",trigger:"palitawin",send:"ipadala",take:"kunin",put:"ilagay",set:"itakda",get:"kuhanin",add:"idagdag",remove:"alisin",toggle:"palitan",hide:"itago",show:"ipakita",if:"kung",unless:"maliban_kung",repeat:"ulitin",for:"para_sa",while:"habang",until:"hanggang",continue:"magpatuloy",break:"itigil",halt:"huminto",wait:"maghintay",fetch:"kuhanin_mula",call:"tawagin",return:"ibalik",make:"gumawa",log:"itala",throw:"ihagis",catch:"hulihin",measure:"sukatin",transition:"baguhin",increment:"dagdagan",decrement:"bawasan",default:"pamantayan",go:"pumunta",pushUrl:"itulak_url",replaceUrl:"palitan_url",copy:"kopyahin",pick:"pumili",beep:"tunog",js:"js",async:"sabay",render:"ipakita",swap:"palitan_pwesto",morph:"baguhin_hugis",settle:"ayusin",append:"idagdag_sa_dulo",prepend:"idagdag_sa_simula",exit:"lumabas",else:"kung_hindi",focus:"ituon",blur:"alisin_tuon",install:"ikabit",behavior:"ugali",init:"simulan",clone:"kopyahin",breakpoint:"breakpoint",clear:"burahin",close:"isara",open:"buksan",select:"piliin"},modifiers:{to:"sa",from:"mula_sa",into:"papasok_sa",with:"kasama",at:"sa",in:"sa_loob",of:"ng",as:"bilang",by:"sa_pamamagitan_ng",before:"bago",after:"pagkatapos",over:"sa_ibabaw",under:"sa_ilalim",between:"sa_pagitan",through:"sa_pamamagitan",without:"walang",on:"sa",then:"pagkatapos",and:"at",end:"wakas",until:"hanggang"},events:{click:"click",dblclick:"dblclick",mousedown:"mousedown",mouseup:"mouseup",mouseenter:"mouseenter",mouseleave:"mouseleave",mouseover:"mouseover",mouseout:"mouseout",mousemove:"mousemove",keydown:"keydown",keyup:"keyup",keypress:"keypress",focus:"focus",blur:"blur",change:"change",input:"input",submit:"submit",reset:"reset",load:"load",unload:"unload",resize:"resize",scroll:"scroll",touchstart:"touchstart",touchend:"touchend",touchmove:"touchmove",touchcancel:"touchcancel",every:"bawat"},logical:{when:"kapag",where:"kung_saan",and:"at",or:"o",not:"hindi",is:"ay",exists:"may",matches:"tumutugma",contains:"naglalaman",includes:"kasama",equals:"katumbas",has:"may",have:"may",then:"pagkatapos",else:"kung_hindi",otherwise:"kung_hindi_man",end:"wakas",live:"live",changes:"nagbabago",if:"kung",empty:"walang_laman",true:"totoo",false:"mali",null:"wala",undefined:"hindi_tinukoy"},temporal:{seconds:"segundo",second:"segundo",milliseconds:"milisegundo",millisecond:"milisegundo",minutes:"minuto",minute:"minuto",hours:"oras",hour:"oras",ms:"ms",s:"s",min:"min",h:"h",now:"ngayon",forever:"magpakailanman",times:"beses"},values:{true:"totoo",false:"mali",null:"wala",undefined:"hindi_tinukoy",it:"ito",its:"nito",me:"ako",my:"aking",myself:"sarili_ko",you:"ikaw",your:"iyong",yourself:"sarili_mo",element:"elemento",target:"target",detail:"detalye",event:"pangyayari",window:"bintana",document:"dokumento",body:"katawan",result:"resulta",value:"halaga"},attributes:{class:"klase",classes:"mga_klase",style:"estilo",styles:"mga_estilo",attribute:"katangian",attributes:"mga_katangian",property:"ari_arian",properties:"mga_ari_arian",id:"id",value:"halaga",text:"teksto",html:"html",disabled:"hindi_pinagana",checked:"naka_tsek"},expressions:{first:"una",last:"huli",next:"susunod",previous:"nakaraan",prev:"nakaraan",at:"sa",random:"random",closest:"pinakamalapit",parent:"magulang",children:"mga_anak",within:"sa_loob_ng",no:"walang",empty:"walang_laman",some:"ilan","starts with":"nagsisimula_sa","ends with":"nagtatapos_sa","ignoring case":"huwag_pansinin_ang_case","sorted by":"nakaayos_ayon_sa","mapped to":"binago_sa","split by":"hinati_sa","joined by":"pinagsama_sa",length:"haba",index:"indeks"}};xo(sl,"tl",{allowEnglishFallback:!0});var il={commands:{add:"הוסף",append:"צרף",async:"אסינכרוני",beep:"ביפ",break:"שבור",call:"קרא",continue:"המשך",copy:"העתק",decrement:"הקטן",default:"ברירת מחדל",exit:"צא",fetch:"הבא",for:"עבור",get:"קבל",go:"לך",halt:"עצור",hide:"הסתר",if:"אם",increment:"הגדל",install:"התקן",js:"js",log:"רשום",make:"צור",measure:"מדוד",morph:"הפוך",on:"ב",pick:"בחר",put:"שים",remove:"הסר",render:"רנדר",repeat:"חזור",return:"החזר",send:"שלח",set:"קבע",settle:"התייצב",show:"הראה",swap:"החלף",take:"קח",tell:"אמור",throw:"זרוק",toggle:"מתג",transition:"מעבר",trigger:"הפעל",until:"עד",wait:"חכה",while:"כל עוד"},modifiers:{after:"אחרי",before:"לפני",from:"מ",into:"לתוך",to:"על",with:"עם"},events:{blur:"טשטש",change:"שינוי",click:"לחיצה",focus:"מקד",input:"קלט",submit:"שליחה"},logical:{and:"וגם",else:"אחרת",end:"סוף",then:"אז",live:"חי",changes:"משתנה",when:"כאשר",where:"איפה"},temporal:{},values:{body:"גוף",event:"אירוע",it:"זה",its:"שלו",me:"אני",my:"שלי",result:"תוצאה",target:"יעד",you:"אתה",your:"שלך"},attributes:{},expressions:{}};xo(il,"he",{allowEnglishFallback:!0});var al=class e{static register(t,r){e.providers.set(t.toLowerCase(),r)}static unregister(t){e.providers.delete(t.toLowerCase())}static setDefault(t){const r=t.toLowerCase();if("en"!==r&&!e.providers.has(r))throw Error(`Locale '${t}' is not registered. Available locales: ${e.getAvailable().join(", ")}`);e.defaultLocale=r}static getDefault(){return e.defaultLocale}static get(t){const r=(t||e.defaultLocale).toLowerCase();if("en"===r)return e.englishProvider;const n=e.providers.get(r);if(!n)throw Error(`Locale '${r}' is not registered. Available locales: ${e.getAvailable().join(", ")}`);return n}static has(t){const r=t.toLowerCase();return"en"===r||e.providers.has(r)}static getAvailable(){return["en",...Array.from(e.providers.keys())]}static reset(){e.providers.clear(),e.defaultLocale="en"}static registerAll(t){for(const[r,n]of Object.entries(t))e.register(r,n)}};al.providers=new Map,al.defaultLocale="en",al.englishProvider=Co();var ol=al;function ll(e){if(0===e.length)return"";let t="";for(let r=0;e.length>r;r++){const n=e[r],s=e[r+1],i=n.endsWith("-"),a=n.startsWith("-");let o=n;if(i&&(o=n.slice(0,-1)),a&&(o=n.substring(1)),t+=o,s){const e=s.startsWith("-");i||e||(t+=" ")}}return t}var cl={en:{code:"en",name:"English",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","source","destination","quantity","duration","method","style"],markers:[{form:"on",role:"event",position:"preposition",required:!0},{form:"to",role:"destination",position:"preposition",required:!1},{form:"into",role:"destination",position:"preposition",required:!1},{form:"from",role:"source",position:"preposition",required:!1},{form:"with",role:"style",position:"preposition",required:!1},{form:"by",role:"quantity",position:"preposition",required:!1},{form:"as",role:"method",position:"preposition",required:!1},{form:"over",role:"duration",position:"preposition",required:!1},{form:"for",role:"duration",position:"preposition",required:!1}]},ja:{code:"ja",name:"日本語",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"を",role:"patient",position:"postposition",required:!0},{form:"に",role:"destination",position:"postposition",required:!0},{form:"から",role:"source",position:"postposition",required:!0},{form:"で",role:"event",position:"postposition",required:!0},{form:"で",role:"style",position:"postposition",required:!1},{form:"と",role:"style",position:"postposition",required:!1},{form:"へ",role:"destination",position:"postposition",required:!1}],rules:[{name:"event-handler",description:"Transform event handlers to Japanese SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"],optionalRoles:["patient"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}},{name:"put-into",description:"Transform put X into Y to Japanese order",priority:90,match:{commands:["put","置く"],requiredRoles:["action","patient","destination"]},transform:{roleOrder:["patient","destination","action"],insertMarkers:!0}}]},ko:{code:"ko",name:"한국어",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"를",role:"patient",position:"postposition",required:!0,alternatives:["을"]},{form:"에",role:"destination",position:"postposition",required:!0},{form:"에서",role:"source",position:"postposition",required:!0},{form:"로",role:"style",position:"postposition",required:!1,alternatives:["으로"]},{form:"와",role:"style",position:"postposition",required:!1,alternatives:["과"]},{form:"로",role:"method",position:"postposition",required:!1,alternatives:["으로"]}],rules:[{name:"event-handler",description:"Transform event handlers to Korean SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},zh:{code:"zh",name:"中文",wordOrder:"SVO",adpositionType:"preposition",morphology:"isolating",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"当",role:"event",position:"preposition",required:!0},{form:"时",role:"event",position:"postposition",required:!0},{form:"把",role:"patient",position:"preposition",required:!1},{form:"到",role:"destination",position:"preposition",required:!1},{form:"从",role:"source",position:"preposition",required:!1},{form:"用",role:"style",position:"preposition",required:!1},{form:"的",role:"method",position:"postposition",required:!1}],rules:[{name:"event-handler-standard",description:"Standard event handler: 当 X 时 Y",priority:100,match:{requiredRoles:["event","action"]},transform:{roleOrder:["event","action","patient"],insertMarkers:!0,custom:(e,t)=>{const r=e.roles.get("event"),n=e.roles.get("action"),s=e.roles.get("patient"),i=["当",r?.translated||r?.value,"时"];return i.push(n?.translated||n?.value||""),s&&i.push(s.translated||s.value),i.filter(Boolean).join(" ")}}},{name:"ba-construction",description:"BA construction for object-fronting: 把 X Y",priority:80,match:{commands:["put","set","move"],requiredRoles:["action","patient","destination"]},transform:{roleOrder:["patient","action","destination"],insertMarkers:!0}}]},ar:{code:"ar",name:"العربية",wordOrder:"VSO",adpositionType:"preposition",morphology:"fusional",direction:"rtl",canonicalOrder:["action","agent","patient","destination","source"],markers:[{form:"عند",role:"event",position:"preposition",required:!0},{form:"إلى",role:"destination",position:"preposition",required:!1},{form:"في",role:"destination",position:"preposition",required:!1},{form:"من",role:"source",position:"preposition",required:!1},{form:"بـ-",role:"style",position:"preposition",required:!1},{form:"مع",role:"style",position:"preposition",required:!1},{form:"كـ-",role:"method",position:"preposition",required:!1}],rules:[{name:"event-handler-vso",description:"VSO event handler: VERB TARGET عند EVENT",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["action","patient","event"],insertMarkers:!0}}]},tr:{code:"tr",name:"Türkçe",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"i",role:"patient",position:"postposition",required:!0,alternatives:["ı","u","ü"]},{form:"e",role:"destination",position:"postposition",required:!0,alternatives:["a"]},{form:"den",role:"source",position:"postposition",required:!0,alternatives:["dan"]},{form:"de",role:"event",position:"postposition",required:!0,alternatives:["da"]},{form:"ile",role:"style",position:"postposition",required:!1},{form:"olarak",role:"method",position:"postposition",required:!1}],rules:[{name:"event-handler-sov",description:"SOV event handler",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},es:{code:"es",name:"Español",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"en",role:"event",position:"preposition",required:!0},{form:"a",role:"destination",position:"preposition",required:!1},{form:"hacia",role:"destination",position:"preposition",required:!1},{form:"de",role:"source",position:"preposition",required:!1},{form:"con",role:"style",position:"preposition",required:!1},{form:"por",role:"quantity",position:"preposition",required:!1},{form:"como",role:"method",position:"preposition",required:!1}]},de:{code:"de",name:"Deutsch",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"bei",role:"event",position:"preposition",required:!0},{form:"zu",role:"destination",position:"preposition",required:!1},{form:"in",role:"destination",position:"preposition",required:!1},{form:"von",role:"source",position:"preposition",required:!1},{form:"aus",role:"source",position:"preposition",required:!1},{form:"mit",role:"style",position:"preposition",required:!1},{form:"um",role:"quantity",position:"preposition",required:!1},{form:"als",role:"method",position:"preposition",required:!1}]},fr:{code:"fr",name:"Français",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"sur",role:"event",position:"preposition",required:!0},{form:"à",role:"destination",position:"preposition",required:!1},{form:"dans",role:"destination",position:"preposition",required:!1},{form:"de",role:"source",position:"preposition",required:!1},{form:"avec",role:"style",position:"preposition",required:!1},{form:"par",role:"quantity",position:"preposition",required:!1},{form:"comme",role:"method",position:"preposition",required:!1}]},pt:{code:"pt",name:"Português",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"em",role:"event",position:"preposition",required:!0},{form:"para",role:"destination",position:"preposition",required:!1},{form:"em",role:"destination",position:"preposition",required:!1},{form:"de",role:"source",position:"preposition",required:!1},{form:"com",role:"style",position:"preposition",required:!1},{form:"por",role:"quantity",position:"preposition",required:!1},{form:"como",role:"method",position:"preposition",required:!1}]},id:{code:"id",name:"Bahasa Indonesia",wordOrder:"SVO",adpositionType:"preposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"pada",role:"event",position:"preposition",required:!0},{form:"ke",role:"destination",position:"preposition",required:!1},{form:"dari",role:"source",position:"preposition",required:!1},{form:"dengan",role:"style",position:"preposition",required:!1},{form:"sebagai",role:"method",position:"preposition",required:!1}]},qu:{code:"qu",name:"Runasimi",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","source","destination","event","action"],markers:[{form:"ta",role:"patient",position:"postposition",required:!0},{form:"man",role:"destination",position:"postposition",required:!0},{form:"manta",role:"source",position:"postposition",required:!0},{form:"pi",role:"event",position:"postposition",required:!0},{form:"wan",role:"style",position:"postposition",required:!1},{form:"hina",role:"method",position:"postposition",required:!1}]},sw:{code:"sw",name:"Kiswahili",wordOrder:"SVO",adpositionType:"preposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"kwenye",role:"event",position:"preposition",required:!0},{form:"kwa",role:"destination",position:"preposition",required:!1},{form:"kutoka",role:"source",position:"preposition",required:!1},{form:"na",role:"style",position:"preposition",required:!1},{form:"kama",role:"method",position:"preposition",required:!1}]},bn:{code:"bn",name:"বাংলা",wordOrder:"SOV",adpositionType:"postposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"কে",role:"patient",position:"postposition",required:!0},{form:"তে",role:"destination",position:"postposition",required:!0},{form:"এ",role:"event",position:"postposition",required:!0},{form:"থেকে",role:"source",position:"postposition",required:!0},{form:"দিয়ে",role:"style",position:"postposition",required:!1},{form:"জন্য",role:"duration",position:"postposition",required:!1}],rules:[{name:"event-handler",description:"Transform event handlers to Bengali SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"],optionalRoles:["patient"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},it:{code:"it",name:"Italiano",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"su",role:"event",position:"preposition",required:!0},{form:"in",role:"destination",position:"preposition",required:!1},{form:"a",role:"destination",position:"preposition",required:!1},{form:"da",role:"source",position:"preposition",required:!1},{form:"di",role:"source",position:"preposition",required:!1},{form:"con",role:"style",position:"preposition",required:!1},{form:"come",role:"method",position:"preposition",required:!1}]},ru:{code:"ru",name:"Русский",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"при",role:"event",position:"preposition",required:!0},{form:"в",role:"destination",position:"preposition",required:!1},{form:"на",role:"destination",position:"preposition",required:!1},{form:"к",role:"destination",position:"preposition",required:!1},{form:"из",role:"source",position:"preposition",required:!1},{form:"от",role:"source",position:"preposition",required:!1},{form:"с",role:"source",position:"preposition",required:!1},{form:"с",role:"style",position:"preposition",required:!1},{form:"со",role:"style",position:"preposition",required:!1},{form:"как",role:"method",position:"preposition",required:!1}]},uk:{code:"uk",name:"Українська",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"при",role:"event",position:"preposition",required:!0},{form:"в",role:"destination",position:"preposition",required:!1},{form:"на",role:"destination",position:"preposition",required:!1},{form:"до",role:"destination",position:"preposition",required:!1},{form:"з",role:"source",position:"preposition",required:!1},{form:"від",role:"source",position:"preposition",required:!1},{form:"із",role:"source",position:"preposition",required:!1},{form:"з",role:"style",position:"preposition",required:!1},{form:"із",role:"style",position:"preposition",required:!1},{form:"як",role:"method",position:"preposition",required:!1}]},vi:{code:"vi",name:"Tiếng Việt",wordOrder:"SVO",adpositionType:"preposition",morphology:"isolating",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"khi",role:"event",position:"preposition",required:!0},{form:"vào",role:"destination",position:"preposition",required:!1},{form:"cho",role:"destination",position:"preposition",required:!1},{form:"đến",role:"destination",position:"preposition",required:!1},{form:"từ",role:"source",position:"preposition",required:!1},{form:"khỏi",role:"source",position:"preposition",required:!1},{form:"với",role:"style",position:"preposition",required:!1},{form:"như",role:"method",position:"preposition",required:!1}]},hi:{code:"hi",name:"हिन्दी",wordOrder:"SOV",adpositionType:"postposition",morphology:"fusional",direction:"ltr",canonicalOrder:["patient","event","action"],markers:[{form:"को",role:"patient",position:"postposition",required:!0},{form:"में",role:"destination",position:"postposition",required:!0},{form:"पर",role:"destination",position:"postposition",required:!1},{form:"पर",role:"event",position:"postposition",required:!0},{form:"से",role:"source",position:"postposition",required:!0},{form:"से",role:"style",position:"postposition",required:!1},{form:"साथ",role:"style",position:"postposition",required:!1},{form:"के रूप में",role:"method",position:"postposition",required:!1}],rules:[{name:"event-handler",description:"Transform event handlers to Hindi SOV order",priority:100,match:{commands:["on"],requiredRoles:["event","action"],optionalRoles:["patient"]},transform:{roleOrder:["patient","event","action"],insertMarkers:!0}}]},tl:{code:"tl",name:"Tagalog",wordOrder:"VSO",adpositionType:"preposition",morphology:"agglutinative",direction:"ltr",canonicalOrder:["action","agent","patient","destination","source"],markers:[{form:"kapag",role:"event",position:"preposition",required:!0},{form:"sa",role:"destination",position:"preposition",required:!1},{form:"mula sa",role:"source",position:"preposition",required:!1},{form:"nang",role:"style",position:"preposition",required:!1},{form:"bilang",role:"method",position:"preposition",required:!1}],rules:[{name:"event-handler-vso",description:"VSO event handler: VERB TARGET kapag EVENT",priority:100,match:{commands:["on"],requiredRoles:["event","action"]},transform:{roleOrder:["action","patient","event"],insertMarkers:!0}}]},th:{code:"th",name:"ไทย",wordOrder:"SVO",adpositionType:"preposition",morphology:"isolating",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"เมื่อ",role:"event",position:"preposition",required:!0},{form:"ใน",role:"destination",position:"preposition",required:!1},{form:"ไปยัง",role:"destination",position:"preposition",required:!1},{form:"จาก",role:"source",position:"preposition",required:!1},{form:"ด้วย",role:"style",position:"preposition",required:!1},{form:"เป็น",role:"method",position:"preposition",required:!1}]},pl:{code:"pl",name:"Polski",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"ltr",canonicalOrder:["event","action","patient","destination"],markers:[{form:"gdy",role:"event",position:"preposition",required:!0},{form:"przy",role:"event",position:"preposition",required:!1},{form:"do",role:"destination",position:"preposition",required:!1},{form:"w",role:"destination",position:"preposition",required:!1},{form:"na",role:"destination",position:"preposition",required:!1},{form:"z",role:"source",position:"preposition",required:!1},{form:"od",role:"source",position:"preposition",required:!1},{form:"ze",role:"source",position:"preposition",required:!1},{form:"z",role:"style",position:"preposition",required:!1},{form:"ze",role:"style",position:"preposition",required:!1},{form:"jako",role:"method",position:"preposition",required:!1}]},he:{code:"he",name:"עברית",wordOrder:"SVO",adpositionType:"preposition",morphology:"fusional",direction:"rtl",canonicalOrder:["event","action","patient","destination"],markers:[{form:"ב",role:"event",position:"preposition",required:!0},{form:"על",role:"destination",position:"preposition",required:!1},{form:"אל",role:"destination",position:"preposition",required:!1},{form:"ל",role:"destination",position:"preposition",required:!1},{form:"את",role:"patient",position:"preposition",required:!1},{form:"מ",role:"source",position:"preposition",required:!1},{form:"מן",role:"source",position:"preposition",required:!1},{form:"עם",role:"style",position:"preposition",required:!1},{form:"כ",role:"method",position:"preposition",required:!1}]}};function ul(e){return cl[e]}function dl(e){const t={};for(const[r,n]of Object.entries(e.words))t[n]=r;const r={};if(e.categories)for(const[t,n]of Object.entries(e.categories)){r[t]={};for(const[e,s]of Object.entries(n))r[t][s]=e}const n={source:e.target,target:e.source,words:t};return Object.keys(r).length>0&&(n.categories=r),n}function ml(e,t,r,n){const s={},i={};for(const r of["commands","modifiers","events","logical","temporal","values","attributes"]){const n=e[r],a=t[r];if(n&&a){i[r]={};for(const[e,t]of Object.entries(n)){const n=a[e];n&&t!==n&&(s[t]=n,i[r][t]=n)}}}return{source:r,target:n,words:s,categories:i}}var pl=ml(To,Mo,"ja","zh"),hl=dl(pl),fl=ml(_o,To,"ko","ja"),yl=dl(fl),gl={source:"es",target:"pt",words:{en:"em",decir:"dizer",disparar:"disparar",enviar:"enviar",tomar:"pegar",poner:"colocar",establecer:"definir",obtener:"obter",agregar:"adicionar",quitar:"remover",alternar:"alternar",ocultar:"esconder",mostrar:"mostrar",si:"se",menos:"a menos",repetir:"repetir",para:"para",mientras:"enquanto",hasta:"até",continuar:"continuar",romper:"parar",detener:"parar",esperar:"esperar",buscar:"buscar",llamar:"chamar",retornar:"retornar",hacer:"fazer",registrar:"registrar",lanzar:"lançar",atrapar:"capturar",medir:"medir","transición":"transição",incrementar:"incrementar",decrementar:"decrementar",predeterminar:"padrão",ir:"ir",copiar:"copiar",escoger:"escolher",intercambiar:"trocar",transformar:"transformar","añadir":"anexar",salir:"sair",a:"para",de:"de",dentro:"em",con:"com",como:"como",por:"por",clic:"clique",cambio:"mudança",entrada:"entrada","envío":"envio",carga:"carregar",enfoque:"foco",desenfoque:"desfoque",verdadero:"verdadeiro",falso:"falso",y:"e",o:"ou",no:"não",es:"é",segundos:"segundos",milisegundos:"milissegundos",nulo:"nulo",indefinido:"indefinido","vacío":"vazio"},categories:{commands:{en:"em",decir:"dizer",tomar:"pegar",poner:"colocar",establecer:"definir",obtener:"obter",agregar:"adicionar",quitar:"remover",ocultar:"esconder",si:"se",mientras:"enquanto",hasta:"até",romper:"parar",detener:"parar",llamar:"chamar",hacer:"fazer",lanzar:"lançar",atrapar:"capturar",escoger:"escolher",intercambiar:"trocar","añadir":"anexar",salir:"sair"},events:{clic:"clique",cambio:"mudança",carga:"carregar",enfoque:"foco",desenfoque:"desfoque"},logical:{verdadero:"verdadeiro",y:"e",o:"ou",no:"não",es:"é"}}},vl=dl(gl),bl=new Map([["ja->zh",pl],["zh->ja",hl],["ko->ja",fl],["ja->ko",yl],["es->pt",gl],["pt->es",vl]]),wl={en:{commands:{on:"on",tell:"tell",trigger:"trigger",send:"send",take:"take",put:"put",set:"set",get:"get",add:"add",remove:"remove",toggle:"toggle",hide:"hide",show:"show",if:"if",unless:"unless",repeat:"repeat",for:"for",while:"while",until:"until",continue:"continue",break:"break",halt:"halt",wait:"wait",fetch:"fetch",call:"call",return:"return",make:"make",log:"log",throw:"throw",catch:"catch",measure:"measure",transition:"transition",increment:"increment",decrement:"decrement",default:"default",go:"go",pushUrl:"pushUrl",replaceUrl:"replaceUrl",copy:"copy",pick:"pick",beep:"beep",js:"js",async:"async",render:"render",swap:"swap",morph:"morph",settle:"settle",append:"append",exit:"exit",install:"install",open:"open",close:"close",select:"select",clear:"clear",breakpoint:"breakpoint",prepend:"prepend",clone:"clone",scroll:"scroll",push:"push",replace:"replace",process:"process"},modifiers:{to:"to",from:"from",into:"into",with:"with",at:"at",in:"in",of:"of",as:"as",by:"by",before:"before",after:"after",over:"over",under:"under",between:"between",through:"through",without:"without"},events:{click:"click",dblclick:"dblclick",mousedown:"mousedown",mouseup:"mouseup",mouseenter:"mouseenter",mouseleave:"mouseleave",mouseover:"mouseover",mouseout:"mouseout",mousemove:"mousemove",keydown:"keydown",keyup:"keyup",keypress:"keypress",focus:"focus",blur:"blur",change:"change",input:"input",submit:"submit",reset:"reset",load:"load",unload:"unload",resize:"resize",scroll:"scroll",touchstart:"touchstart",touchend:"touchend",touchmove:"touchmove",touchcancel:"touchcancel"},logical:{when:"when",where:"where",and:"and",or:"or",not:"not",is:"is",exists:"exists",matches:"matches",contains:"contains",includes:"includes",equals:"equals",has:"has",have:"have",then:"then",else:"else",otherwise:"otherwise",end:"end",live:"live",changes:"changes"},temporal:{seconds:"seconds",second:"second",milliseconds:"milliseconds",millisecond:"millisecond",minutes:"minutes",minute:"minute",hours:"hours",hour:"hour",ms:"ms",s:"s",min:"min",h:"h"},values:{true:"true",false:"false",null:"null",undefined:"undefined",it:"it",its:"its",me:"me",my:"my",myself:"myself",you:"you",your:"your",yourself:"yourself",element:"element",target:"target",detail:"detail",event:"event",window:"window",document:"document",body:"body",result:"result",value:"value"},attributes:{class:"class",classes:"classes",style:"style",styles:"styles",attribute:"attribute",attributes:"attributes",property:"property",properties:"properties"},expressions:{first:"first",last:"last",next:"next",previous:"previous",prev:"prev",at:"at",random:"random",closest:"closest",parent:"parent",children:"children",within:"within",no:"no",empty:"empty",some:"some","starts with":"starts with","ends with":"ends with","ignoring case":"ignoring case","sorted by":"sorted by","mapped to":"mapped to","split by":"split by","joined by":"joined by"}},es:So,ko:_o,zh:Mo,fr:Po,de:No,ja:To,ar:jo,tr:Vo,id:zo,qu:Bo,sw:Uo,pt:Jo,it:Go,vi:Zo,pl:Xo,ru:Yo,uk:Qo,hi:el,bn:tl,th:rl,ms:nl,tl:sl,he:il},kl=["commands","modifiers","events","logical","temporal","values","attributes","expressions"];function El(e){const t=new Set(fo),r=wl[e];return r?.commands&&Object.values(r.commands).forEach(e=>{"string"==typeof e&&t.add(e.toLowerCase())}),t}function xl(e){const t=e.filter(e=>!e.isBlank&&e.originalIndent.length>0);if(0===t.length)return e.map(()=>"");const r=t.map(e=>e.originalIndent.replace(/\t/g," ").length),n=Math.min(...r),s=n>0?n:4;return e.map(e=>{if(e.isBlank)return"";if(0===e.originalIndent.length)return"";const t=e.originalIndent.replace(/\t/g," ");return" ".repeat(Math.round(t.length/s))})}var Cl=new Set(["to","into","from","with","by","as","at","in","on","of","over"]),Sl=new Set(["live","when","unless"]);function Al(e,t){const r=El(t),n=e.split(/\s+/);if(0===n.length)return[e];const s=[];let i=[];const a=n[0]?.toLowerCase();let o=!Ol.has(a),l=0;for(let e=0;n.length>e;e++){const t=n[e],a=t.toLowerCase();if(Sl.has(a)?l++:"end"===a&&l>0&&l--,r.has(a)&&i.length>0){const e=i[i.length-1].toLowerCase();if(!o){o=!0,i.push(t);continue}if(l>0){i.push(t);continue}if(!Cl.has(e)&&!r.has(e)){s.push(i.join(" ")),i=[t];continue}}i.push(t)}return i.length>0&&s.push(i.join(" ")),s.filter(e=>e.length>0)}function Tl(e,t){const r=Array.from(Eo),n="en"===t?null:wl[t];n?.modifiers?.then&&r.push(n.modifiers.then),n?.logical?.then&&r.push((n?.logical).then);const s=r.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=RegExp(`\\s+(${s.join("|")})\\s+`,"gi");return e.split(i).filter(e=>{const t=e.toLowerCase().trim();return t&&!r.some(e=>e.toLowerCase()===t)}).map(e=>e.trim()).filter(e=>e.length>0)}var Ol=function(){const e=new Set;e.add("on");for(const t of Object.values(cl))for(const r of t.markers)if("event"===r.role){const t=r.form.replace(/^-|-$/g,"").toLowerCase();t&&e.add(t),r.alternatives?.forEach(t=>{const r=t.replace(/^-|-$/g,"").toLowerCase();r&&e.add(r)})}return e}();function Pl(e){const t={};e.markers.forEach(e=>{const r=e.form.replace(/^-|-$/g,"").toLowerCase();r&&(t[r]=e.role),e.alternatives?.forEach(r=>{const n=r.replace(/^-|-$/g,"").toLowerCase();n&&(t[n]=e.role)})});for(const[e,r]of Object.entries(po))e in t||(t[e]=r);return t}var Ll={zh:["时","的","地","得"],ja:[],ko:[]},Nl={zh:["当"],ar:["بـ","كـ","و"]};function Il(e,t,r){if(/^[#.<@]/.test(e))return e;if(/^\d+/.test(e))return e;const n="en"===t?null:wl[t],s=wl[r];if(!s)return e;let i=e;if(n){const t=function(e,t){const r=t.toLowerCase();for(const t of kl){const n=e[t];for(const[e,s]of Object.entries(n))if(s.toLowerCase()===r)return{category:t,englishKey:e}}}(n,e);t&&(i=t.englishKey)}const a=function(e,t){const r=t.toLowerCase();for(const t of kl){const n=e[t][r];if(n)return n}}(s,i);return a??e}var jl={en:{type:"suffix",marker:"'s"},es:{type:"preposition",marker:"de"},pt:{type:"preposition",marker:"de"},fr:{type:"preposition",marker:"de"},de:{type:"preposition",marker:"von"},ja:{type:"suffix",marker:"の"},ko:{type:"suffix",marker:"의"},zh:{type:"suffix",marker:"的"},ar:{type:"preposition",marker:"لـ"},tr:{type:"suffix",marker:"'ın"},id:{type:"preposition",marker:"dari"},qu:{type:"suffix",marker:"-pa"},sw:{type:"preposition",marker:"ya"}};function Rl(e,t,r){const n=e.match(/^(.+)'s$/i);if(!n)return e;const s=n[1],i=jl[r]||jl.en,a={me:"my",it:"its",you:"your"},o=s.toLowerCase();if(a[o])return Il(a[o],"en",r);const l=Il(s,t,r);switch(i.type){case"suffix":return`${l}${i.marker}`;case"preposition":return`__POSS__${i.marker}__${l}__POSS__`;default:return l+"'s"}}var _l=/^(my|its|your|me|it|you)(\??\..+)$/i,ql={me:"my",it:"its",you:"your",my:"my",its:"its",your:"your"};function Ml(e,t,r){const n=e.match(_l);if(!n)return null;const s=n[1].toLowerCase(),i=n[2],a=ql[s]||s,o=Il(a,t,r);if(o.includes(" "))return null;if(o!==a)return o+i;if(s!==a){const e=Il(s,t,r);if(e!==s&&!e.includes(" "))return e+i}return null}function $l(e,t,r){if(!e.includes(" ")){if(e.includes("'s"))return Rl(e,t,r);const n=Ml(e,t,r);return null!==n?n:Il(e,t,r)}const n=e.split(/\s+/),s=[];let i=0;for(;n.length>i;){const e=n[i];if(e.includes("'s")){const a=Rl(e,t,r),o=a.match(/^__POSS__(.+)__(.+)__POSS__$/);if(o&&n.length>i+1){const e=o[1],a=o[2],l=Il(n[i+1],t,r);s.push(`${l} ${e} ${a}`),i+=2;continue}if(o){s.push(`${o[1]} ${o[2]}`),i++;continue}s.push(a),i++;continue}if(/^[#.<@]/.test(e)||/^\d+/.test(e)){s.push(e),i++;continue}if(/^["'].*["']$/.test(e)){s.push(e),i++;continue}const a=Ml(e,t,r);null===a?(s.push(Il(e,t,r)),i++):(s.push(a),i++)}return s.join(" ")}var Vl=class{constructor(e="en",t){const r=ul(e),n=ul(t);if(!r)throw Error("Unknown source locale: "+e);if(!n)throw Error("Unknown target locale: "+t);this.sourceProfile=r,this.targetProfile=n}transform(e){const t=function(e){if("en"===e)return"then";const t=wl[e];return t&&(t.modifiers?.then||t.logical?.then)||"then"}(this.targetProfile.code);if(e.includes("\n")){const{parts:r,lineMetadata:n,partToLineIndex:s}=function(e,t){const r=e.split("\n"),n=[],s=[],i=[];for(let e=0;r.length>e;e++){const a=r[e],o=a.match(/^(\s*)/),l=o?o[1]:"",c=a.trim();if(n.push({content:c,originalIndent:l,isBlank:0===c.length}),c.length>0){const r=Tl(c,t);for(const n of r){const r=Al(n,t);for(const t of r)s.push(t),i.push(e)}}}return{parts:s,lineMetadata:n,partToLineIndex:i}}(e,this.sourceProfile.code);return function(e,t,r,n){if(1>=t.filter(e=>!e.isBlank).length&&1>=e.length){const r=xl(t),n=[];for(let s=0;t.length>s;s++)t[s].isBlank?n.push(""):e.length>0&&n.push(r[s]+e[0]);return n.join("\n")}const s=xl(t),i=new Map;for(let t=0;e.length>t;t++){const n=r[t];i.has(n)||i.set(n,[]),i.get(n).push(e[t])}const a=[];for(let e=0;t.length>e;e++){const r=s[e];if(t[e].isBlank)a.push("");else{const t=i.get(e)||[];if(t.length>0){const e=t.join(` ${n} `);a.push(r+e)}}}return a.join("\n")}(r.map(e=>this.transformSingle(e)),n,s,t)}const r=function(e,t){const r=e.split(/\n/).map(e=>e.trim()).filter(e=>e.length>0),n=[];for(const e of r){const r=Tl(e,t);for(const e of r){const r=Al(e,t);n.push(...r)}}return n}(e,this.sourceProfile.code);return r.length>1?r.map(e=>this.transformSingle(e)).join(` ${t} `):this.transformSingle(e)}transformSingle(e){const t=function(e,t){const r=e.split(/\s+/),n=r[0]?.toLowerCase();if(!n||!Sl.has(n))return null;let s=1,i=-1;for(let e=1;r.length>e;e++){const t=r[e].toLowerCase();if(Sl.has(t))s++;else if("end"===t&&(s--,0===s)){i=e;break}}if(-1!==i&&i!==r.length-1)return null;const a=-1!==i?r.slice(1,i):r.slice(1),o={headKeyword:r[0],body:""};if(-1!==i&&(o.tailKeyword=r[i]),"live"===n)return{...o,body:a.join(" ")};if("when"===n){const e=a.findIndex(e=>"changes"===e.toLowerCase());return 0>e?null:{...o,prefixExpr:a.slice(0,e).join(" "),connector:a[e],body:a.slice(e+1).join(" ")}}const l=El(t);let c=-1;for(let e=0;a.length>e;e++)if(l.has(a[e].toLowerCase())){c=e;break}return c>0?{...o,prefixExpr:a.slice(0,c).join(" "),body:a.slice(c).join(" ")}:null}(e,this.sourceProfile.code);if(t)return this.transformBlock(t);const r=function(e,t="en"){const r=ul(t);if(!r)return null;const n=function(e,t){const r=[];let n="",s=!1,i=0;for(let t=0;e.length>t;t++){const a=e[t];"<"===a?(s=!0,i++):">"===a&&s&&(i--,0===i&&(s=!1)),/\s/.test(a)&&!s?n&&(r.push(n),n=""):n+=a}return n&&r.push(n),function(e,t){const r=Ll[t]||[],n=Nl[t]||[];if(0===r.length&&0===n.length)return e;const s=[];for(const t of e){if(/^[#.<@]/.test(t)||/^\d+/.test(t)){s.push(t);continue}let e=t,i="",a="";for(const t of n)if(e.startsWith(t)&&e.length>t.length){i=t,e=e.slice(t.length);break}for(const t of r)if(e.endsWith(t)&&e.length>t.length){a=t,e=e.slice(0,-t.length);break}i&&s.push(i),e&&s.push(e),a&&s.push(a)}return s}(r,t.code)}(e,r),s=function(e,t){if(0===e.length)return"unknown";const r=e[0].toLowerCase(),n=t.markers.find(e=>"event"===e.role&&"preposition"===e.position);return n&&r===n.form.toLowerCase()||Ol.has(r)?"event-handler":ko.has(r)?"conditional":"command"}(n,r);switch(s){case"event-handler":return function(e,t){const r=new Map;let n=Ol.has(e[0]?.toLowerCase())?1:0;if(e[n]&&(r.set("event",{role:"event",value:e[n]}),n++),e[n]&&"from"===e[n].toLowerCase()&&e[n+1]){n++;const t=[];for(;e[n]&&!fo.has(e[n].toLowerCase());)t.push(e[n]),n++;if(t.length>0){const e=t.join(" ");r.set("source",{role:"source",value:e,isSelector:/^[#.<@]/.test(e)})}}if(e[n]&&(r.set("action",{role:"action",value:e[n]}),n++),e[n]){const s=Pl(t);let i="patient",a=[];for(let t=n;e.length>t;t++){const n=e[t],o=s[n.toLowerCase()];if(o){if(a.length>0){const e=a.join(" ");r.set(i,{role:i,value:e,isSelector:/^[#.<@]/.test(e)})}i=o,a=[]}else a.push(n)}if(a.length>0){const e=a.join(" ");r.set(i,{role:i,value:e,isSelector:/^[#.<@]/.test(e)})}}return{type:"event-handler",roles:r,original:e.join(" ")}}(n,r);case"command":return function(e,t){const r=new Map;if(0===e.length)return{type:"command",roles:r,original:""};r.set("action",{role:"action",value:e[0]});const n=Pl(t);let s="patient",i=[];for(let t=1;e.length>t;t++){const a=e[t],o=n[a.toLowerCase()];if(o){if(i.length>0){const e=i.join(" ");r.set(s,{role:s,value:e,isSelector:/^[#.<@]/.test(e)})}s=o,i=[]}else i.push(a)}if(i.length>0){const e=i.join(" ");r.set(s,{role:s,value:e,isSelector:/^[#.<@]/.test(e)})}return{type:"command",roles:r,original:e.join(" ")}}(n,r);case"conditional":return function(e){const t=new Map;t.set("action",{role:"action",value:e[0]});const r=e.findIndex(e=>Eo.has(e.toLowerCase()));if(r>1){const n=e.slice(1,r).join(" ");t.set("condition",{role:"condition",value:n})}return{type:"conditional",roles:t,original:e.join(" ")}}(n);default:return null}}(e,this.sourceProfile.code);if(!r)return e;!function(e,t,r){for(const[n,s]of e.roles)s.translated=s.value.includes("'s")?$l(s.value,t,r):s.isSelector||s.isLiteral?s.value:$l(s.value,t,r)}(r,this.sourceProfile.code,this.targetProfile.code);const n=this.findRule(r);if(n?.transform.custom)return n.transform.custom(r,this.targetProfile);const s=function(e,t){const r=[],n=new Set;for(const s of t){const t=e.get(s);t&&(r.push(t),n.add(s))}for(const[t,s]of e)n.has(t)||r.push(s);return r}(r.roles,n?.transform.roleOrder||this.targetProfile.canonicalOrder);return ll(n?.transform.insertMarkers??1?function(e,t,r){const n=[];for(const s of e){const e=t.find(e=>e.role===s.role);e?"preposition"===r?(e.form&&n.push(e.form),n.push(s.translated||s.value)):"postposition"===r?(n.push(s.translated||s.value),e.form&&n.push(e.form)):n.push(s.translated||s.value):n.push(s.translated||s.value)}return n}(s,this.targetProfile.markers,this.targetProfile.adpositionType):s.map(e=>e.translated||e.value))}transformBlock(e){const t=this.sourceProfile.code,r=this.targetProfile.code,n=Il(e.headKeyword,t,r),s=e.tailKeyword?Il(e.tailKeyword,t,r):"",i=e.connector?Il(e.connector,t,r):"";return[n,e.prefixExpr?$l(e.prefixExpr,t,r):"",i,this.transform(e.body),s].filter(e=>e.length>0).join(" ")}findRule(e){if(this.targetProfile.rules)return this.targetProfile.rules.filter(t=>this.matchesRule(e,t)).sort((e,t)=>t.priority-e.priority)[0]}matchesRule(e,t){const{match:r}=t;for(const t of r.requiredRoles)if(!e.roles.has(t))return!1;if(r.commands&&r.commands.length>0){const t=e.roles.get("action");if(!t)return!1;const n=t.value.toLowerCase();if(!r.commands.some(e=>e.toLowerCase()===n))return!1}return!(r.predicate&&!r.predicate(e))}};function Dl(e,t){return new Vl("en",t).transform(e)}function zl(e,t){return new Vl(t,"en").transform(e)}ol.register("en",Co()),ol.register("es",Ao),ol.register("ja",Oo),ol.register("fr",Lo),ol.register("de",Io),ol.register("ar",Ro),ol.register("ko",qo),ol.register("zh",$o),ol.register("tr",Do),ol.register("id",Fo),ol.register("pt",Ko),ol.register("qu",Ho),ol.register("sw",Wo);let Fl="en";const Bl=Mr(gn,os,ms,hs,Cs,_s),Hl=function(e,t){const r=new Tr(null);for(const t of e)r.register(t);return new qr({registry:r,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([yi(),bi(),zi(),Fi(),Ui(),Ji(),Qi(),ea(),ra(),sa(),aa(),la(),da(),ma(),ha(),ga(),ba(),wa(),ka(),xa(),Ca(),Sa(),Aa(),Oa(),Pa(),La(),Ia(),qa(),Da(),Ba(),Ha(),Ua(),Wa(),Ja(),Ka(),Ga(),Za(),Xa(),to(),ro(),no(),so(),Ya(),Qa(),io(),ao(),oo(),new lo,co(),new uo,new mo],{expressionRegistry:Bl});function Ul(e){const t=function(){if("en"!==Fl)return ol.get(Fl)}();return zt(e,t?{keywords:t}:void 0)}const Wl={parse:e=>Ul(e),execute:async(e,t)=>{const r=kr(t),n=Ul(e);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await Hl.execute(n.node,r)}},Jl=function(e){return new $r(e)}(Wl),Kl={getLocale:()=>Fl,setLocale(e){if(ol.has(e)){if(Fl=e,ol.setDefault(e),"undefined"!=typeof document){document.documentElement.setAttribute("lang",e);const t=ul(e);"rtl"===t?.direction?document.documentElement.setAttribute("dir","rtl"):document.documentElement.setAttribute("dir","ltr")}}else console.warn(`Locale '${e}' not registered. Available: ${ol.getAvailable().join(", ")}`)},getAvailableLocales:()=>ol.getAvailable(),detectAndSetLocale(){if("undefined"==typeof navigator)return"en";const e=navigator.languages||[navigator.language];for(const t of e){const e=t.split("-")[0].toLowerCase();if(ol.has(e))return this.setLocale(e),e}return"en"},registerLocale(e,t){ol.register(e,t)},toLocale:(e,t)=>Dl(e,t||Fl),toEnglish:(e,t)=>zl(e,t||Fl),translate:function(e,t,r){return t===r?e:"en"===t?Dl(e,r):"en"===r?zl(e,t):bl.has(`${t}->${r}`)?function(e,t,r){const n=bl.get(`${t}->${r}`);if(!n)return Dl(zl(e,t),r);return e.split(/\s+/).map(e=>{if(e.startsWith("#")||e.startsWith(".")||e.startsWith("@"))return e;if(e.startsWith('"')||e.startsWith("'"))return e;const t=n.words[e];if(t)return t;const r=e.match(/^(.+?)(-.+)$/);if(r){const[,e,t]=r;return(n.words[e]||e)+t}return e}).join(" ")}(e,t,r):Dl(zl(e,t),r)},createTransformer:(e,t)=>new Vl(e,t),getProfile:ul,getSupportedGrammarLocales:function(){return Object.keys(cl)},profiles:cl,dictionaries:{en:{},es:So,ja:To,fr:Po,de:No,ar:jo,ko:_o,zh:Mo,tr:Vo,id:zo,pt:Jo,qu:Bo,sw:Uo},createKeywordProvider:xo},Gl={runtime:Wl,parse:e=>Ul(e),compile:e=>{const t=performance.now();try{const r=Ul(e);return{success:r.success,ast:r.node,errors:r.error?[r.error]:[],tokens:r.tokens||[],compilationTime:performance.now()-t}}catch(e){return{success:!1,ast:void 0,errors:[{message:e instanceof Error?e.message:e+"",line:1,column:1}],tokens:[],compilationTime:performance.now()-t}}},execute:async(e,t)=>{const r=kr(t);if("string"==typeof e){const t=Ul(e);if(!t.success||!t.node)throw Error(t.error?.message||"Parse failed");return await Hl.execute(t.node,r)}if(e&&"object"==typeof e)return await Hl.execute(e,r);throw Error("execute() requires a code string or compiled AST")},run:async(e,t)=>{const r=kr(t),n=Ul(e);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await Hl.execute(n.node,r)},evaluate:async(e,t)=>Gl.run(e,t),processNode:e=>{e===document?Jl.scanAndProcessAll():e instanceof HTMLElement&&Jl.processElement(e)},process:e=>Gl.processNode(e),createContext:wr,attributeProcessor:Jl,version:"1.1.0-classic-i18n",i18n:Kl,commands:["add","remove","toggle","put","hide","show","make","if","unless","repeat","break","continue","halt","return","exit","throw","set","get","increment","decrement","default","wait","fetch","trigger","send","transition","measure","settle","take","log","tell","call","copy","pick","beep","js","async","go","install","append","render","pseudo-command"],locales:["en","es","ja","fr","de","ar","ko","zh","tr","id","pt","qu","sw"],eval:async(e,t)=>Wl.execute(e,t),init:e=>{!1!==e?.autoDetectLocale&&Kl.detectAndSetLocale(),Jl.init()}};"undefined"!=typeof window&&(window.hyperfixi=Gl,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Gl.init()}):Gl.init());class Zl{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 r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=xn(e,"left operand");return{success:!0,value:Sn(n+xn(r,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[Ln("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 Pn([Ln("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return Pn([Ln("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"),Pn([Ln("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:r,right:n}=e;return An(r)?An(n)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[Ln("type-mismatch","Right operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[Ln("type-mismatch","Left operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for left operand"]}}}const Xl={addition:new Zl,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 r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=xn(e,"left operand");return{success:!0,value:Sn(n-xn(r,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[Ln("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Zl).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 r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=xn(e,"left operand");return{success:!0,value:Sn(n*xn(r,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[Ln("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Zl).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 r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=function(e,t,r=!0){if(0===t){if(r)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(xn(e,"left operand"),xn(r,"right operand"),!0);return{success:!0,value:n,type:"number"}}catch(e){return{success:!1,errors:[Ln("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Zl).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 r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(xn(e,"left operand"),xn(r,"right operand"));return{success:!0,value:n,type:"number"}}catch(e){return{success:!1,errors:[Ln("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 Zl).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 r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=xn(e,"left operand"),s=xn(r,"right operand");return{success:!0,value:Sn(Math.pow(n,s),"power"),type:"number"}}catch(e){return{success:!1,errors:[Ln("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Zl).validate(e)}}};var Yl=Object.freeze({__proto__:null,conversion:Cs,conversionExpressions:Cs,createCommonRegistry:function(){return Mr(gn,os,ms,Cs,_s)},createCoreRegistry:function(){return Mr(gn,os,ms)},createExpressionRegistry:Mr,createFullExpressionRegistry:function(){return Mr(gn,os,Cs,_s,hs,ms,Xl)},createFullRegistry:function(){return Mr(gn,os,ms,Cs,_s,hs)},logical:os,logicalExpressions:os,positional:_s,positionalExpressions:_s,properties:hs,propertiesExpressions:hs,references:gn,referencesExpressions:gn,special:ms,specialExpressions:ms});return Gl}();
2
2
  //# sourceMappingURL=hyperfixi-classic-i18n.js.map