@hyperfixi/core 2.9.4 → 2.10.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 (91) hide show
  1. package/dist/ast-utils/index.js +295 -85
  2. package/dist/ast-utils/index.mjs +295 -85
  3. package/dist/chunks/{bridge-DhmZ3Khh.js → bridge-CPNAPYAo.js} +2 -2
  4. package/dist/chunks/browser-modular-B0lGdcoP.js +2 -0
  5. package/dist/chunks/{index-DKrx4rv2.js → index-BQkkNlzO.js} +2 -2
  6. package/dist/commands/advanced/async.d.ts +0 -8
  7. package/dist/commands/advanced/js.d.ts +0 -8
  8. package/dist/commands/animation/measure.d.ts +0 -8
  9. package/dist/commands/animation/settle.d.ts +0 -8
  10. package/dist/commands/animation/start-view-transition.d.ts +0 -8
  11. package/dist/commands/animation/take.d.ts +0 -8
  12. package/dist/commands/animation/transition.d.ts +0 -8
  13. package/dist/commands/async/fetch.d.ts +0 -8
  14. package/dist/commands/async/wait.d.ts +0 -8
  15. package/dist/commands/behaviors/install.d.ts +0 -8
  16. package/dist/commands/content/append.d.ts +0 -8
  17. package/dist/commands/content/prepend.d.ts +0 -8
  18. package/dist/commands/control-flow/break.d.ts +0 -8
  19. package/dist/commands/control-flow/continue.d.ts +0 -8
  20. package/dist/commands/control-flow/exit.d.ts +0 -8
  21. package/dist/commands/control-flow/halt.d.ts +0 -8
  22. package/dist/commands/control-flow/if.d.ts +0 -8
  23. package/dist/commands/control-flow/repeat.d.ts +0 -8
  24. package/dist/commands/control-flow/return.d.ts +0 -8
  25. package/dist/commands/control-flow/throw.d.ts +0 -8
  26. package/dist/commands/data/clear.d.ts +0 -8
  27. package/dist/commands/data/default.d.ts +0 -8
  28. package/dist/commands/data/get.d.ts +0 -8
  29. package/dist/commands/data/increment.d.ts +0 -8
  30. package/dist/commands/data/set.d.ts +0 -8
  31. package/dist/commands/decorators/index.d.ts +2 -8
  32. package/dist/commands/dom/add.d.ts +0 -8
  33. package/dist/commands/dom/close.d.ts +0 -8
  34. package/dist/commands/dom/empty.d.ts +0 -8
  35. package/dist/commands/dom/hide.d.ts +0 -8
  36. package/dist/commands/dom/make.d.ts +0 -8
  37. package/dist/commands/dom/open.d.ts +0 -8
  38. package/dist/commands/dom/process-partials.d.ts +0 -8
  39. package/dist/commands/dom/put.d.ts +0 -8
  40. package/dist/commands/dom/remove.d.ts +0 -8
  41. package/dist/commands/dom/reset.d.ts +0 -8
  42. package/dist/commands/dom/select.d.ts +0 -8
  43. package/dist/commands/dom/show.d.ts +0 -8
  44. package/dist/commands/dom/swap.d.ts +2 -18
  45. package/dist/commands/dom/toggle.d.ts +0 -8
  46. package/dist/commands/events/trigger.d.ts +0 -8
  47. package/dist/commands/execution/blur.d.ts +0 -8
  48. package/dist/commands/execution/call.d.ts +0 -8
  49. package/dist/commands/execution/focus.d.ts +0 -8
  50. package/dist/commands/execution/pseudo-command.d.ts +0 -8
  51. package/dist/commands/index.js +82 -23
  52. package/dist/commands/index.mjs +82 -23
  53. package/dist/commands/navigation/go.d.ts +0 -8
  54. package/dist/commands/navigation/push-url.d.ts +0 -8
  55. package/dist/commands/navigation/scroll-to.d.ts +0 -8
  56. package/dist/commands/templates/render.d.ts +0 -8
  57. package/dist/commands/utility/beep.d.ts +0 -8
  58. package/dist/commands/utility/breakpoint.d.ts +0 -8
  59. package/dist/commands/utility/copy.d.ts +0 -8
  60. package/dist/commands/utility/log.d.ts +0 -8
  61. package/dist/commands/utility/pick.d.ts +0 -8
  62. package/dist/commands/utility/tell.d.ts +0 -8
  63. package/dist/hyperfixi-browser-classic-i18n.js +1 -1
  64. package/dist/hyperfixi-browser-minimal.js +1 -1
  65. package/dist/hyperfixi-browser-standard.js +1 -1
  66. package/dist/hyperfixi-browser.js +1 -1
  67. package/dist/hyperfixi-classic-i18n.js +1 -1
  68. package/dist/hyperfixi-hx-v4.js +1 -1
  69. package/dist/hyperfixi-minimal.js +1 -1
  70. package/dist/hyperfixi-multilingual.js +1 -1
  71. package/dist/hyperfixi-standard.js +1 -1
  72. package/dist/hyperfixi.js +1 -1
  73. package/dist/hyperfixi.mjs +1 -1
  74. package/dist/index.js +441 -143
  75. package/dist/index.min.js +1 -1
  76. package/dist/index.mjs +441 -143
  77. package/dist/lokascript-browser-classic-i18n.js +1 -1
  78. package/dist/lokascript-browser-minimal.js +1 -1
  79. package/dist/lokascript-browser-standard.js +1 -1
  80. package/dist/lokascript-browser.js +1 -1
  81. package/dist/lokascript-multilingual.js +1 -1
  82. package/dist/parser/command-parsers/dom-commands.d.ts +1 -0
  83. package/dist/parser/full-parser.js +47 -1
  84. package/dist/parser/full-parser.mjs +47 -1
  85. package/dist/reference/index.js +6 -5
  86. package/dist/reference/index.mjs +6 -5
  87. package/dist/registry/index.js +50 -6
  88. package/dist/registry/index.mjs +50 -6
  89. package/dist/runtime/command-adapter.d.ts +8 -8
  90. package/package.json +5 -5
  91. package/dist/chunks/browser-modular-BllAMlht.js +0 -2
@@ -1,2 +1,2 @@
1
- var _hyperfixiMultilingualInternal=function(t){"use strict";class e{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return!1;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const n of this.afterExecuteHooks)await n(t,e)}async runOnError(t,e){let n=e;for(const e of this.onErrorHooks){const r=await e(t,n);r instanceof Error&&(n=r)}return n}shouldIntercept(t,e){for(const n of this.interceptCommandHooks)if(n(t,e))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function n(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function r(t){return{ok:!0,value:t}}function i(t){return{ok:!1,error:t}}function o(t){return!0===t.ok}const s="then",a="else",c="end",l="and",u="for",f="while",d="until",h="forever",m="times",p="index",y="in",g="to",b="from",v="with",w="of",E="on",x="event",k="behavior",S="global",T="the",A="start",C=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","open","pick","prepend","process","pseudo-command","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait","for"]),$=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),O=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),j="at end of",N=["into","before","after","at",O,j,"at the start of","at the end of"],R=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"]),L=t=>C.has(t.toLowerCase()),I=t=>$.has(t.toLowerCase()),M=t=>R.has(t.toLowerCase()),P=t=>q.has(t.toLowerCase()),q=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"]),H=new Set(["me","it","you","result","my","its","your"]),B=new Set(["and","or","not","no"]),D=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),V=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"]),F=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"]),U=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),_=new Set([")","]","}",","]);function z(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const i=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function W(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const i=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function Z(t,e){return{prefix:{bp:t,handler:e??((e,n)=>{const r=n.parseExpr(t);return{type:"unaryExpression",operator:e.value,operand:r,argument:r,prefix:!0,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function J(t){return(e,n,r)=>{const i=r.advance();if(!i||!i.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let o=!0;const s=r.peek();return s&&"!"===s.value&&(r.advance(),o=!1),{type:"typeCheckExpression",value:e,typeName:i.value,nullOk:o,negated:t,start:e.start,end:i.end}}}const K=function(...t){const e=new Map;for(const n of t)for(const[t,r]of n){const n=e.get(t);e.set(t,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return e}(new Map([["or",z(10)],["||",z(10)],["and",z(20)],["&&",z(20)],["==",z(30)],["!=",z(30)],["<",z(30)],[">",z(30)],["<=",z(30)],[">=",z(30)],["is",z(30)],["matches",z(30)],["contains",z(30)],["starts with",z(30)],["ends with",z(30)],["does not start with",z(30)],["does not end with",z(30)],["is between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!1,start:t.start,end:o.end}})],["is not between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!0,start:t.start,end:o.end}})],["am between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!1,start:t.start,end:o.end}})],["am not between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!0,start:t.start,end:o.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=!0,t)}}],["where",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:t,right:r,start:t.start,end:r.end}})],["sorted by",z(28,(t,e,n)=>{const r=n.parseExpr(29);let i="asc";const o=n.peek();if(o&&"string"==typeof o.value){const t=o.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),i="asc"):"desc"!==t&&"descending"!==t||(n.advance(),i="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:i,start:t.start,end:r.end}})],["mapped to",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:t,right:r,start:t.start,end:r.end}})],["split by",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:t,right:r,start:t.start,end:r.end}})],["joined by",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:t,right:r,start:t.start,end:r.end}})],["+",{...z(40),...Z(80)}],["-",{...z(40),...Z(80)}],["*",z(50)],["/",z(50)],["%",z(50)],["mod",z(50)],["^",W(60)],["**",W(60)],["as",z(70,(t,e,n)=>{const r=()=>{const t=n.peek();!t||"a"!==t.value&&"an"!==t.value||n.advance();const e=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&e&&"identifier"===e.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(e.name=`${e.name}:${t.value}`,e.end=t.end)}return e};let i=r(),o={type:"asExpression",expression:t,targetType:i,start:t.start,end:i.end??e.end,line:t.line??e.line,column:t.column??e.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const t=r();o={type:"asExpression",expression:o,targetType:t,start:o.start,end:t.end??o.end,line:o.line,column:o.column}}return o})],["not",Z(80)],["!",Z(80)],["no",Z(27)]]),new Map([["===",z(30)],["!==",z(30)],["is not",z(30)],["am",z(30)],["is in",z(30)],["is not in",z(30)],["precedes",z(30)],["does not precede",z(30)],["follows",z(30)],["does not follow",z(30)],["is a",z(30,J(!1))],["is an",z(30,J(!1))],["is not a",z(30,J(!0))],["is not an",z(30,J(!0))],["has",z(30)],["have",z(30)],["match",z(30)],["include",z(30)],["includes",z(30)],["equals",z(30)],["does not contain",z(30)],["does not include",z(30)],["am in",z(30)],["am not in",z(30)],["is really",z(30)],["is not really",z(30)],["is equal",z(30)],["is not equal",z(30)],["contain",z(30)],["do not contain",z(30)],["does not contains",z(30)],["do not match",z(30)],["does not match",z(30)],["is equal to",z(30)],["is not equal to",z(30)],["is really equal to",z(30)],["is not really equal to",z(30)],["really equals",z(30)],["is greater than",z(30)],["is less than",z(30)],["is greater than or equal to",z(30)],["is less than or equal to",z(30)],["in",z(30)],["of",W(30)],["really",z(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["some",Z(80)]]),new Map([["=",W(5)]])),X=new Map,G=new Map,Y=new Map,Q=new Set,tt=new Set,et=new Set,nt=new Set;function rt(t){return X.get(t.toLowerCase())}function it(t){return Y.get(t)}function ot(t,e){if(0!==tt.size)for(const n of tt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function st(t,e,n){if(0!==et.size)for(const r of et)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function at(t,e){if(0!==nt.size)for(const n of nt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function ct(t,e,n){if(t.globals.set(e,n),0!==Q.size)for(const r of Q)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}const lt=new Map,ut=new WeakMap;function ft(t){let e=ut.get(t);return e||(e=new Map,ut.set(t,e)),e}function dt(t){return t.owner||(t.me instanceof Element?t.me:null)}function ht(t,e){const n=dt(t);if(n)return at(e,t),ft(n).get(e)}function mt(t,e,n){const r=dt(t);r&&(ft(r).set(e,n),st(e,n,t))}function pt(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||lt,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function yt(t){if(!t)return pt();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=pt(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}function gt(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function bt(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function vt(t){if(null==t)return 0;if("number"==typeof t)return isFinite(t)?t:0;if("string"==typeof t)return parseFloat(t);if("boolean"==typeof t)return t?1:0;if(Array.isArray(t))return t.length;if("object"==typeof t){if("length"in t&&"number"==typeof t.length)return t.length;if("function"==typeof t.valueOf){const e=t.valueOf();if("number"==typeof e)return e}return NaN}return 0}function wt(t,e,n){return"element"===n?ht(e,t):"global"===n&&e.globals&&e.globals.has(t)?e.globals.get(t):"global"!==n&&e.locals&&e.locals.has(t)?(at(t,e),e.locals.get(t)):e.globals&&e.globals.has(t)?e.globals.get(t):e.variables&&e.variables.has(t)?e.variables.get(t):"global"===n&&e.locals&&e.locals.has(t)?(at(t,e),e.locals.get(t)):"undefined"!=typeof window&&t in window?window[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}function Et(t,e,n,r){if("element"!==r){if("global"===r)return ct(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void ct(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void st(t,e,n);if(n.globals&&n.globals.has(t))return ct(n,t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(n.variables&&n.variables.has(t))n.variables.set(t,e);else{if("undefined"!=typeof window&&t in window)return window[t]=e,void ct(n,t,e);n.locals.set(t,e),st(t,e,n)}}else mt(n,t,e)}function xt(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:wt(t,e)}function kt(t,e,n){return n||"string"!=typeof e||!e.startsWith("#")?t:Array.isArray(t)?t[0]??null:t}function St(t){if("undefined"==typeof document)throw Error("DOM not available");const e=Array.from(document.querySelectorAll(t)).filter(t=>gt(t));if(!e.length)throw Error(`No elements: "${t}"`);return e}function Tt(t){if(gt(t))return[t];if(Array.isArray(t)){const e=t.filter(gt);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(gt);return e.length>0?e:null}return null}const At=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,n]of this.types)if(n.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),n=this.types.get(e);return n?.hyperscriptType??"unknown"}coerce(t,e,n){const r=this.types.get(e);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(r.isType(t))return t;if(this.config.cacheCoercions){const n=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(t),o=r.coerceFrom?.[i];if(o){const r=o(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(t,e){const n=this.types.get(e);if(!n)return!1;if(n.isType(t))return!0;const r=this.inferType(t);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(t,e){const n=this.types.get(e);return n&&(t===e||n.coerceFrom?.[t])?{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:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e||"false"!==e&&"no"!==e&&"0"!==e&&""!==e&&e.length>0},Number:t=>0!==t,Null:()=>!1,Undefined:()=>!1,Array:t=>!!Array.isArray(t)&&t.length>0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const n=t;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,n)=>{e[n+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Ct(t){const e=At.get("String");return e?e.isType(t):"string"==typeof t}function $t(t){const e=At.get("Number");return e?e.isType(t):"number"==typeof t}function Ot(t){const e=At.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function jt(t){const e=At.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Nt(t){const e=At.get("Function");return e?e.isType(t):"function"==typeof t}function Rt(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Lt(t){return t instanceof Element}function It(t){return t instanceof HTMLElement}const Mt=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Pt(t,e){return Mt.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const qt={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return!1;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>Rt(t)?t.tabIndex:void 0,hidden:t=>Rt(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,next:t=>t.nextElementSibling,previous:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function Ht(t,e){if(e.startsWith("*"))return function(t,e){if(!It(t))return;if(e.startsWith("computed-"))return getComputedStyle(t).getPropertyValue(e.slice(9))||"";const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}(t,e.slice(1));if(e.startsWith("computed-")){const n=e.slice(9);return It(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return Pt(t,e.slice(1));const n=qt[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Pt(t,e);const r=t[e];return Nt(r)?r.bind(t):r}const Bt={1:"one",2:"two",3:"three",4:"four",5:"five"};function Dt(t,e,n,r){if(t.length!==e){return`${n} requires exactly ${i=e,Bt[i]??i+""} argument${1===e?"":"s"}${r?` (${r})`:""}`}var i;return null}function Vt(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function Ft(t,e,n){return Dt(t,1,e,n)??Vt(t,0,e,n)}function Ut(t,e){return Dt(t,2,e,"left, right")}function _t(){return null}function zt(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function Wt(t,e,n,r,i){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${i?` (${i})`:""}`:null}const Zt={conversions:{dynamicResolvers:[]}},Jt={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":Ct(t)?t:jt(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Ot(t))return t;if(null==t)return!1;if(Ct(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return $t(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if($t(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if($t(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!$t(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=Jt.Number(t);return Math.trunc(e)},Float:t=>{const e=Jt.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(Ct(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return new Date(e,n-1,r)}return new Date(t)},JSON:t=>{if(!Ct(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(jt(t))return t;if(Ct(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{const e=document.createDocumentFragment(),n=Array.isArray(t)||t instanceof NodeList?Array.from(t):[t];for(const t of n)if(t instanceof Node)e.append(t);else{const n=document.createElement("template");n.innerHTML=null==t?"":t+"",e.append(n.content)}return e},HTML:t=>Ct(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:Jt.String(t)).join(""):t instanceof Element?t.outerHTML:Jt.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return function(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Kt(n);void 0!==t&&(void 0!==e[n.name]?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(t)):e[n.name]=t)}}),e}(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Kt(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?Jt.Values(t,e):t;if(!jt(n))return"";const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return""+r},Set:t=>new Set(t),Map:t=>new Map(Object.entries(t??{})),Keys:t=>t instanceof Map?Array.from(t.keys()):Object.keys(t??{}),Entries:t=>t instanceof Map?Array.from(t.entries()):Object.entries(t??{}),Reversed:t=>Array.from(t).reverse(),Unique:t=>[...new Set(t)],Flat:t=>Array.from(t).flat(),"Values:Form":(t,e)=>{const n=Jt.Values(t,e);return Jt.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=Jt.Values(t,e);return JSON.stringify(n)}};function Kt(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const Xt={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function Gt(t,e,n){if("string"!=typeof e)throw Error("Conversion type must be a string");if(e.startsWith("Fixed")){const{precision:n}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):0}:{}}(e);return Jt.Number(t).toFixed(n??0)}if(null==t)return t;let r=Jt[e];if(r)return r(t,n);const i=Xt[e.toLowerCase()];if(i&&(r=Jt[i],r))return r(t,n);const o=Zt.conversions[e];if("function"==typeof o)return o(t,n);for(const n of Zt.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Yt={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Gt(n,r,t)},validate:t=>Dt(t,2,"as","value, type")??Vt(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[n,r]=e;if(!Ct(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return Ct(n);case"number":return $t(n)&&!isNaN(n);case"boolean":return Ot(n);case"object":return jt(n);case"array":return Array.isArray(n);case"function":return Nt(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||jt(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>Dt(t,2,"is","value, type")??Vt(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>Dt(t,1,"async","expression")}},Qt=new Set(["__proto__","constructor","prototype"]);function te(t,e){if(t instanceof Element)return Ht(t,e);if(jt(t)){if(Qt.has(e))return;return t[e]}return t[e]}function ee(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return!1;e=Array.from(t)}return 0!==e.length&&e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const ne={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[n,r]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return ee(n)&&!(r in n)?Array.from(n,t=>te(t,r)):te(n,r)}},validate:t=>Dt(t,2,"possessive","element, property")??Vt(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[n]=e;if(t.me){if("string"!=typeof n)throw Error("Property name must be a string");if(t.me instanceof Element)return Ht(t.me,n);if(jt(t.me)){if(Qt.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>Ft(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[n]=e;if(null==t.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=t.it;if(r instanceof Element)return Ht(r,n);if(jt(r)){if(Qt.has(n))return;return r[n]}return r[n]},validate:t=>Ft(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[n]=e;if(t.you){if("string"!=typeof n)throw Error("Property name must be a string");if(t.you instanceof Element)return Ht(t.you,n);if(jt(t.you)){if(Qt.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>Ft(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[n,r]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Ht(r,n);if(jt(r)){if(Qt.has(n))return;return r[n]}return r[n]}},validate:t=>Dt(t,2,"of","property, object")??Vt(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");const i=r||t.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:t=>Wt(t,1,2,"attribute","attributeName, optional element")??Vt(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[n,r,i]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const o=i||t.me;return!!(o&&o instanceof Element)&&o.getAttribute(n)===r},validate:t=>Wt(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Vt(t,0,"attributeWithValue","attribute name")??Vt(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:t=>Ft(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:t=>Ft(t,"idReference","idValue")}};function re(t){return Array.isArray(t)?t:null==t?[]:"string"==typeof t?[t]:t instanceof NodeList||t instanceof HTMLCollection||"number"==typeof t.length?Array.from(t):[t]}var ie;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(ie||(ie={}));const oe=new Set(["+","-","*","/","mod"]),se=new Set(["ms","s","seconds","minutes","hours","days"]);function ae(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function ce(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function le(t){const e=t.input,n=e.length;for(;n>t.position;){const n=e[t.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;ce(t)}}function ue(t,e,n,r,i){const o=r??t.position-n.length,s=t.position;let a=t.column-n.length;if(void 0!==r){a=1;let e=-1;for(let n=0;r>n;n++)"\n"!==t.input[n]&&"\r"!==t.input[n]||(e=n);a=r-e}const c={kind:e,value:n,start:o,end:s,line:fe(t,o),column:a};t.tokens.push(c)}function fe(t,e){let n=1;for(let r=0;e>r&&t.input.length>r;r++){const e=t.input[r];"\n"===e?n++:"\r"===e&&(n++,t.input.length>r+1&&"\n"===t.input[r+1]&&r++)}return n}function de(t){const e=t.position;let n="";for(ce(t),ce(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=ce(t);ue(t,ie.COMMENT,"--"+n,e)}function he(t){const e=t.position,n=ce(t);let r=n;for(;t.input.length>t.position;){const e=ce(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=ce(t))}ue(t,ie.STRING,r,e)}function me(t){const e=t.position;ce(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){ce(t);break}if("\\"===e){if(ce(t),t.input.length>t.position){const e=ce(t);switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=e}}}else n+=ce(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);ue(t,ie.TEMPLATE,n,e)}function pe(t){const e=t.position;let n=ce(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=ce(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=ce(t),"}"===e)break}ue(t,ie.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)ce(t),t.input.length>t.position&&(n+=ce(t));else{if(!ke(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=ce(t)}}ue(t,ie.SELECTOR,n,e)}}function ye(t){const e=t.position;if(Se(t))return void function(t,e){const n=t.input;let r="",i=0,o="";for(;n.length>t.position;){const e=n[t.position];if(o)r+=ce(t),e===o&&(o="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=ce(t);if(n.length>t.position&&(r+=ce(t)),i--,0>=i)break;continue}let e=!1,o="";for(;n.length>t.position;){const i=n[t.position];if(o)r+=ce(t),i===o&&(o="");else if('"'!==i&&"'"!==i){if(">"===i){e="/"===n[t.position-1],r+=ce(t);break}r+=ce(t)}else o=i,r+=ce(t)}if(e||i++,0>=i)break;continue}r+=ce(t)}else o=e,r+=ce(t)}ue(t,ie.SELECTOR,r,e)}(t,e);let n="";for(n+=ce(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=ce(t),"/"===e&&">"===r){n+=ce(t);break}}ue(t,ie.SELECTOR,n,e)}function ge(t){const e=t.position;let n=ce(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!ke(e)&&"_"!==e&&"-"!==e)break;n+=ce(t)}ue(t,ie.SYMBOL,n,e)}function be(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===ae(t,1))return n="'s",ce(t),ce(t),void ue(t,ie.OPERATOR,n,e);const i=t.input.substring(t.position,t.position+2),o=t.input.substring(t.position,t.position+3);["===","!=="].includes(o)?(n=o,ce(t),ce(t),ce(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,ce(t),ce(t)):n=ce(t),ue(t,ie.OPERATOR,n,e)}function ve(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=ce(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(i+=ce(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=ce(t)}if(r>t.position){const e=n[t.position];if("e"===e||"E"===e){const e=r>t.position+1?n[t.position+1]:"",o=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">o||o>"9"))for(i+=ce(t),"+"!==n[t.position]&&"-"!==n[t.position]||(i+=ce(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=ce(t)}}}const o=t.position;let s="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;s+=ce(t)}se.has(s)?ue(t,ie.TIME,i+s,e):(t.position=o,ue(t,ie.NUMBER,i,e))}function we(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;i+=ce(t)}const o=function(t,e,n){const r=e.toLowerCase(),i=t.position;if("'s"===e||"'s"===e)return!1;const o=t.tokens[t.tokens.length-1];if(o&&(o.kind===ie.IDENTIFIER||o.kind===ie.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}le(t);let s="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=ce(t)}if(s){const e=s.toLowerCase(),i=`${r} ${e}`,o=function(t,e,n,r){const i=e.toLowerCase(),o=n.toLowerCase();if("at"===i){const e=t.position;if("the"===o){le(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=ce(t)}const i=n.toLowerCase();if("start"===i||"end"===i){le(t);let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;e+=ce(t)}if("of"===e.toLowerCase())return ue(t,ie.IDENTIFIER,`at the ${i} of`,r),!0}return t.position=e,!1}if("start"===o||"end"===o){le(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=ce(t)}return"of"===n.toLowerCase()?(ue(t,ie.IDENTIFIER,`at ${o} of`,r),!0):(t.position=e,!1)}}return!1}(t,r,e,n);if(o)return!0;const a=function(t,e,n){const r=t.position;let i=`${e} ${n}`,o=t.position;const s=[e,n];for(;8>s.length&&(le(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;e+=ce(t)}if(!e)break;s.push(e.toLowerCase());const n=s.join(" ");D.has(n)&&(i=n,o=t.position)}return D.has(i)&&i!==`${e} ${n}`?(t.position=o,i):(t.position=r,null)}(t,r,e);if(a)return ue(t,ie.OPERATOR,a,n),!0;if(D.has(i))return ue(t,ie.OPERATOR,i,n),!0}return D.has(r)?(t.position=i,ue(t,ie.OPERATOR,e,n),!0):(t.position=i,!1)}(t,i,e);if(o)return;const s=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||B.has(e)||oe.has(t)||oe.has(e)||D.has(e)?ie.OPERATOR:ie.IDENTIFIER}(i);ue(t,s,i,e)}function Ee(t){const e=t.position,n=t.input,r=n.length;ce(t);let i="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;i+=ce(t)}ue(t,ie.IDENTIFIER,i,e)}function xe(t){return/[a-zA-Z]/.test(t)}function ke(t){return/[a-zA-Z0-9]/.test(t)}function Se(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=t.position+1,i="";for(;e.length>r&&/[a-zA-Z0-9-]/.test(e[r]);)i+=e[r],r++;return i.length>0&&-1!==e.indexOf("</"+i+">",r)}function Te(t){if(Se(t))return!0;let e=t.position+1,n=!1;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(ke(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,e++;else{if(" "!==r&&"\t"!==r)return!1;e++}if(e-t.position>50)return!1}return!1}function Ae(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const Ce=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),$e=Ce,Oe=Ce,je=Ce,Ne=Ce,Re=(...t)=>{$e&&console.log("\ud83d\udd27",...t)},Le=(...t)=>{Oe&&console.log("\ud83c\udfaf",...t)},Ie=(...t)=>{je&&console.log("\ud83d\udcdd",...t)},Me=(...t)=>{Ne&&console.log("\ud83d\ude80",...t)};let Pe=!1,qe=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(Pe=!0,qe=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let He={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class Be{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(Be.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const n=t.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(t)}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(t,this.language),i=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const o=r.confidence>=this.confidenceThreshold&&!!r.command,s=!o&&r.confidence>0;if(Pe){const e={};if(r.command?.roles)for(const[t,n]of r.command.roles)e[t]=n.value;const a={input:t.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:o,fallbackTriggered:s,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(t){if(!Pe)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),i=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),qe){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});qe.dispatchEvent(e)}}(a),n=a,He.totalParses++,n.semanticSuccess?He.semanticSuccesses++:n.fallbackTriggered?He.semanticFallbacks++:He.traditionalParses++,He.confidenceHistory.push(n.confidence),He.confidenceHistory.length>100&&He.confidenceHistory.shift(),He.averageConfidence=He.confidenceHistory.reduce((t,e)=>t+e,0)/He.confidenceHistory.length}return o?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:!1,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var n}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const n=this.analyzer.buildCommandNode?.(e);if(!n)throw Error(`Semantic analyzer cannot build an AST node for '${e.name}' (no buildCommandNode wired \u2014 see createSemanticAdapter's buildAST dep)`);return n}buildRepeatCommandNode(t){const e=[],n={},r=t.roles.get("loopType");r&&e.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("patient");"for"==(r?r.value+"":"")&&i&&e.push({type:"identifier",name:"expression"===i.type&&i.raw||i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("event");o&&e.push({type:"string",value:o.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("source");s&&e.push(this.semanticValueToExpression(s));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],n=t.roles.get("destination");if(n)if("property-path"===n.type){const t=n;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(n));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=t.roles.get("patient");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],n=t.roles.get("condition");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:t.name,args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const n=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},r=()=>{n();const r=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(r,e)},i=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(o()),n();","===t[e];)e++,n(),r.push(o()),n();return")"===t[e]&&e++,r},o=()=>{n();const o=r();if(!o)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let s={type:"identifier",name:o,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const o=t[e];if("."===o){e++;const t=r();t&&(s={type:"memberExpression",object:s,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==o)break;s={type:"callExpression",callee:s,arguments:i(),start:0,end:0,line:1,column:0}}}return s};return o()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function De(t){return t.kind===ie.IDENTIFIER&&C.has(t.value.toLowerCase())}function Ve(t){return t.kind===ie.IDENTIFIER&&F.has(t.value.toLowerCase())}function Fe(t){return t.kind===ie.IDENTIFIER&&V.has(t.value.toLowerCase())}function Ue(t){return t.kind===ie.IDENTIFIER&&H.has(t.value.toLowerCase())}function _e(t){return D.has(t.value.toLowerCase())}function ze(t){return t.kind===ie.IDENTIFIER}function We(t){return t.kind===ie.SELECTOR}function Ze(t){return t.kind===ie.SELECTOR&&!t.value.startsWith("<")}function Je(t){return t.kind===ie.STRING||t.kind===ie.NUMBER||t.kind===ie.TEMPLATE}function Ke(t){return t.kind===ie.IDENTIFIER}function Xe(t){return t.kind===ie.TIME}function Ge(t){return t.kind===ie.SYMBOL}function Ye(t){return t.kind===ie.COMMENT}function Qe(t){if(t.kind!==ie.IDENTIFIER)return!1;const e=t.value.toLowerCase();return!(C.has(e)||F.has(e)||V.has(e)||H.has(e))}function tn(t){return t.kind===ie.STRING}function en(t){return t.kind===ie.NUMBER}function nn(t){if(t.kind===ie.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function rn(t){return t.kind===ie.TEMPLATE}function on(t){return t.kind===ie.SELECTOR&&t.value.startsWith("<")}function sn(t){return t.kind===ie.SELECTOR&&t.value.startsWith("#")}function an(t){return t.kind===ie.SELECTOR&&t.value.startsWith(".")}function cn(t){return t.kind===ie.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function ln(t){if(t.kind!==ie.OPERATOR)return!1;const e=t.value.toLowerCase();return!B.has(e)&&!D.has(e)}function un(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function fn(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function dn(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function hn(t,e,n,r){return{type:"binaryExpression",operator:t,left:e,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function mn(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function pn(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function yn(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function gn(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function bn(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function vn(t,e,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...n&&{source:n}}],start:t.start,end:t.end,line:t.line,column:t.column}}Be.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const wn=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"prepend",keywords:["to"],syntax:"prepend <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"throw",keywords:[],syntax:"throw <error>"}];function En(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const xn=[s,l,a,c];function kn(t,e=[]){if(t.isAtEnd())return!0;for(const e of xn)if(t.check(e))return!0;for(const n of e)if(t.check(n))return!0;return!!t.checkIsCommand()}function Sn(t,e=[]){if(!kn(t,e))return t.parseExpression()}function Tn(t,e,n){return!!t.check(e)&&(t.advance(),n.push(t.createIdentifier(e)),!0)}function An(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function Cn(t,e){return!!t.check(e)&&(t.advance(),!0)}function $n(t){const e=t.savePosition();let n;if(t.checkIdentifierLike()){const r=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=r):t.restorePosition(e)}const r=t.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class On{constructor(t){this.args=[],this.isBlocking=!1,this.name=t}static from(t){const e=new On(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new On(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new On(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=!0){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new On(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function jn(t,e){const n=[];let r="";const i=t.peek().start||0,o=t.peek().line||1,s=t.peek().column||1;if(t.checkIdentifierLike()){for(r=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),r+=":",t.checkIdentifierLike()&&(r+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const{name:n,value:r}=$n(t);if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),n.push({type:"functionCall",name:r,args:e,start:i,end:t.getPosition().end,line:o,column:s})}else n.push({type:"string",value:r,start:i,end:t.getPosition().end,line:o,column:s})}const a=[...n];for(;!kn(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}const e=t.savePosition(),n=t.parsePrimary();n&&a.push(n),t.savePosition()===e&&t.advance()}return On.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Nn(t,e){const n=[];if(t.check(T)){const e=t.advance();if(n.push({type:"identifier",name:T,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(x)){const e=t.advance();n.push({type:"identifier",name:x,start:e.start,end:e.end,line:e.line,column:e.column})}}return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Rn(t,e){const n=[],r=()=>t.check(c)||e&&t.check(a);for(;!t.isAtEnd()&&!r();){if(Ye(t.peek())){t.advance();continue}if(!t.checkIsCommand()&&!t.isCommand(t.peek().value))break;t.advance();const e=t.parseCommand();e&&n.push(e),(t.check(s)||t.check(l)||t.check(","))&&t.advance()}return n}const Ln=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function In(t,e,n){return null!==e&&!Ln.has(e.value?.toLowerCase?.()??"")&&(t.checkIsCommand()||t.isCommand(n.value?.toLowerCase()))}function Mn(t,e){const n=[];let r=!1;const i=t.savePosition();let o=null;for(let n=0;500>n&&!t.isAtEnd();n++){const n=t.peek();if(n.value===s){r=!0;break}if(n.value===c||n.value===k||"def"===n.value||n.value===E)break;if(void 0!==n.line&&n.line!==e.line&&In(t,o,n))break;Ye(n)||(o=n),t.advance()}t.restorePosition(i);let l=!1;if(!r){const n=t.savePosition(),r=e.line,i=100;let o=!1,s=null;for(;!t.isAtEnd()&&i>t.current-n;){const e=t.peek(),n=e.value?.toLowerCase();if(o&&void 0!==e.line&&e.line!==r)break;if(n===k||"def"===n||n===E)break;if(n===a||n===c){e.line===r&&(l=!0);break}if(In(t,s,e)){if(void 0!==e.line&&e.line!==r){l=!0;break}o=!0}Ye(e)||(s=e),t.advance()}t.restorePosition(n)}const u=r||l;let f;if(u)f=t.parseExpression();else{const n=[],r=20;let i=0,o=!0;for(;!t.isAtEnd()&&!t.check(s)&&(o||!t.checkIsCommand()&&!t.isCommand(t.peek().value))&&r>i;){o=!1;const e=t.savePosition();n.push(t.parseLogicalAnd()),t.savePosition()===e&&t.advance(),i++}if(0===n.length)throw Error("Expected condition after if/unless");f=1===n.length?n[0]:{type:"expression",tokens:n,start:n[0].start,end:n[n.length-1].end,line:e.line,column:e.column}}if(n.push(f),u){Cn(t,s);const r=Rn(t,!0);if(0===r.length&&t.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");n.push(mn(r,{start:e.start,end:t.getPosition().end,line:e.line,column:e.column}));let i=!1;if(t.check(a))if(t.advance(),t.check("if")){const e=t.peek();t.advance();const r=Mn(t,e);n.push(mn([r],{start:e.start,end:t.getPosition().end,line:e.line,column:e.column})),i=!0}else{const r=Rn(t,!1);n.push(mn(r,{start:e.start,end:t.getPosition().end,line:e.line,column:e.column}))}i||t.consume(c,"Expected 'end' after if block")}else{if(!t.checkIsCommand()&&!t.isCommand(t.peek().value))throw Error("Expected command after if condition in single-line form");{t.advance();const r=t.parseCommand();n.push(mn([r],{start:e.start,end:t.getPosition().end,line:e.line,column:e.column}))}}return On.from(e).withArgs(...n).endingAt(t.getPosition()).build()}function Pn(t,e){const n=[],r={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(n.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();n.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();r.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const i=On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const qn=new Set(["my","its","your"]);function Hn(t){const e={};if(Cn(t,u)){const n=t.parseExpression();return n&&(e.for=n),e}if(!t.check(d))return e;t.advance();const n=t.peek();if(!n||!ze(n))return e;t.advance();let r=n.value;if(t.check(":")){t.advance();const e=t.peek();e&&ze(e)&&(t.advance(),r=`${r}:${e.value}`)}if(e.until={type:"literal",value:r,raw:r},Cn(t,b)){const n=Sn(t);n&&(e.from=n)}return e}function Bn(t,e){const n=[],r=Sn(t,[b]);r&&n.push(r),Tn(t,b,n);const i=Sn(t);return i&&n.push(i),On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Dn(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const r=Sn(t,[l]);if(r&&"binaryExpression"===r.type&&"and"===r.operator)r.left&&n.push(r.left),n.push(t.createIdentifier("and")),r.right&&n.push(r.right);else{r&&n.push(r),Tn(t,l,n);const e=Sn(t,[b,E,u]);e&&n.push(e)}if(An(t,[b,E],n)){const e=Sn(t);e&&n.push(e)}return On.fromIdentifier(e).withArgs(...n).withModifiers(Hn(t)).endingAt(t.getPosition()).build()}const r=Sn(t,[b,E]);if(r&&n.push(r),An(t,[b,E],n)){const e=Sn(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),On.fromIdentifier(e).withArgs(...n).withModifiers(Hn(t)).endingAt(t.getPosition()).build()}function Vn(t,e){const n=t.parseExpression();if(!n)return t.addError("Put command requires content expression"),null;const r=t.peek();if(!r||!N.includes(r.value))return t.addError(`Expected operation keyword (${N.join(", ")}) after put expression, got: ${r?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=O:"at end of"===o||"at the end of"===o?i=j:"at"===i&&(t.check(A)||t.check(T)?(Cn(t,T),t.check(A)&&(t.advance(),t.check(w)&&(t.advance(),i=O))):t.check(c)&&(t.advance(),t.check(w)&&(t.advance(),i=j)));const s=t.parseExpression();return s?On.fromIdentifier(e).withArgs(n,t.createIdentifier(i),s).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Fn=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Un(t,e){const n=t.savePosition();let r=null,i=[];try{r=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end}}(t)??function(t){if(!t.check(S)&&!t.check("local"))return null;const e=t.advance(),n=t.advance();return{type:"identifier",name:n.value,scope:e.value,start:e.start,end:n.end}}(t)??function(t){if(!t.check(T))return null;const e=t.savePosition();t.advance();const n=t.parseExpression();if(!n)return t.restorePosition(e),null;if("binaryExpression"===n.type&&n.operator===w){const t=n.left,e=n.right;return bn(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(g)?n:(t.restorePosition(e),null)}(t),r||(r=t.parseExpression())}catch{t.restorePosition(n),r=null}if(!r){const e=function(t){if(t.match(":")){const e=t.advance();return{expression:{type:"identifier",name:e.value,scope:"element",start:e.start,end:e.end},tokens:[]}}const e=[];for(;!(t.isAtEnd()||t.check(g)||t.check(s)||t.check(l)||t.check(a)||t.check(c));)e.push(t.parsePrimary());if(0===e.length)return{expression:null,tokens:[]};if(e.length>=4){const t=(t,e)=>t[e];if(t(e[0],"value")===T&&t(e[2],"value")===w){const n=e[1],r=e[3];return{expression:bn(dn(t(n,"value")||t(n,"name")||"",{start:n.start??0,end:n.end??0,line:n.line??1,column:n.column??1}),{type:"idSelector"===r.type?"idSelector":"cssSelector",value:t(r,"value")||t(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:e[0].start??0,end:r.end??0,line:e[0].line??1,column:e[0].column??1}),tokens:[]}}}return 1===e.length?{expression:e[0],tokens:[]}:{expression:null,tokens:e}}(t);r=e.expression,i=e.tokens}if(!t.check(g)){const e=t.isAtEnd()?"end of input":t.peek().value;throw Error("Expected 'to' in set command, found: "+e)}t.advance();const o=t.parseExpression()??t.parsePrimary();let u;var f;t.check(E)&&(f=t.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||_n.has(f.value))&&(t.advance(),u=Sn(t));const d=[];r?d.push(r):i.length>0&&d.push(...i),d.push(t.createIdentifier(g)),o&&d.push(o);const h=On.fromIdentifier(e).withArgs(...d);return u&&h.withModifier("on",u),h.endingAt(t.getPosition()).build()}const _n=new Set(["me","my","it","its","you","your","yourself"]),zn=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]);function Wn(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Zn(t,e){const n=[];for(;!kn(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Jn(t){const e=t.peek();if("/"===e.value)return!0;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return!1}const Kn=new Set(["{",")"]);function Xn(t){const e=t.savePosition(),n=t.peek();let r="",i=null;for(;!t.isAtEnd();){const e=t.peek();if(i&&e.start!==i.end)break;if("$"===e.value&&"{"===t.peekAt(1)?.value){t.advance();let n=t.advance(),o=1;for(;!t.isAtEnd()&&o>0;)n=t.advance(),"{"===n.value?o++:"}"===n.value&&o--;r+=t.getInputSlice(e.start,n.end),i=n;continue}if(Kn.has(e.value))break;i=t.advance(),r+=i.value}if(!r||"/"===r)return t.restorePosition(e),null;const o={start:n.start,end:i?i.end:n.end,line:n.line,column:n.column};return r.includes("${")?{type:"templateLiteral",value:r,...o}:{type:"literal",value:r,raw:r,...o}}function Gn(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function Yn(t){const e=[],n=t.getPosition();do{if(!t.checkIdentifierLike())break;const n=t.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};t.consume(":","Expected ':' after property name in fetch named arguments");const i=t.parsePrimary();i&&e.push({key:r,value:i})}while(t.match(",")&&!t.isAtEnd());const r=t.getPosition();return{type:"objectLiteral",properties:e,start:n.start,end:r.end,line:n.line,column:n.column}}const Qn=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class tr{constructor(t,e,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new Be({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=n||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors],t.recovered=!0),t}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 t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:!1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}const t=this.peek(),e=t&&rt(t.value)?t.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==e){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const t=this.peekAt(1);if(null!==t&&("init"===t.value||"on"===t.value||"def"===t.value||void 0!==rt(t.value))){this.advance();continue}}if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def")){const e=this.peek(),n=e?rt(e.value):void 0;if(n){const e=this.advance(),r=n(this.getContext(),e);r&&t.push(r);continue}break}{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}}return this.isAtEnd()?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}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){Ie("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];Ie(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){Ie(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(Ie("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,Ie(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),Ie(`\u2705 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 Ie("\u26a0\ufe0f PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};Ie("\u2705 PARSER: No more event handlers, at end of input");break}}return Ie(`\u2705 PARSER: Finished parsing, creating Program node with ${e.length} statements`),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}}return this.isAtEnd()?this.error?{success:!1,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const t=this.peek();return n&&["number","string","identifier"].includes(t.kind)?this.addError(`Unexpected token: ${t.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+t.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,warnings:this.warnings}}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,n=this.prattCache.get(e);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),i=tr.PRATT_TABLE.get(r.value);let o;if(i?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();o=i.prefix.handler(t,this.makePrattContext())}else o=this.parseCall();for(;!this.isAtEnd();){const e=this.peek();if(60>=t){const t=this.tryParseStringPostfix(o,e);if(t){o=t;continue}}const n=tr.PRATT_TABLE.get(e.value);if(!n?.infix){if(U.has(e.value)||_.has(e.value))break;break}const[r]=n.infix.bp;if(t>r)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(t){Ie("arrow body discarded after error:",t instanceof Error?t.message:t+"")}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),o}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),o}const i=this.advance();if(this.isAtEnd()&&!tr.POSTFIX_UNARY_OPERATORS.has(i.value))return this.addError(`Expected expression after '${i.value}' operator`),o;o=n.infix.handler(o,i,this.makePrattContext())}return this.prattCache.set(e,{node:o,endPos:this.current}),o}tryParseStringPostfix(t,e){const n=e.value;let r=null;if(Qn.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const i=this.advance();return{type:"stringPostfix",expression:t,unit:r,start:t.start,end:i.end,line:t.line,column:t.column}}canStartOperand(t){if(!t)return!1;const e=t.value;return!U.has(e)&&!_.has(e)&&("number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(e))}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return!e||U.has(e.value)||_.has(e.value)},atEnd:()=>t.current>=t.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):L(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):M(t)}createCommandFromIdentifier(t){const e=[],n=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:!1,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return I(t)}parseCompoundCommand(t){return function(t,e){switch(e.name.toLowerCase()){case"put":return Vn(t,e);case"trigger":case"send":return jn(t,e);case"remove":return Bn(t,e);case"take":return function(t,e){const n=[],r={},i=Sn(t,[b,u]);if(i&&n.push(i),t.check(b)){Tn(t,b,n);const e=Sn(t,[u]);e&&n.push(e)}if(Cn(t,u)){const e=Sn(t);e&&(r.for=e)}return On.fromIdentifier(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(t,e);case"toggle":return Dn(t,e);case"set":return Un(t,e);case"halt":return Nn(t,e);case"measure":return Pn(t,e);case"js":return function(t,e){const n=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&n.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const r=t.peek().start,i=function(t,e){const n=t.getInputSlice(e);if(!n)return e;let r=0;for(;n.length>r;){const t=n[r];if("'"!==t&&"\u2019"!==t&&"\u2018"!==t)if('"'!==t)if("`"!==t)if("/"===t&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===t&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==t&&"E"!==t||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return e+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==t;)"\\"===n[r]&&r++,r++;r++}}return e+n.length}(t,r);for(;!t.isAtEnd()&&!t.check(c)&&t.peek().start<i;)t.advance();t.consume(c,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(r,i).trim(),start:e.start,end:t.getPosition().end},s={type:"arrayLiteral",elements:n.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return On.fromIdentifier(e).withArgs(o,s).endingAt(t.getPosition()).build()}(t,e);case"go":return function(t,e){const n=[];for(;!kn(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(zn.has(r)){t.advance(),n.push(Wn(r,e));continue}if(Jn(t)){const r=Xn(t);if(r){n.push(r);continue}t.advance(),n.push(Wn(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(Wn(e.value,e));continue}if("number"===e.kind){t.advance();const r=t.peek();if(t.isAtEnd()||"px"!==r.value||r.start!==e.end)n.push({type:"literal",value:Number(e.value),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column});else{const r=t.advance();n.push(Wn(e.value+"px",{...e,end:r.end}))}continue}const i=t.current;if(n.push(t.parsePrimary()),t.current===i)break}return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(t,e);case"tell":return function(t,e){const n=t.parseExpression();if(!n)throw Error("tell command requires a target expression");const r=[];for(;!t.isAtEnd();){if(t.checkIsCommand()){try{t.advance();const e=t.parseCommand();if(!e)break;r.push(e)}catch{break}if(t.match(l)||t.match(s))continue;if(t.check(a)||t.check(c))break;if(t.checkIsCommand())continue;break}break}if(0===r.length)throw Error("tell command requires at least one command after the target");return On.fromIdentifier(e).withArgs(n,...r).endingAt(t.getPosition()).build()}(t,e);case"pick":return function(t,e){const n=On.fromIdentifier(e);Cn(t,T);const r=t.peek().value,i=t=>({type:"literal",value:t,start:e.start,end:e.end}),o=()=>{if(!t.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return t.parseExpression()};if("first"===r){t.advance();const e=t.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("last")).withModifier("count",e).endingAt(t.getPosition()).build()}if("random"===r){let e;t.advance(),t.check("of")||t.check("from")||(e=t.parsePrimary());const r=o(),s=n.withArgs(r).withModifier("variant",i("random"));return e&&s.withModifier("count",e),s.endingAt(t.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let e,r;t.advance(),t.match("at","from"),e=t.match("start")?i("start"):t.parsePrimary();let s=!1;(t.match("to")||t.match(".."))&&(t.match("end")?s=!0:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=o(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",e).withModifier("rangeMode",i(a));return s?l.withModifier("rangeEnd",i("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let s;t.matchOperator("|")&&(s=t.advance().value);const a=o(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",e);return s&&c.withModifier("flags",i(s)),c.endingAt(t.getPosition()).build()}return Zn(t,e)}(t,e);case"start":return function(t,e){if(!t.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!t.match("transition"))throw Error("start view: expected 'transition'");const n={};if(t.match("using")){const e=t.parsePrimary();n.transitionName=e}const r=t.parseCommandListUntilEnd("start view transition");return On.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(t,e);case"swap":case"morph":return function(t,e){const n=[];let r=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const i=e.value.toLowerCase();Fn.includes(i)&&(r=i,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(w)&&(t.advance(),n.push(t.createIdentifier("of")));const i=t.parseExpression();if(i&&n.push(i),!t.isAtEnd()&&t.check(v)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(t,e);default:return Zn(t,e)}}(this.getContext(),t)}parsePutCommand(t){return Vn(this.getContext(),t)}parseSetCommand(t){return Un(this.getContext(),t)}parseHaltCommand(t){return Nn(this.getContext(),t)}parseMeasureCommand(t){return Pn(this.getContext(),t)}parseTriggerCommand(t){return jn(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(Ie("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){Ie("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){Ie(r?"\u2705 Found COMMAND token:":"\u2705 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&&(Ie("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(Ie("\u2705 Parsed command:",r.name),e.push(r),t=!0)}catch(t){Ie("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&Ie("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){Ie("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(Ie("\ud83d\udccd After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)Ie("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))Ie("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){Ie("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}Ie("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const e of t)if(this.check(e)){r=e;break}return this.check("end")||t.some(t=>this.check(t))||(r=""),Ie("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(t="repeat"){const{commands:e}=this.parseCommandListUntilTerminator([]);if(Ie('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw Ie('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${t} block`);return Ie('\u2705 Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else"]),n="else"===e;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:t,hasElse:n}}parseRepeatBody(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===e)this.advance();else if(""===e)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:t,terminator:e}}parseRepeatCommand(t){return function(t,e){const n=[];let r="forever",i=null,o=null,s=null,a=null,c=null,l=null;if(t.check(u)){t.advance(),r=u;const e=t.peek();ze(e)&&(c=e.value,t.advance()),t.check(y)&&(t.advance(),a=t.parseExpression())}else if(t.check(y))t.advance(),r=u,c="it",a=t.parseExpression();else if(t.check(f))t.advance(),r=f,s=t.parseExpression();else if(t.check(d))if(t.advance(),r=d,t.check(x)){t.advance(),r="until-event";const e=t.peek();if(Ie("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!ze(e)&&!Fe(e))throw Error('Expected event name after "event"');if(i=e.value,t.advance(),Ie("\u2705 Got event name:",i,"Next token:",t.peek().value),Ie('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(b)){Ie('\u2705 Found "from", advancing...'),t.advance(),Ie('\ud83d\udccd After consuming "from", current token:',t.peek().value),Cn(t,T)&&Ie('\u2705 Found "the", advancing...');const e=t.peek();Ie("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),o=t.parsePrimary(),Ie("\u2705 After parsePrimary, eventTarget:",o)}else Ie('\u274c No "from" found, skipping target parsing')}else s=t.parseExpression();else t.check(h)?(t.advance(),r=h):(l=t.parseExpression(),t.check(m)&&(t.advance(),r=m));let g,w=null;if(t.check(v)){const e=t.peekAt(1);e&&e.value.toLowerCase()===p&&(t.advance(),t.advance(),w=p)}else if(t.check(p)){t.advance();const e=t.peek();ze(e)?(w=e.value,t.advance()):w=p}let E=null,k=!1;if(r===h){const e=t.parseRepeatBody();if(g=e.commands,"else"===e.terminator)t.advance(),E=t.parseCommandListUntilEnd();else if("until"===e.terminator||"while"===e.terminator){if(k=!0,r=e.terminator,t.advance(),s=t.parseExpression(),!t.check("end"))throw Error('Expected "end" to close repeat block');t.advance()}}else{const e=t.parseCommandListUntilEndOrElse();g=e.commands,e.hasElse&&(t.advance(),E=t.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column});const S={start:e.start,end:e.end,line:e.line,column:e.column};c&&n.push(pn(c,S)),a&&n.push(a),s&&n.push(s),l&&n.push(l),i&&n.push(pn(i,S)),o&&n.push(o),w&&n.push(pn(w,S)),n.push(mn(g,{...S,end:S.end||0})),null!==E&&n.push(mn(E,{...S,end:S.end||0}));const A=On.from(e).withArgs(...n);return k&&A.withModifier("bottomTested",{type:"literal",value:!0,...S}),A.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,i=null;t.check("each")&&t.advance();const o=t.peek();if(!ze(o))throw Error('Expected variable name after "for"');if(r=o.value,t.advance(),!t.check(y))throw Error('Expected "in" after variable name in for loop');if(t.advance(),i=t.parseExpression(),!i)throw Error('Expected collection expression after "in"');let s=null;if(t.check(v)){const e=t.peekAt(1);e&&e.value.toLowerCase()===p&&(t.advance(),t.advance(),s=p)}else if(t.check(p)){t.advance();const e=t.peek();ze(e)?(s=e.value,t.advance()):s=p}const a=t.parseCommandListUntilEnd("for");n.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return n.push(pn(r,c)),n.push(i),s&&n.push(pn(s,c)),n.push(mn(a,{...c,end:c.end||0})),On.from({...e,value:"repeat"}).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const n=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!kn(t)){const r=t.parseExpression();return n.push(r),On.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{if(t.checkTimeExpression()||t.checkLiteral()||t.check("(")){if(r.push({kind:"duration",expr:t.parseExpression()}),t.check("or")){t.advance();continue}break}const e=t.peek();if(!ze(e))throw Error('Expected event name or duration after "for"');const n=e.value;t.advance();const i=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!ze(e))break;i.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({kind:"event",name:n,params:i}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let i=null;t.check(b)&&(t.advance(),Cn(t,T),i=t.parsePrimary());const o={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(gn(r.map(t=>yn("duration"===t.kind?[{key:dn("duration",o),value:t.expr}]:[{key:dn("name",o),value:fn(t.name,`"${t.name}"`,o)},{key:dn("args",o),value:gn(t.params.map(t=>fn(t,`"${t}"`,o)),o)}],o)),o)),i&&n.push(i)}return On.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const n=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=t.advance().value,i=t.previous();if(n.push(dn(r,{start:i.start,end:i.end,line:i.line,column:i.column})),t.check("(")){t.advance();const r=[];for(;!t.isAtEnd()&&!t.check(")");)if(r.push($n(t)),t.check(","))t.advance();else if(!t.check(")"))break;if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),r.length>0){const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(yn(r.map(t=>({key:t.name?dn(t.name,i):fn("_positional","_positional",i),value:t.value})),i))}}return On.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let i=null,o=null;const s=t.peek();if(t.checkAnySelector()||t.checkContextVar()||t.check("<")||ze(s)&&qn.has(s.value)){const e=t.parsePrimary();("possessiveExpression"===e.type||"memberExpression"===e.type&&!e.computed)&&e.object&&e.property?.name?(o=e.object,i={type:"string",value:e.property.name,start:s.start||0,end:t.getPosition().end,line:s.line,column:s.column}):(o=e,t.check("'s")&&t.advance())}const a=t.peek();if(!i&&(ze(a)||"*"===a.value)){let e="";t.check("*")&&(e="*",t.advance());const n=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);n&&(e+=n,i={type:"string",value:e,start:a.start||0,end:t.getPosition().end,line:a.line,column:a.column})}if(!i)throw Error("Transition command requires a CSS property");if(o&&n.push(o),n.push(i),!t.check(g))throw Error('Expected "to" keyword after property in transition command');t.advance();const c=t.parsePrimary();if(r.to=c,t.check("over")){t.advance();const e=t.parsePrimary();r.over=e}if(t.check(v)){t.advance();const e=t.parsePrimary();r.with=e}return On.from(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const n=[];if(t.match("{"))n.push(t.parseCSSObjectLiteral());else{const e=Sn(t,[g]);e&&n.push(e)}if(t.check(g)){t.advance();const e=Sn(t);e&&n.push(e)}return On.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Mn(this.getContext(),t)}parseRemoveCommand(t){return Bn(this.getContext(),t)}parseToggleCommand(t){return Dn(this.getContext(),t)}parseRegularCommand(t){return Zn(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),!1);n.optional=!0,t=n}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,!0)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):Ge(this.peek())&&this.peek().value.startsWith("@")?e=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),e=this.advance().value,this.consume("]","Expected ']' after attribute reference")):e=this.consumeIdentifierLike("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&ze(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),n=this.processEscapeSequences(e);return this.createLiteral(n,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=!0;break;case"false":e=!1;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value,e=t.slice(1,-2).trim(),n=this.createSelector(e);return n.fromQuery=!0,n.raw=t,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Qe)||this.matchPredicate(Ve)||this.matchPredicate(Ue)||this.matchPredicate(De)||this.matchPredicate(Fe))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(t.value):this.parseNavigationFunction(t.value)}const e=this.check(".")||this.check("?.");return"my"!==t.value||e?"its"!==t.value||e?"your"!==t.value||e?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Ge(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const t=this.peek().start;this.advance();const e=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}e.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:e,body:this.parseExpression(),start:t,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.check("["))this.advance(),e=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,t)}else{if(!this.check("-")&&!this.checkPredicate(Qe))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=!1;for(;this.check("-");)this.advance(),t+="-",n=!0;for(this.checkPredicate(Qe)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=!0,this.checkPredicate(Qe)&&(t+=this.advance().value);if(""===t||"-"===t)return this.addError("Expected property name in object literal"),this.createErrorNode();e=n?this.createLiteral(t,t):this.createIdentifier(t)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(t.push({key:e,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Qe))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);n=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,o=0,s=-1,a=-1;for(;!this.isAtEnd()&&(0!==o||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),0>s&&"number"==typeof t.start&&(s=t.start),"number"==typeof t.end&&(a=t.end),"$"===t.value&&this.check("{")&&(i=!0),"{"===t.value&&o++,"}"===t.value&&o--}const c=this.originalInput&&s>=0&&a>s?this.originalInput.slice(s,a):r.join(""),l=i?{type:"templateLiteral",value:c,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(c,c);if(e.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),n=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column},arguments:r,isConstructor:!0,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:i,errorHandler:o,finallyHandler:s}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==o&&{errorHandler:o},...void 0!==s&&{finallyHandler:s},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseErrorAndFinallyBlocks(){let t,e,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(t=this.advance().value),e=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==t&&{errorSymbol:t},...void 0!==e&&{errorHandler:e},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let n=e.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,n,r,i){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==i.start&&{start:i.start},...void 0!==i.end&&{end:i.end},...void 0!==i.line&&{line:i.line},...void 0!==i.column&&{column:i.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(tr.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Qe(r)&&!this.isCommand(r.value)||Ue(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!1};let i,o;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),tr.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{o=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,t,i,o,e),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(Ie("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return Ie("\u26a0\ufe0f Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseTemporalKeywordModifiers(t){if(!this.check("debounced")&&!this.check("throttled"))return;const e=this.advance().value.toLowerCase(),n="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const i=this.advance(),o=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);t[n]=o,Ie(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${i.value}' (${o}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,Ie(`\ud83d\udd27 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 r}parseEventHandler(){Ie("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const t=this.tokens[this.current+1],n=t?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),e=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),Ie("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),Ie("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),Ie("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(Ie("\ud83d\udd27 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,Ie(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const i=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();i.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),Ie("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const o={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)o.once=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)o.prevent=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)o.stop=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),n=parseInt(e.value,10);if(isNaN(n))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(o.debounce=n,Ie(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(o.throttle=n,Ie(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else Ie(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let s,a,c,l;if(this.parseTemporalKeywordModifiers(o),e&&(o.once=!0),Object.keys(o).length>0&&Ie("\ud83d\udd27 parseEventHandler: Parsed modifiers:",o),this.match("[")&&(s=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,Ie(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`),this.parseTemporalKeywordModifiers(o)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,Ie("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(Ie("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),Ie("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(Ie(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(Ie(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){Ie("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())Ie("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){Ie("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){Ie(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const n=this.parseCommand();u.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),Ie("\u2705 parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){Ie("\u26a0\ufe0f Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const n={type:"command",name:e.left.name,args:[e.right],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}};u.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}let f,d,h;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:f,errorHandler:d,finallyHandler:h}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const m=this.getPosition(),p={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...void 0!==f&&{errorSymbol:f},...void 0!==d&&{errorHandler:d},...void 0!==h&&{finallyHandler:h},...i.length>0&&{args:i},...s&&{condition:s},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(o).length>0&&{modifiers:o},start:m.start,end:m.end,line:m.line,column:m.column};return Ie(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),p}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let o;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Qe(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let o;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),o=e.value,this.advance())}}const{commands:s,terminator:a}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const f={type:"eventHandler",event:e,commands:s,...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:l},...void 0!==u&&{finallyHandler:u},...void 0!==o&&{target:o},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};i.push(f)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}o={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:n,eventHandlers:i,...void 0!==o?{initBlock:o}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,n=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(Ie("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)Ie("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){Ie('\u2705 parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),n=this.getPosition(),r="Expected command, got: "+e.value;this.addError(r);const i=vn(n,r,e.value);if(t.push(i),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return wn.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return En(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const i=[],o={};for(;!kn(t,["catch","finally",...r.keywords])&&!En(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(i.push(e),!t.match(",")&&En(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&En(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(o[e]=n),!En(t.peek(),r.keywords))break}const s=On.from(e).withArgs(...i).endingAt(t.getPosition());return Object.keys(o).length>0&&s.withModifiers(o),s.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();if(e.push(t),this.match("then","and",","))continue}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(Ie(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(Ie(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return Ie("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),n=e.value.toLowerCase();if(t.includes(n))break;if(De(e))break;this.advance()}}parseCommand(){const t=this.parseCommandCore();if(t&&"command"===t.type&&!t.body&&(this.check("when")||this.check("where"))){const e=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(t.modifiers={...t.modifiers??{},[e]:n})}return t}parseCommandCore(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","prepend","toggle","take","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const n={};let r=null;if(!t.isAtEnd()&&Jn(t)&&(r=Xn(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),On.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(n.with=t.parsePrimary());for(let e=0;3>e&&!t.isAtEnd();e++)if(!t.check("as")||n.as){if(!t.check("with")||n.with){if(t.check("do")&&!n.doNotThrow){const e=t.peekAt(1),r=t.peekAt(2);if("not"===e?.value&&"throw"===r?.value){const e=t.advance();t.advance();const r=t.advance();n.doNotThrow={type:"literal",value:!0,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Gn(t)?Yn(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||Cn(t,"a")||Cn(t,"an"),n.as=t.parsePrimary();const i=On.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}(this.getContext(),t);const n=this.parseMultiWordCommand(t,e);if(n)return n;const r=e.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(t);if("for"===r)return this.parseForCommand(t);if("if"===r||"unless"===r)return this.parseIfCommand(t);if("wait"===r)return this.parseWaitCommand(t);if("install"===r)return this.parseInstallCommand(t);if("transition"===r)return this.parseTransitionCommand(t);if("add"===r)return this.parseAddCommand(t);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||function(t,e){return{type:"command",name:t,args:[],partial:!0,start:e.start,end:e.end,line:e.line,column:e.column}}(r,this.getPosition());const i=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let i=!1;t.check(S)&&(i=!0,t.advance());const o=t.parseExpression();if(!o)throw Error("Expected variable or expression after "+n);let s;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${n} command`);s=e}else s=fn(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=o;i&&"identifier"===o.type&&(a={...o,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=hn(r,o,s,c);l.coerceNumeric=!0;const u=[a,dn(g,c),l];return On.from(e).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(i.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const o=this.getPosition();return{type:"command",name:e,args:i,isBlocking:!1,start:o.start,end:o.end,line:o.line,column:o.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}const n=this.createCallExpression(this.createIdentifier(t),e);if("next"===t||"previous"===t){const t=this.parseRelativePositionalModifiers();t&&(n.relativePositional=t)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let t,e,n,r=!1,i=!1;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=!0),{from:t,within:e,inElt:n,inSearch:r,wrapping:i}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parseCall(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),!1);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const n="*"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(t),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Ge(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}const e=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;P(e)&&Ie(`\ud83d\udca1 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return fn(t,e,this.getPosition())}createIdentifier(t){return dn(t,this.getPosition())}createBinaryExpression(t,e,n){return hn(t,e,n,this.getPosition())}createUnaryExpression(t,e,n){return function(t,e,n,r){return{type:"unaryExpression",operator:t,argument:e,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createCallExpression(t,e){return function(t,e,n){return{type:"callExpression",callee:t,arguments:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createMemberExpression(t,e,n){return function(t,e,n,r){return{type:"memberExpression",object:t,property:e,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,n){return{type:"possessiveExpression",object:t,property:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(Ie(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return Ie("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return Ie(`\u2705 createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return Ie(`\u2705 createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),!0;return!1}matchOperator(t){if(this.isAtEnd())return!1;const e=this.peek();return!(!ln(e)||e.value!==t||(this.advance(),0))}check(t){if(this.isAtEnd())return!1;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return!this.isAtEnd()&&t(this.peek())}matchPredicate(t){return!!this.checkPredicate(t)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Ze)}matchSelector(){return this.matchPredicate(Ze)}checkAnySelector(){return this.checkPredicate(We)}checkLiteral(){return this.checkPredicate(Je)}checkIdentifierLike(){return this.checkPredicate(ze)}checkIsCommand(){return this.checkPredicate(De)}checkCommandTerminator(){return this.checkPredicate(un)}checkReference(){return this.checkPredicate(Ke)}checkTimeExpression(){return this.checkPredicate(Xe)}checkEvent(){return this.checkPredicate(Fe)}checkContextVar(){return this.checkPredicate(Ue)}checkComment(){return this.checkPredicate(Ye)}checkIdentifier(){return this.checkPredicate(Qe)}checkKeyword(){return this.checkPredicate(Ve)}checkString(){return this.checkPredicate(tn)}matchString(){return this.matchPredicate(tn)}checkNumber(){return this.checkPredicate(en)}matchNumber(){return this.matchPredicate(en)}checkBoolean(){return this.checkPredicate(nn)}matchBoolean(){return this.matchPredicate(nn)}checkTemplateLiteral(){return this.checkPredicate(rn)}matchTemplateLiteral(){return this.matchPredicate(rn)}checkQueryReference(){return this.checkPredicate(on)}matchQueryReference(){return this.matchPredicate(on)}checkIdSelector(){return this.checkPredicate(sn)}checkClassSelector(){return this.checkPredicate(an)}checkCssSelector(){return this.checkPredicate(cn)}checkBasicOperator(){return this.checkPredicate(ln)}matchBasicOperator(){return this.matchPredicate(ln)}matchTimeExpression(){return this.matchPredicate(Xe)}matchIdentifierLike(){return this.matchPredicate(ze)}matchComparisonOperator(){return this.matchPredicate(_e)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Qe,t)}consumeIdentifierLike(t){return this.consumePredicate(ze,t)}consumeEvent(t){return this.consumePredicate(Fe,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(t){const e=this.current+t;return e>=0&&this.tokens.length>e?this.tokens[e]:null}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let n=e.start||0,r=e.line||1,i=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1,0===n&&this.current>0&&(n=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;n=t.start||0,r=t.line||1,i=t.column||1,0===n&&(n=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const n=this.tokens[e];if(n&&("+"===n.value||"-"===n.value)){t=n;break}}n=t.start||0,r=t.line||1,i=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;Ie("\u26a0\ufe0f synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();r.push(t.value)}this.consume("]","Expected ']' after attribute literal");const i=r.join("");if(!i.includes("="))return{type:"attributeAccess",attributeName:i.replace(/^@/,""),start:t,end:this.previous().end,line:e,column:n};const o="["+i+"]";return{type:"literal",value:o,raw:o,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),i=this.tokens[this.current],o=this.tokens[this.current+1];if("identifier"===i?.kind&&("]"===o?.value||o&&r.has(o.value)&&"string"===this.tokens[this.current+2]?.kind)){let t="["+this.advance().value;if(this.check("]"))this.advance(),t+="]";else{const e=this.advance().value,n=this.advance().value;t+=e+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),t+="]"}return this.createSelector(t)}const s=[];if(!this.check("]"))do{if(this.check("]"))break;s.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:s,start:t,end:this.previous().end,line:e,column:n}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),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:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>t.peekAt(e),getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:!0,configurable:!0}),e}}function er(t,e){const n=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const n=t.length;for(;n>e.position&&(le(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==ae(e,1))if('"'!==n){if("'"===n||"'"===n){const t=ae(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==ie.IDENTIFIER&&n.kind!==ie.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)he(e);else{const t=e.position;ce(e),ce(e),ue(e,ie.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===ae(e,1)){const t=e.position;ce(e),ce(e),ue(e,ie.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=t&&t.kind===ie.IDENTIFIER&&C.has(t.value.toLowerCase()),i=t&&t.kind===ie.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===ie.OPERATOR&&")"!==t.value&&"]"!==t.value||r||i||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(xe(ae(e))||"{"===ae(e)||"-"===ae(e))){pe(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===ie.IDENTIFIER&&V.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==ie.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(ce(e),ue(e,ie.SYMBOL,"[")):(ce(e),ue(e,ie.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const t=ae(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){Ee(e);continue}}Ae(n)?be(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(ue(e,ie.UNKNOWN,n),ce(e)):we(e):ve(e)}else ce(e),ue(e,ie.OPERATOR,"]")}else ce(e),ue(e,ie.OPERATOR,"}");else ce(e),ue(e,ie.OPERATOR,"{");else ge(e)}else pe(e);else Te(e)?ye(e):be(e);else me(e)}else he(e);else de(e)}return e.tokens}(t);return new tr(n,e,t).parse()}function nr(t,e){const n=t.registry?.get(e);if(!n)throw Error(`Expression '${e}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function rr(t){if(t&&"object"==typeof t&&"success"in t){if(t.success)return"value"in t?t.value:void 0;const e=t.errors||[];throw Error(e.length>0?e[0].message:"Expression evaluation failed")}return t}async function ir(t,e){if(!t)throw Error("Cannot evaluate null or undefined AST node");if("literal"===t.type)return t.value;if("identifier"===t.type)return fr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return fr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,i=t.left;if("="===n){const n=await ir(t.right,e);if("identifier"===i?.type&&"string"==typeof i.name){const t=i.name;return t.startsWith("$")?ct(e,t.slice(1),n):"global"===i.scope?ct(e,t,n):"element"===i.scope?mt(e,t,n):(e.locals||(e.locals=new Map),e.locals.set(t,n)),n}throw Error(`Assignment target must be a variable identifier (got '${i?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await ir(t.left,e);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===i?.type&&"identifier"===i.callee?.type?i.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(i.arguments)){const r=i.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const i=await ir(t.right,e);if(i&&"function"==typeof i.querySelectorAll){const t=Array.from(i.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===i?.type&&i.fromQuery&&"string"==typeof i.value){const n=await ir(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(i.value))}}if("of"===n&&"selector"===i?.type&&"string"==typeof i.value&&/^\*[a-zA-Z][\w-]*$/.test(i.value)){const n=await ir(t.right,e);return nr(e,"styleRef").evaluate(e,i.value.slice(1),n)}if("of"===n){const n=dr(t.left);if(n){const r=await ir(t.right,e);let i=r;for(const t of n){if(null==i)return;i=Lt(i)?Ht(i,t):i[t]}return"function"==typeof i?i.bind(r):i}}const o=await ir(t.left,e);if("and"===n){if(!o)return o;const n=await ir(t.right,e);return nr(e,"and").evaluate(e,o,n)}if("or"===n){if(o)return o;const n=await ir(t.right,e);return nr(e,"or").evaluate(e,o,n)}const s=await ir(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(o):o,l=t.ignoringCase?a(s):s;switch(n){case"+":{let n=o,r=s;return t.coerceNumeric&&("string"==typeof n&&(n=vt(n)),"string"==typeof r&&(r=vt(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:rr(await nr(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return rr(await nr(e,"subtraction").evaluate(e,{left:o,right:s}));case"*":return rr(await nr(e,"multiplication").evaluate(e,{left:o,right:s}));case"/":return rr(await nr(e,"division").evaluate(e,{left:o,right:s}));case"%":case"mod":return rr(await nr(e,"modulo").evaluate(e,{left:o,right:s}));case"^":case"**":return rr(await nr(e,"power").evaluate(e,{left:o,right:s}));case">":case"is greater than":return nr(e,"greaterThan").evaluate(e,o,s);case"<":case"is less than":return nr(e,"lessThan").evaluate(e,o,s);case">=":case"is greater than or equal to":return nr(e,"greaterThanOrEqual").evaluate(e,o,s);case"<=":case"is less than or equal to":return nr(e,"lessThanOrEqual").evaluate(e,o,s);case"==":return nr(e,"equals").evaluate(e,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=pr(t,o,s);return void 0!==n?n:nr(e,"equals").evaluate(e,c,l)}case"!=":return nr(e,"notEquals").evaluate(e,c,l);case"is not":case"is not equal":case"is not equal to":{const n=pr(t,o,s);return void 0!==n?!n:nr(e,"notEquals").evaluate(e,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return nr(e,"strictEquals").evaluate(e,c,l);case"!==":case"is not really":case"is not really equal to":return nr(e,"strictNotEquals").evaluate(e,c,l);case"as":return nr(e,"as").evaluate(e,o,gr(s));case"contains":case"contain":case"includes":case"include":return nr(e,"contains").evaluate(e,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return nr(e,"doesNotContain").evaluate(e,c,l);case"starts with":return nr(e,"startsWith").evaluate(e,c,l);case"ends with":return nr(e,"endsWith").evaluate(e,c,l);case"does not start with":return!await nr(e,"startsWith").evaluate(e,c,l);case"does not end with":return!await nr(e,"endsWith").evaluate(e,c,l);case"match":case"matches":return nr(e,"matches").evaluate(e,c,mr(t.right,l));case"does not match":case"do not match":return!await nr(e,"matches").evaluate(e,c,mr(t.right,l));case"in":case"is in":case"am in":return hr(o,s);case"is not in":case"am not in":return!hr(o,s);case"of":return s&&"object"==typeof s?s[o]:void 0;case"precedes":return yr(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!yr(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return yr(o,s,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!yr(o,s,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await ir(t.expression,e),r=gr(t.targetType);return nr(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await ir(t.value,e),r=await ir(t.min,e),i=await ir(t.max,e),o=t=>"string"==typeof t?t.toLowerCase():t,[s,a,c]=t.ignoringCase?[o(n),o(r),o(i)]:[n,r,i],l=await nr(e,"between").evaluate(e,s,a,c);return t.negated?!l:l}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return!0;if(Object.prototype.toString.call(t).slice(8,-1)===e)return!0;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await ir(t.value,e),t.typeName+"",!1!==t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await ir(t.collection,e);if(null==n)return n;const r=async(t,n)=>ir(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=re(t),i=[];for(const t of r)await n(e,t)&&i.push(t);return i}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const i=[...re(t)],o=await Promise.all(i.map(t=>r(e,t))),s=i.map((t,e)=>e);s.sort((t,e)=>{const n=o[t],r=o[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=s.map(t=>i[t]);return"desc"===n?a.reverse():a}(n,t.right,t.order??"asc",r);case"mapped to":return async function(t,e,n){const r=re(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return o=await ir(t.right,e),null==(i=n)?[]:(i+"").split(null==o?"":o+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return re(t).map(t=>null==t?"":t+"").join(n)}(n,await ir(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var i,o}(n,e);case"unaryExpression":return async function(t,e){const n=t.operand??t.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${t.operator})`);const r=await ir(n,e);switch(t.operator){case"not":case"!":return nr(e,"not").evaluate(e,r);case"no":return nr(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return nr(e,"exists").evaluate(e,r);case"does not exist":return nr(e,"doesNotExist").evaluate(e,r);case"is empty":return nr(e,"isEmpty").evaluate(e,r);case"is not empty":return nr(e,"isNotEmpty").evaluate(e,r);default:throw Error("Unknown unary operator: "+t.operator)}}(n,e);case"memberExpression":return async function(t,e){const n=await ir(t.object,e);if(t.computed){const r=await ir(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Er(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await ir(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await Er(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await ir(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>ir(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,i=await async function(t,e,n){return xr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:ir(t,n))):Promise.all(t.map(t=>ir(t,n)))}(t.arguments,r,e);switch(r){case"closest":return nr(e,"closest").evaluate(e,...i);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?kr(await ir(n.from,e)):e.me,o=n.within?kr(await ir(n.within,e)):void 0,s=n.inElt?await ir(n.inElt,e):void 0;return nr(e,r).evaluate(e,i[0],t,{within:o,inElt:s,inSearch:n.inSearch,wrapping:n.wrapping})}return nr(e,r).evaluate(e,...i)}case"first":return nr(e,"first").evaluate(e,...i);case"last":return nr(e,"last").evaluate(e,...i);default:if("function"==typeof n)return n(...i);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>ir(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const i=await ir(t.callee.object,e);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){let n=t.value;if("string"==typeof n&&!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return nr(e,"styleRef").evaluate(e,n.slice(1));if("string"==typeof n&&t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=await async function(t,e){const n=$r(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>cr(t.expr,e)));return Or(n,r)}(n,e),o=Ar(t,r);i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await nr(e,"elementWithSelector").evaluate(e,o)}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!t.fromQuery&&n.includes("{")&&(n=await function(t,e){return wr(t,/\{([^}]*)\}/g,async(t,n)=>(await cr(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Ar(t,n):n;return kt(await nr(e,"elementWithSelector").evaluate(e,r),n,t.fromQuery)}(n,e);case"contextReference":return async function(t,e){switch(t.contextType){case"me":case"you":case"it":return nr(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return nr(e,"me").evaluate(e);case"your":case"yourself":return nr(e,"you").evaluate(e);case"its":return nr(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??nr(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return nr(e,"document").evaluate(e);case"window":return nr(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await ir(t.object,e),r=t.property.name;return nr(e,"possessive").evaluate(e,n,r)}(n,e);case"eventHandler":return async function(t,e){return{event:t.event,selector:t.selector,commands:t.commands,handler:async n=>{const r={...e,event:n,target:n.target,currentTarget:n.currentTarget};for(const e of t.commands)await ir(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await ir(t.test,e)?ir(t.consequent,e):t.alternate?ir(t.alternate,e):void 0}(n,e);case"string":return n.value;case"arrayLiteral":return async function(t,e){const n=[];for(const r of t.elements)n.push(await ir(r,e));return n}(n,e);case"objectLiteral":return async function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await ir(t,e)+"",n[i]=await ir(r.value,e)}return n}(n,e);case"attributeAccess":return async function(t,e){const n=t.attributeName;return e.me&&e.me instanceof Element?e.me.getAttribute(n):"@"+n}(n,e);case"propertyOfExpression":return async function(t,e){const n=t.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await ir(t.target,e);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return nr(e,"possessive").evaluate(e,i,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await wr(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(t,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const t=n.split(".");let r=vr(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(vr(n,e)??"")+""}catch{return""}}),n=await wr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const i=n||r;try{return await cr(i,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await ir(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return br(n,e);default:{const n=G.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}tr.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),tr.PRATT_TABLE=K,tr.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class or extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function sr(t,e){const n=t;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(t,e){const n=t.value;if("string"!=typeof n)throw new or("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new or("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(t,e){const n=$r(t),r=n.filter(t=>"expr"in t).map(t=>ar(t.expr,e));return Or(n,r)}(n,e),o=Ar(t,r),s=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new or("selector");i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return Array.from(s.querySelectorAll(o))}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}const r=!t.fromQuery&&n.includes("{")?function(t,e){return t.replace(/\{([^}]*)\}/g,(t,n)=>(ar(n.trim(),e)??"")+"")}(n,e):n,i=Ar(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new or("selector");return kt(Array.from(o.querySelectorAll(i)),r,t.fromQuery)}(n,e);case"identifier":return function(t,e,n){return"me"===t||"my"===t||"I"===t?e.me:"you"===t||"your"===t||"yourself"===t?e.you:"it"===t||"its"===t?e.it??e.result:"result"===t?e.result??e.it:"window"===t?"undefined"!=typeof window?window:globalThis:"document"===t?"undefined"!=typeof document?document:void 0:"element"===n?ht(e,t):e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):t.startsWith("$")&&e.globals?.has(t.slice(1))?e.globals.get(t.slice(1)):void 0!==e[t]?e[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}(n.name,e,n.scope);case"contextReference":return function(t,e){switch(t){case"me":return e.me;case"you":return e.you;case"it":return e.it??e.result;case"event":return e.event;case"target":return e.target??e.event?.target??e.me;default:throw new or("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>sr(t,e));case"objectLiteral":return function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:sr(t,e)+"",n[i]=sr(r.value,e)}return n}(n,e);case"asExpression":return Gt(sr(n.expression,e),gr(n.targetType),e);case"stringPostfix":return`${sr(n.expression,e)}${n.unit}`;case"blockLiteral":return br(n,e);case"memberExpression":{const t=sr(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new or("memberExpression");const r=t[n.computed?sr(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new or(n?.type??"unknown")}}function ar(t,e){const n=er(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return sr(n.node,e)}async function cr(t,e){const n=er(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}const r=e.registry?e:{...e,registry:await ur()};return ir(n.node,r)}let lr=null;async function ur(){if(!lr){const t=await Promise.resolve().then(function(){return fo});lr=t.createFullExpressionRegistry()}return lr}async function fr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?nr(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?nr(e,"you").evaluate(e):"it"===n||"its"===n?nr(e,"it").evaluate(e):"result"===n?nr(e,"result").evaluate(e):"window"===n?nr(e,"window").evaluate(e):"document"===n?nr(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?(ot(n,e),e.globals.get(n)):"element"===t.scope?ht(e,n):e.locals&&e.locals.has(n)?(at(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&ot(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?(ot(n.slice(1),e),e.globals.get(n.slice(1))):void 0!==e[n]?e[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function dr(t){const e=t;if(!e)return null;if("identifier"===e.type&&"string"==typeof e.name)return[e.name];if("memberExpression"===e.type&&!e.computed){const t=dr(e.object);if(!t)return null;const n=e.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...t,r]}return null}function hr(t,e){return Array.isArray(e)?e.includes(t):"string"==typeof e?e.includes(t+""):t instanceof Node&&e instanceof Node?t===e||e.contains(t):null!=e&&"object"==typeof e&&t in e}function mr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function pr(t,e,n){if(void 0!==n)return;const r=t.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==e||"object"!=typeof e)return;const i=e[r.name];return"boolean"==typeof i?!0===i:void 0}function yr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function gr(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t+""}function br(t,e){const n=t.parameters??[];return(...r)=>{const i=new Map(e.locals??new Map);n.forEach((t,e)=>i.set(t,r[e]));const o={...e,locals:i};try{return sr(t.body,o)}catch(e){if(e instanceof or)return ir(t.body,o);throw e}}}function vr(t,e){if(e.locals?.has(t))return at(t,e),e.locals.get(t);if("me"===t&&e.me)return e.me;if("you"===t&&e.you)return e.you;if("it"===t){const t=e.it??e.result;if(t)return t}if("result"===t){const t=e.result??e.it;if(t)return t}return"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function wr(t,e,n){const r=[];let i;for(;null!==(i=e.exec(t));)r.push({index:i.index,length:i[0].length,replacement:await n(i[0],...i.slice(1))});let o=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:i}=r[t];o=o.substring(0,e)+i+o.substring(e+n)}return o}function Er(t,e,n){if("string"==typeof e&&e.startsWith("@")){const n=e.substring(1);return t&&"function"==typeof t.getAttribute?t.getAttribute(n):void 0}return t instanceof Element&&"string"==typeof e?Ht(t,e):ee(t)&&!(e in t)?nr(n,"possessive").evaluate(n,t,e):t?.[e]}const xr=new Set(["closest","previous","next"]);function kr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const Sr=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"),Tr=/[:&()[\]/]/g;function Ar(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(Sr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(Tr,"\\$&")}(e)}const Cr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function $r(t){const e=[];let n,r=0;for(Cr.lastIndex=0;null!==(n=Cr.exec(t));)n.index>r&&e.push({lit:t.slice(r,n.index)}),e.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return t.length>r&&e.push({lit:t.slice(r)}),e}function Or(t,e){let n="";const r=[];let i=0;for(const o of t){if("lit"in o){n+=o.lit;continue}const t=e[i++];Lt(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class jr{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??!1}registerListener(t,e,n,r,i){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,i),this.debugMode&&Me(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&Me("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&Me("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&Me("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,n){this.addCleanup(t,{type:"custom",cleanup:e,description:n||"Custom cleanup"})}registerGlobal(t,e="custom",n){this.globalCleanups.push({type:e,cleanup:t,description:n||"Global cleanup"}),this.debugMode&&Me("CleanupRegistry: Registered global cleanup: "+(n||e))}addCleanup(t,e){const n=this.elementCleanups.get(t);n?n.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&Me(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let n=0;for(const t of e){try{t.cleanup(),n++}catch(t){this.debugMode&&Me("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&Me(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(t){let e=this.cleanupElement(t);const n=t.querySelectorAll("*");for(const t of n)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&Me("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&Me(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,n=0,r=0,i=0;for(const o of this.globalCleanups)switch(o.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}class Nr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&Me("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(n,e)}unregister(t){const e=t.toLowerCase(),n=this.sources.get(e);if(n){for(const[t,n]of this.subscriptions.entries())n.source===e&&(n.unsubscribe(),this.subscriptions.delete(t));return n.destroy?.(),this.sources.delete(e)}return!1}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,n){const r=this.get(t);if(!r)return void Me("[EventSourceRegistry] Unknown event source: "+t);r.initialize?.();const i=r.subscribe(e,n);return this.subscriptions.set(i.id,i),i}unsubscribe(t){const e=this.subscriptions.get(t);return!!e&&(e.unsubscribe(),this.subscriptions.delete(t))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,n]of this.sources.entries())if(n.supports?.(t)??n.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Rr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,n){const r=t.toLowerCase();this.providers.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:e)}registerGlobal(t,e,n){const r=t.toLowerCase();this.globalProviders.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const o=await r.provide(e);return r.cache&&n&&n.set(i,o),o}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);const o=r.provide(e);if(o instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,o),o}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,i){if("string"==typeof r&&e.get(r))try{return e.resolveSync(r,t,n)}catch{return e.resolve(r,t,n)}return Reflect.get(t,r,i)},has:(t,n)=>!("string"!=typeof n||!e.has(n))||Reflect.has(t,n)})}async resolveAll(t){const e=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,o]of r)try{n[i]=await this.resolve(i,t,e)}catch(t){Me(`[ContextProviderRegistry] Failed to resolve '${i}':`,t),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Lr={evaluate:(t,e)=>ir(t,e)};class Ir{static toTyped(t){return{me:t.me,...void 0!==t.owner&&{owner:t.owner},it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},...void 0!==t.registry&&{registry:t.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Mr{constructor(t,e,n){this.impl=t,this.hookRegistry=n??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,n={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:n,event:t.event??void 0,executionContext:t}}get name(){const t=this.impl.name;if(t)return t;const e=this.impl.metadata?.name;return"string"==typeof e?e:""}get metadata(){const t=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(t)?t.join(" | "):t||""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(Re(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void Re(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Ir.toTyped(t);let o,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(Re(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const e=n.modifiers,r=e?.when||e?.where;if(r&&!await ir(r,t))return void Re(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);o=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},Lr,t)}else o=e;else Re(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),o=e;if(Re("CommandAdapterV2: Calling execute with parsed input:",o),2===this.impl.execute.length)s=await this.impl.execute(o,i);else{const t=Array.isArray(o)?o:[o];s=await this.impl.execute(i,...t)}return Re("CommandAdapterV2: Command result:",s),Object.assign(t,Ir.fromTyped(i,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,s),s}catch(t){if(Vr(t)||Re(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:!0,errors:[],suggestions:[]}}}class Pr{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);Me(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=e.toLowerCase();Me(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Mr(t,void 0,this.hookRegistry);this.adapters.set(n,r),C.add(n);const i=t.metadata?.aliases;if(i&&Array.isArray(i))for(const e of i){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),C.add(n)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const n=this.getAdapter(t);return n?n.validate(e):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let qr=null;function Hr(){return qr||(qr=function(t){const e=t?.commands??new Pr,n=t?.eventSources??new Nr,r=t?.context??new Rr,i=new Set,o={commands:e,eventSources:n,context:r,use(t){if(i.has(t.name))Me(`[LokaScriptRegistry] Plugin '${t.name}' is already installed`);else{if(t.commands)for(const n of t.commands)e.register(n);if(t.eventSources)for(const e of t.eventSources)n.register(e.name,e);if(t.contextProviders)for(const{name:e,provide:n,options:i}of t.contextProviders)r.register(e,n,i);t.setup?.(o),i.add(t.name)}},reset(){i.clear()}};return o}()),qr}class Br{constructor(t={}){this.contextCache=new WeakMap;const e=Hr();this.options={enableContextProviders:t.enableContextProviders??!0,enableEventSources:t.enableEventSources??!0,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,Me(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),Me(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return Me("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return Me(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return Me(`[RegistryIntegration] Found event source '${n}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(t,e,n);if(!r)throw Error(`Failed to subscribe to event source '${t}'`);return Me(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,Me("[RegistryIntegration] Destroyed")}}function Dr(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=!0,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Vr(t){return t instanceof Error&&(null!==n(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function Fr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Ur=new WeakMap;function _r(t,e=new Set){if(null===t||"object"!=typeof t)return e;if(Array.isArray(t)){for(const n of t)_r(n,e);return e}const n=t;"identifier"===n.type&&"string"==typeof n.name&&e.add(n.name);for(const t of Object.keys(n))"start"!==t&&"end"!==t&&"line"!==t&&"column"!==t&&_r(n[t],e);return e}class zr{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...t},this.registry=t.registry,this.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=lt,this.hookRegistry=new e,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new jr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new Br("object"==typeof t.registryIntegration?t.registryIntegration:{}),Me("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,n)=>await this.installBehaviorOnElement(t,e,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const n of t)for(const t of n.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&Me(`RuntimeBase: Auto-cleaned ${e} 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(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}trackListener(t,e,n,r,i){this.cleanupRegistry.registerListener(t,e,n,r,i)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...t){this.options.enableErrorReporting&&console.error(...t)}logWarn(...t){this.options.enableErrorReporting&&console.warn(...t)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),Me("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){Me(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,n)=>this.execute(t,n||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return Me("\u26a0\ufe0f RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(t,e);if(!o(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw Dr(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const r=n(t);if(r?.isReturn){const t=r.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw t}case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(n,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"def":return this.installFunction(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=t,r=await this.executeCommandSequenceWithResult(n.commands||[],e);if(!o(r))throw Dr(r.error);return r.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(t,e);if(!o(n))throw Dr(n.error);return n.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:n,args:r,modifiers:i}=t,o=n.toLowerCase();if(Re(`RUNTIME BASE: Processing command '${o}'`),this.registry.has(o)){const t=await this.registry.getAdapter(o);if(!t)throw Error(`Command '${o}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:i||{},commandName:o,runtime:this})}catch(t){throw Vr(t)||this.logError(`Error executing command '${o}':`,t),t}}const s=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(s),Error(s)}toSignal(t){const e=n(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:n,args:o,modifiers:s}=t,a=n.toLowerCase();if(Re(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const t=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(t),Error(t)}const c=await this.registry.getAdapter(a);if(!c)throw Error(`Command '${a}' is registered but failed to load adapter.`);try{return r(await c.execute(e,{args:o||[],modifiers:s||{},commandName:a,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return i(e);throw this.logError(`Error executing command '${a}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const i of t){if(this.hasErrorDiagnostics(i)){const t=i.diagnostics?.[0];Me("\u26a0\ufe0f RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===i.type){const t=await this.processCommandWithResult(i,e);if(!o(t)){const n=t.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==n.returnValue&&Object.assign(e,{it:n.returnValue,result:n.returnValue}),r(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(i,e);if(!o(t))return t;n=t.value}}return r(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await ir(t,n);return Fr(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},s=await async function(t,e){try{return r(await ir(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return i({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return i({type:"exit",returnValue:e.returnValue});if(e.isBreak)return i({type:"break"});if(e.isContinue)return i({type:"continue"});if(e.isReturn)return i({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!o(s))return s;const a=s.value;if(Fr(a)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:a.command,args:[{type:"literal",value:a.selector}]},e);try{return r(await this.executeCommandFromPattern(a.command,a.selector,e))}catch(t){const e=this.toSignal(t);if(e)return i(e);throw t}}return r(a)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}installFunction(t,e){const r=this,i=t.params??[],s=t.body??[],a=t.errorHandler,c=t.finallyHandler,l=t.errorSymbol;e.globals.set(t.name,async(...t)=>{const u={...e,locals:new Map(e.locals)};i.forEach((e,n)=>{e&&u.locals.set(e,t[n])});const f=async t=>{const e=await r.executeCommandSequenceWithResult(t,u);if(!o(e))throw n(e.error);return e.value};if(!a&&!c)return await f(s);try{return await f(s)}catch(t){if(!a||Vr(t))throw t;return l&&u.locals.set(l,t),await f(a)}finally{c&&await f(c)}})}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],i=[],o=[],s=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"def"===e.type?i.push(e):"initBlock"===e.type?o.push(e):s.push(e);for(const t of i)this.execute(t,e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Vr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of o)try{n=await this.execute(t,e)}catch(t){if(Vr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Vr(t)&&(t.isHalt||t.isExit))break;throw t}return n}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const n of t.commands)try{await this.execute(n,e)}catch(t){if(Vr(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let n;for(const r of t.commands)try{n=await this.execute(r,e)}catch(t){if(Vr(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return n}async executeObjectLiteral(t,e){const n={};if(!t.properties)return n;for(const r of t.properties){let t;t="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,e)+"";const i=await this.execute(r.value,e);n[t]=i}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:o}=t,s=t.imperativeInstaller;"function"==typeof s?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:s}),Me(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:o}),Me(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){Me("BEHAVIOR: installBehaviorOnElement called: "+t);let r=this.behaviorRegistry.get(t);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(r=this.behaviorRegistry.get(t)),!r))throw Error(`Behavior "${t}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(Me(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),Me(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));Me("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const i={me:e,owner:e,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},o=this.enhanceContext(i);if(r.parameters)for(const t of r.parameters)o.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||o.locals.set(t,e);if(r.initBlock){Me("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,o),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),Me("BEHAVIOR: Init block completed for "+t)}catch(e){if(Me(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Vr(e)))throw e}}if(Me(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${t}`),r.eventHandlers){const e=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,o),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}Me("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:i,target:o,args:s,selector:a,condition:c,attributeName:l,watchTarget:u,modifiers:f,errorSymbol:d,errorHandler:h,finallyHandler:m}=t,p=r&&r.length>0?r:[n];Me(`BEHAVIOR: executeEventHandler: event='${n}', target='${o}'`);let y=[],g=null;if(o){const t="string"==typeof o?o.toLowerCase():"";if("window"===t||"the window"===t)g=window;else if("document"===t||"the document"===t||"body"===t)g=document;else if("me"===t||"myself"===t)y=e.me?[e.me]:[];else if("string"==typeof o&&e.locals.has(o)){const t=e.locals.get(o);Me(`BEHAVIOR: Target resolution: found local '${o}', isElement: ${this.isElement(t)}`),this.isElement(t)?y=[t]:Array.isArray(t)?y=t.filter(t=>this.isElement(t)):"string"==typeof t&&(y=this.queryElements(t,e))}else Me(`BEHAVIOR: Target resolution: querying for '${o}'`),y=this.queryElements(o,e)}else y=e.me?[e.me]:[];if(0===y.length&&!g)return void Me(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(y,l,i,e);if("change"===n&&u)return void this.setupChangeObserver(u,i,e);const b=t.customEventSource;if(b&&this.registryIntegration){Me(`BEHAVIOR: executeEventHandler - Using custom event source '${b}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),o={...e,locals:r,it:t,event:t},s=this.enhanceContext(o);Me(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},s)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(b,{event:n,handler:t,target:o,selector:a},e);Me(`BEHAVIOR: Subscribed to custom event source '${b}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${b}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${b}':`,t)}return}const v=zr.createEventHandler(this,i,e,a,s,{errorSymbol:d,errorHandler:h,finallyHandler:m},1===p.length?c:void 0);let w,E=null;if(f){let t=v;if(f.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(f.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(f.debounce){const e=f.debounce;let n;w=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},E=()=>{n&&(clearTimeout(n),n=void 0)}}else if(f.throttle){const e=f.throttle;let n=0;w=r=>{const i=Date.now();e>i-n||(n=i,t(r))}}else w=t}else w=v;const x=f?.once?{once:!0}:void 0;if(g){for(const t of p)g.addEventListener(t,w,x),y.length>0?this.cleanupRegistry.registerListener(y[0],g,t,w):this.cleanupRegistry.registerGlobal(()=>g.removeEventListener(t,w),"listener",`Global ${t} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const t of y){for(const e of p){if("resize"===e&&"undefined"!=typeof ResizeObserver){const e=new ResizeObserver(t=>{for(const n of t){const t=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(t.synthetic=!0,w(t),x?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,w,x),this.cleanupRegistry.registerListener(t,t,e,w)}E&&this.cleanupRegistry.registerCustom(t,E,"debounce-timeout")}}static createEventHandler(t,e,n,r,i,o,s){return async a=>{const c=Ur.get(a)??0;if(c>=100)return;if(Ur.set(a,c+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{Me(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const l=new Map(n.locals),u={...n,locals:l,it:a,event:a};l.has("target")||u.locals.set("target",a.target);const f=t.enhanceContext(u);if(i&&i.length>0){const t=a,e=t.detail;for(const n of i)f.locals.set(n,t[n]??e?.[n]??null)}if(s){const e=a;for(const t of _r(s))!f.locals.has(t)&&t in e&&f.locals.set(t,e[t]);let n;try{n=await t.evaluateExpression(s,f)}catch(t){return void Me("Event filter threw; skipping handler body:",t)}if(!n)return}const d=async e=>{for(const n of e)try{await t.execute(n,f)}catch(e){if(Vr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(f,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}},h=o?.errorHandler,m=o?.finallyHandler;if(h||m)try{await d(e)}catch(t){if(!h||Vr(t))throw t;o?.errorSymbol&&f.locals.set(o.errorSymbol,t),await d(h)}finally{m&&await d(m)}else await d(e)}}setupMutationObserver(t,e,n,r){Me(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const i of t){const t=new MutationObserver(async t=>{for(const o of t)if("attributes"===o.type&&o.attributeName===e){Le(`MUTATION DETECTED: attribute '${e}' changed on`,i);const t={...r,me:i,it:o,locals:new Map(r.locals)},s=o.oldValue,a=i.getAttribute(e);t.locals.set("oldValue",s),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Vr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(i,t),Me("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){Me("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(t,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(t=>this.isElement(t))),Me(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const t of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){Le("CONTENT CHANGE DETECTED on",t,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",t);const o=i.oldValue,s=t.textContent;null!==o&&r.locals.set("oldValue",o),r.locals.set("newValue",s);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Vr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(t,r),Me("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const n=e.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=t;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return Me(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}function Wr(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}function Zr(t,e){if(e.startsWith("computed-")){const n=e.substring(9);return getComputedStyle(t).getPropertyValue(n)||""}const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}const Jr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:_t},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:_t},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:_t},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:_t},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result??t.it,validate:_t},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:t=>Ft(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:t=>Ft(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:t=>Ft(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:t=>Ft(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let n=e[0];if(n&&"object"==typeof n&&"type"in n){const t=n;"identifier"===t.type&&t.name?n=t.name:"literal"===t.type&&"string"==typeof t.value&&(n=t.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return t.me?t.me.closest(n):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:_t},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:_t},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:_t},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const i=r.querySelectorAll(n);return Array.from(i)},validate:t=>Ft(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const i=r||t.me;if(i&&i instanceof HTMLElement)return Zr(i,n)},validate:t=>Wt(t,1,2,"styleRef","property, optional element")??Vt(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&t.me?i=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return Zr(i,r)},validate:t=>Dt(t,2,"possessiveStyleRef","possessor, property")??Vt(t,0,"possessiveStyleRef","possessor")??Vt(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&t.me?i=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return Zr(i,n)},validate:t=>Dt(t,2,"ofStyleRef","property, reference")??Vt(t,0,"ofStyleRef","property")??Vt(t,1,"ofStyleRef","reference")}};function Kr(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Xr="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 Yr(){return Gr({validate:t=>({success:!0,data:t})})}function Qr(t,e){if(Xr)return Yr();const n=Gr({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:Kr("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(e?.strict){const e=Object.keys(t),n=Object.keys(r).filter(t=>!e.includes(t));if(n.length>0)return{success:!1,error:Kr("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[e,n]of Object.entries(t)){const t=r[e];if(!(e in r)&&!n.t)return{success:!1,error:Kr("missing-argument",`Required field "${e}" is missing`,e)};const o=n.validate(t);if(!o.success)return{success:!1,error:Kr("validation-error",o.error.message||`Field "${e}" validation failed`,o.error.path?`${e}.${o.error.path}`:e)};void 0!==o.data&&(i[e]=o.data)}return{success:!0,data:i}}});return n.strict=()=>Qr(t,{strict:!0}),n}Gr=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:!0,data:e.data}:{success:!1,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:!0,validate:e=>null==e?{success:!0,data:void 0}:t(e)};return Gr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:!1,error:Kr("runtime-error",`String must be at least ${t} characters long`)}:r}};return Gr(n)}),t.max||(t.max=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:!1,error:Kr("runtime-error",`String must be at most ${t} characters long`)}:r}};return Gr(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:!0,validate:n=>void 0===n?{success:!0,data:t}:e(n)};return Gr(n)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?t(i.data)?i:{success:!1,error:Kr("runtime-error",e||"Refinement validation failed")}:i}};return Gr(r)}),new Proxy(t,{get:(t,e,n)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,n):function(...t){return n}})};const ti=t=>function(t={}){return Xr?Yr():Gr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:Kr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:Kr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:Kr("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:!1,error:Kr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:Kr("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),ei=t=>Qr(t),ni=t=>function(t){return Xr?Yr():Gr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:Kr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:Kr("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const i=t[r].validate(e[r]);if(!i.success)return{success:!1,error:Kr("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(t),ri=()=>Yr();class ii{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(this.ttl>=Date.now()-e.timestamp)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU(),this.cache.set(t,{result:e,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[n,r]of this.accessOrder)e>r&&(e=r,t=n);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,n)=>t+(e-n.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const oi=new class{constructor(){this.domQueryCache=new ii(200,3e3),this.exprResultCache=new ii(500,2e3),this.cssMatchCache=new ii(100,5e3),this.formValueCache=new ii(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(t);return this.domQueryCache.set(e,r),r}querySelectorAll(t){const e="querySelectorAll:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,r),r}getElementById(t){const e="getElementById:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(t);return this.domQueryCache.set(e,r),r}getElementsByClassName(t){const e="getElementsByClassName:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,r),r}matches(t,e){const n=`matches:${this.getElementCacheKey(t)}:${e}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=t.matches(e);return this.cssMatchCache.set(n,i),i}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),n=this.formValueCache.get("formValue:"+e);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(t,e){const n=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+n,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(t.cache.keys()))"string"==typeof n&&n.includes(e)&&t.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),n=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${n}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([n,r])=>{t-r.timestamp>e.ttl&&e.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{oi.cleanup()},1e4);const si=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const n=performance.now()-e;return this.startTimes.delete(t),n}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=oi.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function ai(){oi.cleanup(),si.getMetrics().memoryUsage>52428800&&si.reset()}let ci=null;function li(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const n=t.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${e} cannot be converted to number: "${t}"`);return r}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const n=t[0];if(Array.isArray(n))throw Error(e+" is a nested array, cannot convert to number");return li(n,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const n=parseFloat(t);if(!isNaN(n))return n}}const n=t.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function ui(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?null:n}return"boolean"==typeof t?t?1:0:null==t?0:null}function fi(t,e){if(!Number.isFinite(t)){if(Number.isNaN(t))throw Error(e+" resulted in non-finite value: NaN");throw Error(`${e} resulted in non-finite value: ${t>0?"Infinity":"-Infinity"}`)}return t}function di(t){try{return li(t,"_"),!0}catch{return!1}}function hi(t,e,n){if("==="===n)return t===e;if("!=="===n)return t!==e;if(null==t||null==e)return function(t,e,n){if(null==t&&null==e)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(t,e,n);const[r,i]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const n=parseFloat(t),r=parseFloat(e);return isNaN(n)||isNaN(r)?[t,e]:[n,r]}const n=ui(t),r=ui(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>i;case"<":return i>r;case">=":return r>=i;case"<=":return i>=r;case"==":return mi(t,e);case"!=":return!mi(t,e);default:return!1}}function mi(t,e){if(t===e)return!0;if(typeof t==typeof e)return("string"==typeof t||"number"==typeof t)&&t===e;if("number"==typeof t&&"string"==typeof e){const n=parseFloat(e);return!isNaN(n)&&t===n}if("string"==typeof t&&"number"==typeof e){const n=parseFloat(t);return!isNaN(n)&&n===e}return"boolean"==typeof t?mi(t?1:0,e):"boolean"==typeof e?mi(t,e?1:0):t+""==e+""}function pi(t,e=[]){return{isValid:!1,errors:t,suggestions:e}}function yi(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function gi(t,e,n,r,i,o=!0,s){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:o,...void 0!==s&&{error:s}}),r}function bi(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}"undefined"!=typeof window&&function(t=3e4){ci&&clearInterval(ci),ci=setInterval(ai,t)}();const vi=ni([ri(),ri()]),wi=ni([ri(),ti()]),Ei={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return gi(this,t,[e,n],e==n,r)}catch(i){throw gi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Ut(t,"equals"),inputSchema:vi,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"]}},xi={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e===n;return r&&gi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"strictEquals")},ki={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!=n;return r&&gi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"notEquals")},Si={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!==n;return r&&gi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"strictNotEquals")},Ti={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=hi(e,n,"<");return r&&gi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"lessThan")},Ai={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=hi(e,n,"<=");return r&&gi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"lessThanOrEqual")},Ci={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=hi(e,n,">");return r&&gi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"greaterThan")},$i={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=hi(e,n,">=");return r&&gi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"greaterThanOrEqual")},Oi={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return gi(this,t,[e,n],e&&n,r)}catch(i){throw gi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Ut(t,"and"),inputSchema:vi,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"]}},ji={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e||n;return r&&gi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"or")},Ni={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&gi(this,t,[e],r,n?Date.now():0),r},validate:t=>Dt(t,1,"not","operand")},Ri={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||(Ct(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!jt(e)||0!==Object.keys(e).length)),n&&gi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"isEmpty","value")},Li={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||!1===e||(Array.isArray(e)||e instanceof NodeList?0===e.length:(Ct(e),!1)),n&&gi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"no","value")},Ii={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!await Ri.evaluate(t,e);return n&&gi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"isNotEmpty","value")},Mi={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=Pi(e);return n&&gi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"exists","value")};function Pi(t){return null!=t&&(Array.isArray(t)?t.length>0:!("undefined"!=typeof NodeList&&t instanceof NodeList)||t.length>0)}const qi={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!Pi(e);return n&&gi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"doesNotExist","value")},Hi={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let o;if(e&&n){if(bi(e)&&bi(n))return o=e.contains(n),r&&gi(this,t,[e,n],o,i),o;if(Ct(e)&&e.match(/^[.#][\w-]+$/)){const s=document.querySelector(e);if(s&&bi(n))return o=s.contains(n),r&&gi(this,t,[e,n],o,i),o;if(s&&Ct(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return o=!!a&&s.contains(a),r&&gi(this,t,[e,n],o,i),o}}if(Ct(n)&&n.match(/^[.#][\w-]+$/)&&bi(e)){const s=document.querySelector(n);return o=!!s&&e.contains(s),r&&gi(this,t,[e,n],o,i),o}}if(Ct(e)&&Ct(n))o=e.includes(n);else if(Array.isArray(e)||"undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e);o=t.includes(n)||n instanceof Node&&t.some(t=>t instanceof Node&&t.contains(n))}else o=!(!jt(e)||!Ct(n))&&n in e;return r&&gi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"contains","container, value")},Bi={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=!await Hi.evaluate(t,e,n);return r&&gi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"doesNotContain","container, value")},Di={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=null!=e&&null!=n&&(e+"").startsWith(n+"");return r&&gi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"startsWith","str, prefix")},Vi={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=null!=e&&null!=n&&(e+"").endsWith(n+"");return r&&gi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"endsWith","str, suffix")},Fi={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const i=t.evaluationHistory;let o=n,s=r;if(null!=o&&null!=s&&o>s){const t=o;o=s,s=t}const a=null!=o&&null!=s&&e>=o&&s>=e;return i&&gi(this,t,[e,n,r],a,i?Date.now():0),a},validate:t=>Dt(t,3,"between","value, min, max")},Ui={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let i;if(e instanceof Element&&Ct(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{i=function(t,e){return oi.matches(t,e)}(e,t)}catch(t){i=!1}else i=!1}else if(Ct(e)&&Ct(n)){const t=e,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){i=t.includes(r)}}else i=!1;return gi(this,t,[e,n],i,r)}catch(i){throw gi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Dt(t,2,"matches","element, selector"),inputSchema:wi,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"]}},_i={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let o=!1;if(e instanceof Element&&Ct(n)){const t=n;t.startsWith(".")?o=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(o=e.hasAttribute(t.slice(1,-1)))}return r&&gi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"has","element, selector")},zi={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=!await _i.evaluate(t,e,n);return r&&gi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"doesNotHave","element, selector")},Wi={equals:Ei,strictEquals:xi,notEquals:ki,strictNotEquals:Si,lessThan:Ti,lessThanOrEqual:Ai,greaterThan:Ci,greaterThanOrEqual:$i,and:Oi,or:ji,not:Ni,no:Li,isEmpty:Ri,isNotEmpty:Ii,exists:Mi,doesNotExist:qi,contains:Hi,doesNotContain:Bi,startsWith:Di,endsWith:Vi,between:Fi,matches:Ui,has:_i,doesNotHave:zi};class Zi{trackPerformance(t,e,n,r){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(t,e,n,r=(n?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:e,duration:Date.now()-e,success:n})}toBoolean(t){return!(!1===t||0===t||0n===t||""===t||null==t||$t(t)&&isNaN(t))}success(t,e){return{success:!0,value:t,type:e}}failure(t,e,n,r,i=[]){return{success:!1,error:{name:t,type:e,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:!1,errors:[{type:t,message:e,suggestions:n}],suggestions:n}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":jt(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":Ct(t)?"String":$t(t)?"Number":Ot(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):Ct(t)?t.split(""):null==t?[]:jt(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if($t(t)&&Number.isFinite(t))return t;if(Ct(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Ot(t)?t?1:0:null}}const Ji=ei({value:ti().describe("String literal value")}).strict(),Ki=ei({value:function(t={}){return Xr?Yr():Gr({validate:e=>{const n=Number(e);return isNaN(n)?{success:!1,error:Kr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:!1,error:Kr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:!1,error:Kr("runtime-error","Number must be at most "+t.max)}:{success:!0,data:n}}})}(Yi||{}).describe("Number literal value")}).strict(),Xi=ei({value:(Xr?Yr():Gr({validate:t=>"boolean"!=typeof t?{success:!1,error:Kr("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}})).describe("Boolean literal value")}).strict(),Gi=ei({left:ri().describe("Left operand"),right:ri().describe("Right operand")}).strict();var Yi;const Qi={stringLiteral:new class extends Zi{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=Ji,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid){const e=this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(t,n,!1),e}let i=e.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,t));const o=this.success(i,"string");return this.trackSimple(t,n,!0,i),o}catch(e){return this.trackSimple(t,n,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let n=t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=this.resolveExpression(n.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,n)=>{try{const t=this.resolveVariable(n,e);return void 0!==t?t+"":""}catch(t){return""}}),n}resolveExpression(t,e){if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++)r=r[n[t]];return r}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?(at(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Zi{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Ki,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?Number.isFinite(e.value)?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Zi{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Xi,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Zi{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Gi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=li(e.left,"left operand")+li(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Zi{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=Gi,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,!0,i),this.success(i,"string")}catch(e){return this.trackSimple(t,n,!1),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=Gi.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(Ct(t))return t;if($t(t))return""+t;if(Ot(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Zi{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Gi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=li(e.left,"left operand")*li(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}},to={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const n=void 0!==e?e:t.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:Ct(n)?n.length>0?n[0]:null:jt(n)&&"length"in n&&$t(n.length)&&n.length>0?n[0]:null},validate:t=>zt(t,1,"first","collection")},eo={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const n=void 0!==e?e:t.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const t=n.children;return t.length>0?t[t.length-1]:null}return Ct(n)?n.length>0?n[n.length-1]:null:jt(n)&&"length"in n&&$t(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>zt(t,1,"last","collection")},no={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!$t(n))throw Error("Index must be a number");const i=n,o=void 0!==r?r:t.it;if(null==o)return null;if(Array.isArray(o)){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}if(o instanceof NodeList||o instanceof HTMLCollection){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}if(o instanceof Element){const t=o.children,e=0>i?t.length+i:i;return e>=0&&t.length>e?t[e]:null}if(Ct(o)){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}if(jt(o)&&"length"in o&&$t(o.length)){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}return null},validate:t=>Wt(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function ro(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;const t=n.querySelector(e);if(t)return t;n=n.nextElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?ro(r,e):null}function io(t,e){let n=t.previousElementSibling;for(;n;){const t=Array.from(n.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(n.matches(e))return n;n=n.previousElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?io(r,e):null}function oo(t,e,n,r){if(n.inSearch){if(null==n.inElt)return;return function(t,e,n,r){const i=Array.from(e??[]),o=[];for(const e of i)(e.matches&&e.matches(n)||e===t)&&o.push(e);for(let e=0;o.length-1>e;e++)if(o[e]===t)return o[e+1];if(r){const t=o[0];if(t&&t.matches&&t.matches(n))return t}}(t,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),e,!!n.wrapping)}const i=n.within??("undefined"!=typeof document?document.body:null);if(i)return r?function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=0;i.length>e;e++){const n=i[e];if(2===n.compareDocumentPosition(t))return n}return r?i[0]:void 0}(t,i,e,!!n.wrapping):function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=i.length-1;e>=0;e--){const n=i[e];if(4===n.compareDocumentPosition(t))return n}return r?i[i.length-1]:void 0}(t,i,e,!!n.wrapping)}function so(t){let e=0,n=t;for(;n&&n.parentElement;)e+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,e+=1e3;return e}const ao={first:to,last:eo,at:no,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r,i]=e,o=r||t.me;return o&&o instanceof Element?n?i?oo(o,n,i,!0):ro(o,n):o.nextElementSibling:null},validate:t=>zt(t,3,"next","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[n,r,i]=e,o=r||t.me;return o&&o instanceof Element?n?i?oo(o,n,i,!1):io(o,n):o.previousElementSibling:null},validate:t=>zt(t,3,"previous","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[n,r,i]=e,o=i||t.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=so(t);for(const t of r)if(so(t)>i)return t;return null}(o,n,s):null},validate:t=>Wt(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[n,r,i]=e,o=i||t.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=so(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(i>so(e))return e}return null}(o,n,s):null},validate:t=>Wt(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}};class co{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=li(t,"left operand");return{success:!0,value:fi(r+li(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:!1,errors:[yi("runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){const e=function(t){if(null==t)return pi([yi("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return pi([yi("type-mismatch","Expected object, got "+typeof t)],["Provide an object with left and right operands"]);const e=t;if(!("left"in e)||!("right"in e)){const t=[];return"left"in e||t.push("left"),"right"in e||t.push("right"),pi([yi("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return di(n)?di(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[yi("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[yi("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const lo={addition:new co,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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=li(t,"left operand");return{success:!0,value:fi(r-li(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:!1,errors:[yi("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new co).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=li(t,"left operand");return{success:!0,value:fi(r*li(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:!1,errors:[yi("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new co).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=!0){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(li(t,"left operand"),li(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[yi("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new co).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e){if(0===e)throw Error("Modulo by zero");return t%e}(li(t,"left operand"),li(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[yi("runtime-error","Modulo failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(t){return(new co).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=li(t,"left operand"),i=li(n,"right operand");return{success:!0,value:fi(Math.pow(r,i),"power"),type:"number"}}catch(t){return{success:!1,errors:[yi("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new co).validate(t)}}};function uo(){return Wr(Jr,Wi,Yt,ao,ne,Qi,lo)}var fo=Object.freeze({__proto__:null,conversion:Yt,conversionExpressions:Yt,createCommonRegistry:function(){return Wr(Jr,Wi,Qi,Yt,ao)},createCoreRegistry:function(){return Wr(Jr,Wi,Qi)},createExpressionRegistry:Wr,createFullExpressionRegistry:uo,createFullRegistry:function(){return Wr(Jr,Wi,Qi,Yt,ao,ne)},logical:Wi,logicalExpressions:Wi,positional:ao,positionalExpressions:ao,properties:ne,propertiesExpressions:ne,references:Jr,referencesExpressions:Jr,special:Qi,specialExpressions:Qi});function ho(t,e,n,r,i,o){function s(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?r.static?t:t.prototype:null,f=e||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),d=!1,h=n.length-1;h>=0;h--){var m={};for(var p in r)m[p]="access"===p?{}:r[p];for(var p in r.access)m.access[p]=r.access[p];m.addInitializer=function(t){if(d)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(t||null))};var y=(0,n[h])("accessor"===c?{get:f.get,set:f.set}:f[l],m);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=s(y.get))&&(f.get=a),(a=s(y.set))&&(f.set=a),(a=s(y.init))&&i.unshift(a)}else(a=s(y))&&("field"===c?i.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),d=!0}function mo(t,e,n){for(var r=arguments.length>2,i=0;e.length>i;i++)n=r?e[i].call(t,n):e[i].call(t);return r?n:void 0}function po(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}function yo(t){return function(e,n){Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function go(t){return{isBlocking:!1,hasBody:!1,version:"1.0.0",...t}}function bo(t){return()=>new t}function vo(t,e){return t?`[${t}] ${e}`:e}function wo(t,e,n){if(gt(t))return t;if(!t){const t=e.me;if(!t)throw Error(vo(n,"No target element \u2014 provide explicit target or ensure context.me is set"));return xo(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error(vo(n,'Context reference "me" is not available'));return xo(e.me)}if("it"===r){if(!gt(e.it))throw Error(vo(n,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===r){if(!e.you)throw Error(vo(n,'Context reference "you" is not available'));return xo(e.you)}const i=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw Error(vo(n,"DOM not available \u2014 cannot resolve element selector"));const o=i.querySelector(r);if(!o)throw Error(vo(n,"Element not found with selector: "+r));if(!gt(o))throw Error(vo(n,"Element found but is not an HTMLElement: "+r));return o}throw Error(vo(n,"Invalid target type: "+typeof t))}function Eo(t,e){if(Array.isArray(t))return t.filter(gt);if(bt(t))return Array.from(t).filter(gt);if(gt(t))return[t];if(!t){const t=e.me;return t&&gt(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&gt(e.me)?[e.me]:[];if("it"===n)return gt(e.it)?[e.it]:[];if("you"===n)return e.you&&gt(e.you)?[e.you]:[];const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let t=n;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.querySelectorAll(t);return Array.from(e).filter(gt)}}return[]}function xo(t){if(gt(t))return t;throw Error("Value is not an HTMLElement")}function ko(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(vo(n,'No "me" element in context'));if(!gt(e.me))throw Error(vo(n,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(vo(n,'No "it" value in context'));if(!gt(e.it))throw Error(vo(n,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(vo(n,'No "you" element in context'));if(!gt(e.you))throw Error(vo(n,"context.you is not an HTMLElement"));return e.you;default:throw Error(vo(n,"Unknown possessive: "+t))}}"function"==typeof SuppressedError&&SuppressedError;const So=["on","from","to","in","with","at"];async function To(t,e,n,r,i={},o){let s=t;if(i.filterPrepositions&&t&&(s=t.filter(t=>{const e=t;return"identifier"!==e?.type||"string"!=typeof e.name||!So.includes(e.name.toLowerCase())})),(!s||0===s.length)&&i.fallbackModifierKey&&o){const t=o[i.fallbackModifierKey];t&&(s=[t])}if(!s||0===s.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!gt(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of s){const i=await e.evaluate(t,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(gt(i))a.push(i);else if(bt(i)){const t=Array.from(i).filter(gt);a.push(...t)}else if(Array.isArray(i)){const t=i.filter(gt);a.push(...t)}else{if("string"!=typeof i){if(null==i)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`)}try{let t=i;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),o=Array.from(r).filter(gt);a.push(...o)}catch(t){throw Error(`Invalid CSS selector: "${i}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!gt(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}class Ao{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await To(t.args,e,n,r)}}(t,e,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>gt(t))||"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay)}showElement(t,e="block"){const n=t.dataset.originalDisplay;void 0!==n?(t.style.display=n||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let Co=(()=>{let t,e,n=[yo({name:"hide"})],r=[],i=Ao;var o=e=class extends i{constructor(){super(...arguments),this.mode="hide"}get metadata(){return o.metadata}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>gt(t))}};return po(e,"HideCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),mo(e,r),o=e})();const $o=bo(Co);let Oo=(()=>{let t,e,n=[yo({name:"show"})],r=[],i=Ao;var o=e=class extends i{constructor(){super(...arguments),this.mode="show"}get metadata(){return o.metadata}async execute(t,e){const n=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,n)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>gt(t))&&"string"==typeof e.defaultDisplay}};return po(e,"ShowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),mo(e,r),o=e})();const jo=bo(Oo);function No(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function Ro(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),n=t.indexOf("=");if(-1===n)return{name:t.trim()};const r=t.slice(0,n).trim();let i=t.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function Lo(t,e){for(const n of t)e(n);return t}function Io(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function Mo(t,e,n){const r=t.hasAttribute(e);void 0!==n?r&&t.getAttribute(e)===n?t.removeAttribute(e):t.setAttribute(e,n):r?t.removeAttribute(e):t.setAttribute(e,"")}function Po(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&Ho(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&Ho(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&Ho(n)?[n]:[]}function qo(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function Ho(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!qo(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function Bo(t,e){return t.map(t=>{if(qo(t)){const n=function(t){const e=t.trim(),n=e.match(/^\{(.+)\}$/);return n?n[1].trim():e}(t),r=e.locals.get(n)??e.globals.get(n);return null!=r?r+"":(Re(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}function Do(t){return"string"==typeof t&&t.trim().startsWith("*")}function Vo(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const n=e.substring(1).trim();return n?{property:n}:null}(t);if(!e)return null;const n=e.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function Fo(t,e,n){t.style.setProperty(e,n)}const Uo=["dialog","details","summary","select"];function _o(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function zo(t,e,n){return function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return!1;const n=_o(t);return"string"==typeof n&&n.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return!1;const n=_o(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:_o(t),extractedFromNode:!0}:function(t){if(!t||"object"!=typeof t)return!1;if("attributeAccess"===t.type)return!0;if("selector"===t.type||"cssSelector"===t.type){const e=_o(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:_o(r)),extractedFromNode:!0}:{value:await e.evaluate(t,n),extractedFromNode:!1};var r}class Wo{async resolveTargets(t,e,n,r){return To(t,e,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return zo(t,e,n)}parseClassNames(t){return Po(t)}isAttribute(t){return No(t.trim())}isCSSProperty(t){return Do(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>gt(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Zo=(()=>{let t,e,n=[yo({name:"add"})],r=[],i=Wo;var o=e=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return o.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:o}=function(t){const e=Ro(t);return{name:e.name,value:e.value??""}}(i);return{type:"attribute",name:r,value:o,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const o=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:o+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const i=this.parseClassNames(r);if(0===i.length)throw Error("add command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=Bo(t.classes,e);n.length>0&&Io(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,Lo(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":!function(t,e){Io(t,Object.entries(e),(t,[e,n])=>{t.style.setProperty(e,n)})}(t.targets,t.styles)}var n,r}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1;if("string"!=typeof t.value)return!1}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return!1;if(Array.isArray(e.styles))return!1;const n=e.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(t=>"string"==typeof t))return!1}return!0}};return po(e,"AddCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),o=e})();const Jo=bo(Zo),Ko={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function Xo(t){return t.includes("<")&&t.includes(">")}function Go(t,e,n){!function(t,e,n){"replace"!==n?gt(e)?function(t,e,n){switch(n){case"beforebegin":t.parentElement?.insertBefore(e,t);break;case"afterbegin":t.insertBefore(e,t.firstChild);break;case"beforeend":t.appendChild(e);break;case"afterend":t.parentElement?.insertBefore(e,t.nextSibling)}}(t,e,n):function(t,e,n){const r=n,i=["beforebegin","afterbegin","beforeend","afterend"];if(!i.includes(r))throw Error(`Invalid insert position '${n}'. Expected one of ${i.join(", ")} (or 'replace').`);Xo(e)?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e)}(t,e,n):function(t,e){gt(e)?(t.innerHTML="",t.appendChild(e)):Xo(e)?t.innerHTML=e:t.textContent=e}(t,e)}(t,e,function(t){const e=Ko[t];if(void 0===e)throw Error(`Unknown semantic position '${t}'. Valid positions: ${Object.keys(Ko).join(", ")}.`);return e}(n))}function Yo(t){return!!t.parentNode&&(t.remove(),!0)}let Qo=(()=>{let t,e,n=[yo({name:"remove"})],r=[],i=Wo;var o=e=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return o.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if(gt(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&gt(r[0]))return{type:"element",targets:r.filter(t=>gt(t))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:Ro(i).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const i=this.parseClassNames(r);if(0===i.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=Bo(t.classes,e);n.length>0&&Io(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,Lo(t.targets,t=>{t.removeAttribute(n)});break;case"styles":!function(t,e){Io(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)Yo(e)}var n}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return!1;return!0}};return po(e,"RemoveCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),o=e})();const ts=bo(Qo);function es(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function ns(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=es(t);return n?n.milliseconds:e}return e}function rs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=es(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function is(t){return t&&"none"!==t?t.split(",").map(t=>{const e=parseFloat(t.trim());return isNaN(e)?0:t.includes("s")&&!t.includes("ms")?1e3*e:e}):[0]}function os(t,e){let n=0;for(let r=0;t.length>r;r++)n=Math.max(n,(t[r]||0)+(e[r]||0));return n}function ss(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function as(t){return"DIALOG"===t.tagName}function cs(t){return"DETAILS"===t.tagName}function ls(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&Mo(t,n)}}function us(t,e,n,r){const i=ls(t,e,n),o=setTimeout(i,r);return()=>{clearTimeout(o)}}function fs(t,e,n,r){const i=ls(t,e,n),o=()=>{i(),t.removeEventListener(r,o)};return t.addEventListener(r,o,{once:!0}),()=>{t.removeEventListener(r,o)}}function ds(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(!1===n?t.removeAttribute(r):t.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(e){case"textContent":return void(t.textContent=r);case"innerHTML":return void(t.innerHTML=r);case"innerText":return void(t.innerText=r);case"id":return void(t.id=r);case"className":return void(t.className=r);case"value":return void("value"in t&&(t.value=r));case"checked":return void("checked"in t&&(t.checked=!!n))}if(e.includes(".")){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++)if(i=i[r[t]],null==i)return;return void(i[r[r.length-1]]=n)}if(e.includes("-")||e in t.style)t.style.setProperty(e,r);else try{t[e]=n}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}function hs(t){return null==t||""===t}const ms=/^the\s+(.+?)\s+of\s+(.+)$/i,ps=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 ys(t){return"string"==typeof t&&ms.test(t)}function gs(t,e){const n=t.match(ms);if(!n)return null;try{return{element:wo(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function bs(t,e,n){if(function(t){return!(!t||"object"!=typeof t)&&"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(t))return async function(t,e,n){const r=t.property?.name;if(!r)return null;let i=await e.evaluate(t.target,n);return Array.isArray(i)&&(i=i[0]),gt(i)?{element:i,property:r}:null}(t,e,n);if(function(t){return!(!t||"object"!=typeof t)&&"propertyAccess"===t.type&&("string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name)}(t))return async function(t,e,n){const r="string"==typeof t.property?t.property:t.property?.name;if(!r)return null;let i=await e.evaluate(t.object,n);return Array.isArray(i)&&(i=i[0]),gt(i)?{element:i,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,i=r.property;let o=await e.evaluate(t,n);if(Array.isArray(o)&&(o=o[0]),!gt(o))return null;const s=i?.name||i?.value;return s?{element:o,property:s}:null}return null}function vs(t){const{element:e,property:n}=t;return n.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,n.substring(1)):Ht(e,n)}function ws(t,e){const{element:n,property:r}=t;r.startsWith("*")?Fo(n,r.substring(1),e+""):ds(n,r,e)}async function Es(t,e,n){let r,i;if(t?.for){const i=await e.evaluate(t.for,n);r="number"==typeof i?i:"string"==typeof i?ns(i):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function xs(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return!1;if("identifier"!==t.type)return!1;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Uo.includes(e)}(e)}(e);if(gt(t)||Array.isArray(t)&&t.every(t=>gt(t)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Uo.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const ks=bo((()=>{let t,e,n=[yo({name:"toggle"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(t){if(!t||"asExpression"!==t.type)return!1;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=!0;const e=t.args[0].expression;t={...t,args:[e,...t.args.slice(1)]}}const i=t.args[0],o=i?.name;if("between"===o&&t.args.length>=4){const{duration:r,untilEvent:i}=await Es(t.modifiers,e,n),o=async t=>{const r=t;return"selector"===r?.type?r.value:e.evaluate(t,n)},s=await o(t.args[1]),a=await o(t.args[3]),c=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&c.push(t.args[e])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await To(c,e,n,"toggle",l,t.modifiers);return{type:"classes-between",classA:(s+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:i}}const s=await bs(i,e,n);if(s)return{type:"property",target:s};if("selector"===i.type&&"string"==typeof i.value&&i.value.startsWith("*")){let r=i.value,o=1;if("*"===r&&t.args.length>1&&"identifier"===t.args[1].type&&(r="*"+t.args[1].name,o=2),"*"===r&&t.modifiers?.on){const i=t.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:o,untilEvent:s}=await Es(t.modifiers,e,n),a=Vo(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:o,untilEvent:s}}}}const s=Vo(r);if(s){const{duration:r,untilEvent:i}=await Es(t.modifiers,e,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:s,targets:await To(t.args.slice(o),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await Es(t.modifiers,e,n),{value:l}=await zo(i,e,n);if(ys(l)){const t=gs(l,n);if(t)return{type:"property",target:t}}const{type:u,expression:f}=xs(l,i),d={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:i}=Ro(f);return{type:"attribute",name:r,value:i,targets:await To(t.args.slice(1),e,n,"toggle",d,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Vo(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await To(t.args.slice(1),e,n,"toggle",d,t.modifiers)}}case"element":{let o;if(gt(l))o=[l];else if(Array.isArray(l)&&l.every(t=>gt(t)))o=l;else if(f){const t=document.querySelectorAll(f);o=Array.from(t).filter(t=>gt(t))}else o=await To([i],e,n,"toggle",d,t.modifiers);const s=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(o);if("dialog"===s){const i=r?"modal":await async function(t,e,n,r){if(e?.as){const t=await n.evaluate(e.as,r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await n.evaluate(t[1],r);if("string"==typeof e){const i=e.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&t.length>=3){const e=await n.evaluate(t[2],r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,n);return{type:"dialog",mode:i,targets:o}}return"details"===s?{type:"details",targets:ss(o)}:"select"===s?{type:"select",targets:o}:{type:"classes",classes:Po(f),targets:o,duration:a,untilEvent:c}}default:{const r=Po(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await To(t.args.slice(1),e,n,"toggle",d,t.modifiers),duration:a,untilEvent:c}}}}async execute(t,e){switch(t.type){case"classes":{const n=Bo(t.classes,e);if(0===n.length)return[...t.targets];if(Io(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&us(e,"class",n[0],t.duration),t.untilEvent&&fs(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,Lo(t.targets,t=>{Mo(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&us(e,"attribute",t.name,t.duration),t.untilEvent&&fs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Lo(t.targets,e=>function(t,e){const n=window.getComputedStyle(t);switch(e){case"display":"none"===n.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=n.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=vs(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||ps.has(r)||ps.has(r.toLowerCase())){const n=!e;return ws(t,n),n}if("number"==typeof e){const n=0===e?1:0;return ws(t,n),n}if("string"==typeof e){const r="__ht_"+n,i=t.element[r];return""===e&&void 0!==i?(ws(t,i),i):(t.element[r]=e,ws(t,""),"")}ws(t,!e)}(t.target),[t.target.element];case"dialog":return Lo(t.targets,e=>{return r=t.mode,void((n=e).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return Lo(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Lo(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const n=e.classList.contains(t.classA),r=e.classList.contains(t.classB);n?(e.classList.remove(t.classA),e.classList.add(t.classB)):r?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&us(e,"class",t.classA,t.duration),t.untilEvent&&fs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}};return po(e,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})());const Ss=bo((()=>{let t,e,n=[yo({name:"put"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let o=-1,s=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&i.includes(c)){o=e,s=c;break}}let a=null,c=null;if(-1===o){const e=i.find(e=>t.modifiers[e]);if(e)a=t.args[0],s=e,c=t.modifiers[e];else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],s=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],s=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2]}else a=t.args.slice(0,o)[0]||null,c=t.args.slice(o+1)[0]||null;if(!a)throw Error("put requires content");if(!s)throw Error("put requires position keyword");const l=await e.evaluate(a,n),u=this.mapPosition(s);let f,d,h=null;if(c){const t=r(c),i=await bs(c,e,n);if(i)return{value:l,targets:[i.element],position:"into",memberPath:i.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)h=t.value;else if("identifier"===t?.type){const i=t.name;if("my"===i||"me"===i||"I"===i){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"into",memberPath:r.name}}else if("its"===i||"it"===i){const t=await e.evaluate(c,n);"string"==typeof t&&(h=t)}else h=i}if(h&&r?.name)f=r.name;else if(!h&&!f){const t=await e.evaluate(c,n);"string"==typeof t&&(h=t)}}else if("identifier"===t&&"me"===c.name)h=null;else if("selector"===t||"cssSelector"===t)h=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&ys(t)){const e=gs(t,n);if(e)return{value:l,targets:[e.element],position:"into",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?h=t:d=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))h=t;else{const r=Tt(await e.evaluate(c,n));if(r)return{value:l,targets:r,position:u,memberPath:f};d=t}}else{const t=await e.evaluate(c,n),r=Tt(t);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof t&&(this.looksLikeCss(t)?h=t:d=t)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(h,n),position:u,memberPath:f}}async execute(t,e){const{value:n,targets:r,position:i,memberPath:o,variableName:s}=t;if(s)return e.locals&&e.locals.set(s,n),e[s]=n,void Object.assign(e,{it:n});if(o)for(const t of r)this.setProperty(t,o,n);else for(const t of r)Go(t,this.parseValue(n),i);return r}mapPosition(t){switch(t){case"into":return"into";case"before":return"before";case"after":return"after";case"at start of":return"prepend";case"at end of":return"append";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!gt(e.me))throw Error("put: no target and context.me is null");return[e.me]}return St(t)}parseValue(t){return gt(t)?t:null==t?"":t+""}looksLikeCss(t){return!!t&&(!!/^[#.\[]/.test(t)||(!(!/[>+~\s]/.test(t)||1>=t.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(t.toLowerCase())))}setProperty(t,e,n){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++){if(!i[r[t]])throw Error(`Property path "${e}" does not exist`);i=i[r[t]]}i[r[r.length-1]]=n}};return po(e,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})()),Ts={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function As(t){return t.replace(/[&<>"']/g,t=>Ts[t])}let Cs=(()=>{let t,e,n=[yo({name:"make"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.modifiers.an??t.modifiers.a??t.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const i=r.raw;let o="string"==typeof i&&i.startsWith("<")?i:await e.evaluate(r,n);if(null==o)throw Error("Make command requires class name or DOM element expression");"string"==typeof o&&o.startsWith("<")&&(o=await async function(t,e){if(!t.includes("{"))return t;const n=/\{([^{}]+)\}/g,r=[];let i;for(;null!==(i=n.exec(t));){let t=i[0];try{const n=await cr(i[1].trim(),e);null!=n&&(t=As(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:t})}let o=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,text:i}=r[t];o=o.slice(0,e)+i+o.slice(e+n)}return o}(o,n));const s=void 0!==t.modifiers.an?"an":"a",a=await async function(t,e,n){if(!t)return[];if("arrayLiteral"===t.type&&Array.isArray(t.args)){const r=[];for(const i of t.args)r.push(await e.evaluate(i,n));return r}const r=await e.evaluate(t,n);return Array.isArray(r)?r:[r]}(t.modifiers.from,e,n),c=await async function(t,e,n){if(!t)return;if(("symbol"===t.type||"identifier"===t.type)&&"string"==typeof t.name)return t.name;const r=await e.evaluate(t,n);return"string"==typeof r?r:void 0}(t.modifiers.called,e,n);return{article:s,expression:o,constructorArgs:a,variableName:c}}async execute(t,e){const{expression:n,constructorArgs:r=[],variableName:i}=t,o="string"==typeof n&&n.startsWith("<"),s=o&&n.endsWith("/>")?function(t){const e=t.slice(1,-2);let n="div",r=e;const i=e.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=e.slice(i[0].length));const o=document.createElement(n),s=r.split(/(?=[.#])/);for(const t of s)if(t.startsWith("#")){const e=t.slice(1);e&&(o.id=e)}else if(t.startsWith(".")){const e=t.slice(1);e&&o.classList.add(e)}return o}(n):o&&/<\/[a-zA-Z]/.test(n)?function(t){const e=document.createElement("template");e.innerHTML=t.trim();const n=e.content.firstElementChild;if(n&&gt(n))return n;const r=document.createElement("div");r.innerHTML=t.trim();const i=r.firstElementChild;return i&&gt(i)?i:r}(n):function(t,e,n){if(gt(t))return t;const r=t+"";let i;if("undefined"!=typeof window&&(i=window[r]),i||"undefined"==typeof global||(i=global[r]),!i&&n.variables?.has(r)&&(i=n.variables.get(r)),!i||"function"!=typeof i)throw Error(`Constructor '${r}' not found or is not a function`);return 0===e.length?new i:new i(...e)}(n,r,e);return Object.assign(e,{it:s}),i&&Et(i,s,e),s}};return po(e,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})();const $s=bo(Cs),Os=bo((()=>{let t,e,n=[yo({name:"empty"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await To(t.args,e,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.innerHTML=""}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return po(e,"EmptyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})());function js(t){if("string"!=typeof t)return;const e=t.toLowerCase().trim();return"non-modal"===e||"nonmodal"===e?"non-modal":"modal"===e?"modal":void 0}function Ns(t){return t.hasAttribute("popover")}const Rs=bo((()=>{let t,e,n=[yo({name:"open"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=(t.args??[]).filter(t=>{const e=t;if("identifier"!==e?.type)return!0;const n=e.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=ss(await To(r,e,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)),o=await async function(t,e,n,r){if(e?.as){const t=js(await n.evaluate(e.as,r));if(t)return t}for(const e of t){const t=e;if("asExpression"!==t?.type)continue;const n=t.targetType,r=js(n?.name??n?.value);if(r)return r}for(let e=0;t.length-1>e;e++){const i=t[e];if("identifier"===i?.type&&"as"===i.name?.toLowerCase()){const i=await n.evaluate(t[e+1],r);if("string"==typeof i){const t=i.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}}return"modal"}(t.args??[],t.modifiers??{},e,n);return{targets:i,dialogMode:o}}async execute(t,e){for(const e of t.targets)if(as(e))e.open||("modal"===t.dialogMode?e.showModal():e.show());else if(cs(e))e.open=!0;else if(Ns(e)){const t=e;if("function"==typeof t.showPopover)try{t.showPopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>gt(t))||"modal"!==e.dialogMode&&"non-modal"!==e.dialogMode)}};return po(e,"OpenCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})());function Ls(t){return t.hasAttribute("popover")}const Is=bo((()=>{let t,e,n=[yo({name:"close"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:ss(await To(t.args,e,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers))}}async execute(t,e){for(const e of t.targets)if(as(e))e.open&&e.close();else if(cs(e))e.open=!1;else if(Ls(e)){const t=e;if("function"==typeof t.hidePopover)try{t.hidePopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return po(e,"CloseCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})());function Ms(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e}const Ps=bo((()=>{let t,e,n=[yo({name:"select"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await To(t.args,e,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if(0!==t.targets.length)for(const e of t.targets){if(Ms(e)){e.select();continue}const t=e.ownerDocument??("undefined"!=typeof document?document:null),n=t?.defaultView;if(!t||!n)continue;const r=n.getSelection?.();if(r)try{const n=t.createRange();n.selectNodeContents(e),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return po(e,"SelectCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})());function qs(t){return"FORM"===t.tagName}const Hs=bo((()=>{let t,e,n=[yo({name:"reset"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await To(t.args,e,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)qs(e)&&e.reset()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return po(e,"ResetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),mo(e,r),i=e})());function Bs(t,e,n,r){return t?new Promise(n=>{const i=()=>{o({event:null,timedOut:!1,cancelled:!0})},o=Vs(()=>{t.removeEventListener(e,s),r&&r.removeEventListener("abort",i)},n),s=t=>{o({event:t,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(t.addEventListener(e,s),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function Ds(t){return new Promise(e=>setTimeout(e,t))}function Vs(t,e){let n=!1;return r=>{n||(n=!0,t(),e(r))}}const Fs=bo((()=>{let t,e,n=[yo({name:"wait"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,n);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n);const r=t.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,t.args[1],e,n):this.parseTimeWait(t.args[0],e,n)}async execute(t,e){const n=Date.now();if("time"===t.type)return await Ds(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,i=(await Bs(r,t.eventName)).event;if(Object.assign(e,{it:i}),t.destructure)for(const n of t.destructure)n in i&&e.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const t of i.destructure)t in r&&e.locals.set(t,r[t]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(t,e,n){return{type:"time",milliseconds:rs(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const i=await n.evaluate(t,r);if("string"!=typeof i)throw Error("wait for: event name must be a string");const o=i.match(/^(\w+)\(([^)]+)\)$/),s=o?o[1]:i,a=o?o[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await n.evaluate(e,r);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=r.me??void 0;return{type:"event",eventName:s,target:c,destructure:a}}async parseEventArrayWait(t,e,n,r){let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}i||(i=r.me??void 0);const o=[];for(const e of t){const t=e;if("objectLiteral"!==t.type||!t.properties)continue;let s,a="",c=[];for(const e of t.properties){const t=e.key?.name||e.key?.value;"name"===t&&e.value?a=e.value.value||"":"args"===t&&e.value?.elements?c=e.value.elements.map(t=>t.value||t.name||""):"duration"===t&&e.value&&(s=e.value)}if(s){const t=await n.evaluate(s,r);o.push({type:"time",milliseconds:rs(t)})}else a&&o.push({type:"event",eventName:a,target:i,destructure:c.length>0?c:void 0})}return 1===o.length?o[0]:{type:"race",conditions:o}}async parseRaceCondition(t,e,n){const r=[];t.modifiers.for?r.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n)):t.args[0]&&r.push(await this.parseTimeWait(t.args[0],e,n));const i=await e.evaluate(t.modifiers.or,n),o=Array.isArray(i)?i:[i];for(const t of o)try{r.push({type:"time",milliseconds:rs(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);r.push(e?{type:"event",eventName:e[1],target:n.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(t,e){const n=new AbortController,r=n.signal,i=t.map(t=>"time"===t.type?Ds(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Bs(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(i)}finally{n.abort()}}};return po(e,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"async",compatibility:"standard"}),mo(e,r),i=e})()),Us=new Map;let _s=[/^4\d{2}$/,/^5\d{2}$/],zs=(()=>{let t,e,n=[yo({name:"fetch"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(t.args[0],e,n),i=this.parseResponseType(t.modifiers.as);return{url:r,responseType:i,options:await this.parseRequestOptions(t.modifiers.with,e,n),throwOnError:!t.modifiers.doNotThrow&&"response"!==i}}async execute(t,e){const n=Date.now(),{url:r,responseType:i,options:o}=t,s=new AbortController;let a;e.me&&(a=()=>s.abort(),e.me.addEventListener("fetch:abort",a,{once:!0}));const c={...o,signal:s.signal},l=Us.get(i);if(l?.accept){const t=new Headers(c.headers);t.has("Accept")||t.set("Accept",l.accept),c.headers=t}if(e.me){const t={...c,sender:e.me,headers:c.headers||{}};this.dispatchEvent(e.me,"fetch:beforeRequest",t),c.headers=t.headers}let u;o.timeout&&(u=setTimeout(()=>s.abort(),o.timeout));try{let o=await fetch(r,c);if(e.me){const t={response:o};this.dispatchEvent(e.me,"fetch:afterResponse",t),o=t.response}if(t.throwOnError&&function(t){const e=t+"";return _s.some(t=>t.test(e))}(o.status)){const t=Error(`Fetch failed for ${r}: HTTP ${o.status} ${o.statusText}`.trim());throw t.response=o,t.isFetchStatusError=!0,t}const s=await this.handleResponse(o,i,e);e.me&&this.dispatchEvent(e.me,"fetch:afterRequest",{result:s});const a={status:o.status,statusText:o.statusText,headers:o.headers,data:s,url:o.url,duration:Date.now()-n};return Object.assign(e,{it:s}),a}catch(t){if(e.me&&this.dispatchEvent(e.me,"fetch:error",{reason:t instanceof Error?t.message:t+"",error:t}),t instanceof Error&&"AbortError"===t.name)throw Error("Fetch aborted for "+r);if(t instanceof Error&&!0===t.isFetchStatusError)throw t;throw Error(`Fetch failed for ${r}: ${t instanceof Error?t.message:t+""}`)}finally{u&&clearTimeout(u),e.me&&a&&e.me.removeEventListener("fetch:abort",a)}}async parseURL(t,e,n){const r=await e.evaluate(t,n);if("string"!=typeof r||!r){const e=t;if(null==r&&"identifier"===e?.type&&e.name)throw Error(`fetch: URL expression "${e.name}" evaluated to ${r+""} \u2014 check the variable is set, or quote it if you meant a literal URL (fetch 'https://example.com/path')`);throw Error("fetch: URL must be a non-empty string")}return r}parseResponseType(t){if(!t)return"text";if(("identifier"===t.type||"expression"===t.type)&&t.name){const e=t.name.toLowerCase();if("object"===e)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(e))return"arraybuffer"===e?"arrayBuffer":e;if(Us.has(e))return e;throw Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(t,e,n){if(!t)return{};const r=await e.evaluate(t,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const i={};return"method"in r&&(i.method=(r.method+"").toUpperCase()),"headers"in r&&(i.headers=this.parseHeaders(r.headers)),"body"in r&&(i.body=this.parseBody(r.body)),"credentials"in r&&(i.credentials=r.credentials),"mode"in r&&(i.mode=r.mode),"cache"in r&&(i.cache=r.cache),i}parseHeaders(t){if(t instanceof Headers)return t;const e=new Headers;if("object"==typeof t&&null!==t)for(const[n,r]of Object.entries(t))e.set(n,r+"");return e}parseBody(t){return null==t?null:t instanceof FormData||t instanceof Blob||t instanceof ArrayBuffer||t instanceof URLSearchParams||"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):t+""}async handleResponse(t,e,n){switch(e){case"response":return t;case"json":return t.json();case"html":return this.parseHTML(await t.text());case"blob":return t.blob();case"arrayBuffer":return t.arrayBuffer();case"text":return t.text();default:{const r=Us.get(e);return r?r.handler(t,n):t.text()}}}parseHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),n=document.createDocumentFragment();return Array.from(e.body.childNodes).forEach(t=>n.appendChild(t.cloneNode(!0))),1===n.childNodes.length&&gt(n.firstChild)?n.firstChild:n}dispatchEvent(t,e,n){t.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,cancelable:!0}))}};return po(e,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"async",compatibility:"standard"}),mo(e,r),i=e})();const Ws=bo(zs);async function Zs(t,e,n){const r=await e.evaluate(t,n),i=Array.isArray(r)?r[0]:r;return gt(i)?i:null}async function Js(t,e,n,r){if(!t)return null;const i=t,o=i.type;if(r.nodeWriters&&o){const e=it(o);if(e)return{kind:"node-write",node:t,writer:e}}if(r.selectorSource&&"selector"===o&&"string"==typeof i.value)return{kind:"selector",selector:i.value};const s=await async function(t,e,n,r){const i=t;if("attributeAccess"===i?.type)return{elements:await r(),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const t=await Zs(i.right,e,n);if(t)return{elements:[t],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const t=await Zs(i.object,e,n);if(t)return{elements:[t],name:i.property.attributeName}}return null}(t,e,n,r.scopeElements);if(s)return{kind:"attribute",elements:s.elements,name:s.name};const a=await bs(t,e,n);if(a)return r.styleSplit&&a.property.startsWith("*")?{kind:"style",element:a.element,property:a.property.substring(1)}:{kind:"property",target:a};if(r.bareReference&&("identifier"===o||"variable"===o||"symbol"===o)&&"string"==typeof i.name){const t=i.scope;return{kind:"variable",name:i.name,scope:"element"===t||"global"===t?t:void 0}}return null}const Ks=bo((()=>{let t,e,n=[yo({name:"set"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],i=r?.name||r?.value,o=r?.scope,s=await Js(r,e,n,{scopeElements:()=>this.resolveTargets(t.modifiers.on,e,n),nodeWriters:!0,styleSplit:!0});if(s)return function(t,e){switch(t.kind){case"node-write":return{type:"node-write",node:t.node,value:e,writer:t.writer};case"attribute":return{type:"attribute",elements:t.elements,name:t.name,value:e};case"style":return{type:"style",element:t.element,property:t.property,value:e+""};case"property":return{type:"property",element:t.target.element,property:t.target.property,value:e};default:throw Error(`set: unrequested write-target rung '${t.kind}'`)}}(s,await this.extractValue(t,e,n));if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,t,e,n);if(i)return i}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await e.evaluate(r,n):i,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;if(gt(t)||t instanceof Node)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(ys(a)){const r=gs(a,n);if(r){const i=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(a,t,e,n)}if("string"==typeof a&&Do(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:i+""}}if("string"==typeof a&&No(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"attribute",elements:await this.resolveTargets(t.modifiers.on,e,n),name:r,value:i}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=ko(r[1],n),o=await this.extractValue(t,e,n);return{type:"property",element:i,property:r[2],value:o}}}if(gt(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&gt(a[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(t,e,n),scope:"element"===o||"global"===o?o:void 0}}async execute(t,e){switch(t.type){case"variable":return"element"===t.scope?mt(e,t.name,t.value):"global"===t.scope?Et(t.name,t.value,e,"global"):Et(t.name,t.value,e),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":for(const e of t.elements)e.setAttribute(t.name,t.value+"");return Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return ds(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Fo(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[n,r]of Object.entries(t.properties))ds(e,n,r);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};case"node-write":return await t.writer(t.node,t.value,e),Object.assign(e,{it:t.value}),{target:t.node.name??"",value:t.value,targetType:"variable"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,n,r){const i=t.object,o=t.property;if(i?.name&&o?.name){const t=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const i=ko(t,r),s=await this.extractValue(e,n,r);return{type:"property",element:i,property:o.name,value:s}}}const s=t.object,a=t.computed;if(s){const i=s;let c;if("memberExpression"===i.type&&!i.computed&&"style"===i.property?.name&&i.object){const t=await n.evaluate(i.object,r);c=(t&&"object"==typeof t&&"style"in t?t.style:void 0)??await n.evaluate(s,r)}else c=await n.evaluate(s,r);if(null!=c&&"object"==typeof c){const i=a?await n.evaluate(t.property,r)+"":o?.name||"";if(i)return{type:"member-assignment",container:c,property:i,value:await this.extractValue(e,n,r)}}}return null}async extractValue(t,e,n){if(t.modifiers.to)return e.evaluate(t.modifiers.to,n);const r=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(r>=0&&t.args.length>r+1)return e.evaluate(t.args[r+1],n);if(t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,n){return wo(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return Eo(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const i=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw Error('Invalid "the X of Y" syntax');const[,o,s]=i,a=wo(s,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:o.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return!1;const e=t;if(!e.type||"string"!=typeof e.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return!1;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Array.isArray(e.elements)&&e.elements.every(gt)&&"value"in e;case"property":return"string"==typeof e.property&&gt(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&gt(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return!1}}};return po(e,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"data",compatibility:"standard"}),mo(e,r),i=e})()),Xs=bo((()=>{let t,e,n=[yo({name:"get"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("get command requires an expression argument");const r=t.args[0],i=await e.evaluate(r,n);return i instanceof NodeList&&1===i.length||Array.isArray(i)&&1===i.length?{value:i[0]}:{value:i}}execute(t,e){return e.it=t.value,Object.assign(e,{result:t.value}),{value:t.value}}validate(t){return"object"==typeof t&&null!==t&&"value"in t}};return po(e,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"data",compatibility:"standard"}),mo(e,r),i=e})());function Gs(t){return t&&"object"==typeof t&&t.type||"unknown"}let Ys=(()=>{let t,e,n=[yo({name:"increment"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="decrement"===t.commandName?.toLowerCase()?"decrement":"increment",i=await async function(t,e,n,r){if(!t.args||0===t.args.length)throw Error(r+" command requires a target");const i=t.args[0];let o,s,a;const c=Gs(i);if("identifier"===c)o=i.name,i.scope&&(s=i.scope);else if("literal"===c)o=i.value;else{const t=it(c);if(t){const r=await e.evaluate(i,n),s="number"==typeof r?r:null==r?0:Number(r)||0;o=s,a={node:i,writer:t,currentValue:s}}else{const t=await e.evaluate(i,n);o=Array.isArray(t)&&t.length>0?t[0]:t}}let l=1,u=s;for(let r=1;t.args.length>r;r++){const i=t.args[r];if(i&&"literal"===i.type){const t=i.value;"global"===t?u="global":"number"==typeof t&&(l=t)}else if(i&&"literal"!==i.type){const t=await e.evaluate(i,n);"number"==typeof t&&(l=t)}}const f=t.modifiers?.by;if(f){const t=f.value;if("literal"===Gs(f)&&"number"==typeof t)l=t;else if("literal"!==Gs(f)){const t=await e.evaluate(f,n);"number"==typeof t&&(l=t)}}return{target:o,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(t,e,n,r);return{...i,operation:r}}async execute(t,e){const{target:n,property:r,scope:i,amount:o=1,operation:s="increment",customWrite:a}=t;if(a){const t=isFinite(o)?o:1,n="increment"===s?a.currentValue+t:a.currentValue-t;return await a.writer(a.node,n,e),Object.assign(e,{it:n}),n}const c=function(t,e,n,r){if("number"==typeof t)return t;if(gt(t)){const n=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?vt(n.getAttribute(e)):vt(n[e]):vt(n.value||n.textContent)}return"string"==typeof t?"element"===n?vt(wt(t,r,"element")):"global"===n?vt(wt(t,r,"global")):t.includes(".")?function(t,e){const n=t.split("."),r=n[1],i=xt(n[0],e);return i?vt(i[r]):0}(t,r):vt("me"===t&&r.me?r.me.value||0:"it"===t?r.it||0:"you"===t&&r.you?r.you.value||0:wt(t,r)):vt(t)}(n,r,i,e);let l;if(isNaN(c))l=NaN;else{const t=isFinite(o)?o:1;l="increment"===s?c+t:c-t}return function(t,e,n,r,i){if(gt(t)){const n=t;return void(e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?n.setAttribute(e,r+""):n[e]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof t){if("element"===n)return void Et(t,r,i,"element");if("global"===n)return void Et(t,r,i,"global");if(t.includes("."))return void function(t,e,n){const r=t.split("."),i=r[1],o=xt(r[0],n);o&&(o[i]=e)}(t,r,i);if("me"===t&&i.me)return void(i.me.value=r);if("it"===t)return void Object.assign(i,{it:r});if("you"===t&&i.you)return void(i.you.value=r);Et(t,r,i)}}(n,r,i,l,e),Object.assign(e,{it:l}),l}};return po(e,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"data",compatibility:"standard"}),mo(e,r),i=e})();const Qs=bo(Ys),ta=bo(Ys),ea=bo((()=>{let t,e,n=[yo({name:"default"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("default command requires a target");const r=await this.extractValue(t,e,n),i=t.args[0],o=function(t){if("contextReference"!==t?.type)return null;const e=t.name;return"string"!=typeof e?null:e.startsWith(":")?{name:e.slice(1),scope:"element"}:e.startsWith("$")?{name:e.slice(1),scope:"global"}:null}(i);if(o)return{type:"variable",name:o.name,value:r,scope:o.scope};const s=await Js(i,e,n,{scopeElements:async()=>n.me?[n.me]:[],bareReference:!0});if(s)return function(t,e){switch(t.kind){case"attribute":return{type:"attribute",elements:t.elements,name:t.name,value:e};case"property":return{type:"property",element:t.target.element,property:t.target.property,value:e};case"variable":{const n=t.name.startsWith("$"),r=n?t.name.slice(1):t.name,i=n?"global":t.scope;return{type:"variable",name:r,value:e,...i?{scope:i}:{}}}default:throw Error(`default: unrequested write-target rung '${t.kind}'`)}}(s,r);const a=await e.evaluate(t.args[0],n);if(gt(a))return{type:"element",element:a,value:r};if(Array.isArray(a)&&gt(a[0]))return{type:"element",element:a[0],value:r};if("string"==typeof a)return{type:"variable",name:a,value:r};throw Error("Invalid target type: "+typeof a)}async extractValue(t,e,n){if(t.modifiers?.to)return e.evaluate(t.modifiers.to,n);const r=t.args[1],i="identifier"===r?.type&&"to"===(r.name+"").toLowerCase();if(i&&t.args.length>=3)return e.evaluate(t.args[2],n);if(!i&&t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('default command requires a value (use "to <value>")')}async execute(t,e){switch(t.type){case"variable":return this.defaultVariable(e,t.name,t.value,t.scope);case"attribute":return this.defaultAttribute(e,t.elements,t.name,t.value);case"property":return this.defaultElementProperty(e,t.element,t.property,t.value);case"element":return this.defaultElementValue(e,t.element,t.value)}}defaultVariable(t,e,n,r){const i=wt(e,t,r);return null!=i?{target:e,value:n,wasSet:!1,existingValue:i,targetType:"variable"}:(Et(e,n,t,r),Object.assign(t,{it:n}),{target:e,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(t,e,n,r){if(0===e.length)throw Error("No element context available for attribute default");const i=e.filter(t=>null===t.getAttribute(n));if(0===i.length)return{target:"@"+n,value:r,wasSet:!1,existingValue:e[0].getAttribute(n),targetType:"attribute"};for(const t of i)t.setAttribute(n,r+"");return Object.assign(t,{it:r}),{target:"@"+n,value:r,wasSet:!0,targetType:"attribute"}}defaultElementProperty(t,e,n,r){const i=function(t,e){if(e.startsWith("@"))return t.getAttribute(e.substring(1));switch(e){case"textContent":return t.textContent;case"innerHTML":return t.innerHTML;case"innerText":return t.innerText;case"id":return t.id;case"className":return t.className;case"value":return"value"in t?t.value:void 0;case"checked":return"checked"in t?t.checked:void 0}if(e.includes(".")){const n=e.split(".");let r=t;for(const t of n){if(null==r)break;r=r[t]}return r}return e.includes("-")||e in t.style?t.style.getPropertyValue(e)||t.style[e]:t[e]}(e,n);return hs(i)?(ds(e,n,r),Object.assign(t,{it:r}),{target:n,value:r,wasSet:!0,targetType:"property"}):{target:n,value:r,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(t,e,n){const r=function(t){return"value"in t?t.value:t.textContent}(e);return hs(r)?(function(t,e){"value"in t?t.value=e+"":t.textContent=e+""}(e,n),Object.assign(t,{it:n}),{target:"element",value:n,wasSet:!0,targetType:"element"}):{target:"element",value:n,wasSet:!1,existingValue:r,targetType:"element"}}};return po(e,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"data",compatibility:"standard"}),mo(e,r),i=e})());function na(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e||"SELECT"===e}const ra=bo((()=>{let t,e,n=[yo({name:"clear"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.args?.[0],i=r?.type,o=r?.name;if(r&&("variable"===i||"identifier"===i&&"string"==typeof o))try{const t=await e.evaluate(r,n);if(!gt(t)&&!Array.isArray(t))return{type:"variable",name:o}}catch{return{type:"variable",name:o}}return{type:"form-fields",targets:await To(t.args,e,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if("variable"===t.type)return e.locals.set(t.name,null),void Object.assign(e,{it:null});for(const e of t.targets)na(e)&&("SELECT"===e.tagName?e.selectedIndex=-1:e.value="")}validate(t){if("object"!=typeof t||null===t)return!1;if("variable"===t.type)return"string"==typeof t.name;if("form-fields"===t.type){const e=t.targets;return Array.isArray(e)&&e.every(t=>gt(t))}return!1}};return po(e,"ClearCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"data",compatibility:"standard"}),mo(e,r),i=e})());function ia(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e||"false"!==e&&("null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0)}let oa=(()=>{let t,e,n=[yo({name:"trigger"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",i=r;if(!t.args?.length)throw Error(i+" command requires an event name");const o=t=>t?.type||"unknown",s=t.args[0];let a,c,l;if("functionCall"===o(s)||"callExpression"===o(s)){a=s.name||s.callee?.name;const t=s.args||s.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===o(s)||"keyword"===o(s))a=s.name;else{const t=await e.evaluate(s,n);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,n,i);else{const r=t.args.findIndex((t,e)=>{if(0===e)return!1;const n=t.name||t.value;return"on"===n||"to"===n});if(-1!==r&&t.args.length-1>r){const o=t.args.slice(r+1),s=o.findIndex(t=>"with"===(t.name||t.value)),a=-1===s?o:o.slice(0,s);l=await this.resolveTargets(a,e,n,i)}else{if(!n.me)throw Error(i+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(n);e.it=n}async resolveTargets(t,e,n,r){const i=[];for(const r of t){const t=await e.evaluate(r,n);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&n.me)i.push(n.me);else if("you"===t&&n.you)i.push(n.you);else if("it"===t&&n.it)i.push(n.it);else if(gt(t))i.push(t);else if(t instanceof NodeList)i.push(...Array.from(t).filter(gt));else if(Array.isArray(t))i.push(...t.filter(gt));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);i.push(...Array.from(e).filter(gt));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);i.push(t)}else i.push(document);else i.push(window)}if(!i.length)throw Error(r+": no valid targets");return i}async parseEventDetail(t,e,n){if(!t?.length)return;if(1===t.length){const r=t[0];if("objectLiteral"!==r?.type)return await e.evaluate(r,n)}const r={};for(const i of t){const t=await e.evaluate(i,n);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,n]=t.split(":",2);r[e.trim()]=ia(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:!0,cancelable:!0,composed:!1},i=t.findIndex(t=>"with"===(t.name||t.value));if(-1===i)return r;for(const o of t.slice(i+1)){const t=await e.evaluate(o,n);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?r.bubbles=!0:"nobubbles"===e?r.bubbles=!1:"cancelable"===e?r.cancelable=!0:"nocancelable"===e?r.cancelable=!1:"composed"===e&&(r.composed=!0)}}return r}};return po(e,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"event",compatibility:"standard"}),mo(e,r),i=e})();const sa=bo(oa),aa=bo(oa),ca=bo((()=>{let t,e,n=[yo({name:"go"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{args:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{args:[]}}async execute(t,e){const{args:n}=t;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,e),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,e),type:"scroll"}}isUrlNavigation(t){return-1!==t.findIndex(t=>"url"===t)}isBareUrl(t){return!!t.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(t)}findBareUrl(t){for(const e of t)if("to"!==e&&"the"!==e)return"string"==typeof e&&this.isBareUrl(e)?e:null;return null}async navigateToBareUrl(t,e){if(e.includes("new")&&e.includes("window")){if("undefined"!=typeof window&&window.open){const e=window.open(t,"_blank");e?.focus&&e.focus()}}else t.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=t):"undefined"!=typeof window&&(window.location.assign?.(t)??(window.location.href=t));return t}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(t,e){const n=t.findIndex(t=>"url"===t),r=t[n+1];if(!r)throw Error('URL is required after "url" keyword');const i="string"==typeof r?r:r+"",o=t.includes("new")&&t.includes("window");if(!this.isValidUrl(i))throw Error(`Invalid URL: "${i}"`);if(o){if("undefined"!=typeof window&&window.open){const t=window.open(i,"_blank");t?.focus&&t.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(t){try{return t.startsWith("/")||t.startsWith("#")||new URL(t),!0}catch{return!1}}async scrollToElement(t,e){const n=this.parseScrollPosition(t),r=this.parseScrollTarget(t),i=this.parseScrollOffset(t),o=!t.includes("instantly"),s=this.resolveScrollTarget(r,e);if(!s)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const t=o?"smooth":"instant",e=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){s.scrollIntoView?.({behavior:t,block:e,inline:r});const{x:o,y:a}=this.calculateScrollPosition(s,n,i);window.scrollTo?.({left:o,top:a,behavior:t})}else s.scrollIntoView?.({behavior:t,block:e,inline:r})}return s}mapVerticalPosition(t){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[t]||"start"}mapHorizontalPosition(t){return{left:"start",center:"center",right:"end",nearest:"nearest"}[t]||"nearest"}parseScrollPosition(t){const e={vertical:"top",horizontal:"nearest"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,o=!1;for(const s of t)"string"==typeof s&&(n.includes(s)?(e.vertical=s,i=!0):r.includes(s)&&(e.horizontal=s,o=!0));return o&&!i&&(e.vertical="nearest"),e}parseScrollTarget(t){const e=t.findIndex(t=>"of"===t);if(-1!==e&&t.length>e+1){let n=t[e+1];return"the"===n&&t.length>e+2&&(n=t[e+2]),n}for(const e of t)if("object"==typeof e&&e&&e.nodeType)return e;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const e of t)if("string"==typeof e&&!n.includes(e)&&(e.startsWith("#")||e.startsWith(".")||e.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(e)))return e;return"body"}parseScrollOffset(t){for(let e=0;t.length>e;e++){const n=t[e];if("string"==typeof n){const t=n.match(/^([+-]?\d+)(px)?$/);if(t)return parseInt(t[1],10)}if(("+"===n||"-"===n)&&t.length>e+1){const r=t[e+1],i="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(t,e){if("object"==typeof t&&t&&t.nodeType)return t;const n="string"==typeof t?t:t+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&gt(e.me))return e.me;if("it"===n&&gt(e.it))return e.it;if("you"===n&&gt(e.you))return e.you;const r=wt(n,e);if(gt(r))return r;if("undefined"!=typeof document)try{const t=document.querySelector(n);if(t)return t}catch{try{const t=document.getElementsByTagName(n);if(t.length>0)return t[0]}catch{}}return null}calculateScrollPosition(t,e,n){if("undefined"==typeof window||!t.getBoundingClientRect)return{x:0,y:0};const r=t.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,o=window.pageYOffset||document.documentElement?.scrollTop||0,s=window.innerWidth||800,a=window.innerHeight||600;let c=i,l=o;switch(e.horizontal){case"left":c=r.left+i;break;case"center":c=r.left+i+r.width/2-s/2;break;case"right":c=r.right+i-s}switch(e.vertical){case"top":l=r.top+o+n;break;case"middle":l=r.top+o+r.height/2-a/2+n;break;case"bottom":l=r.bottom+o-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}};return po(e,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"navigation",compatibility:"standard"}),mo(e,r),i=e})());function la(t,e){if("boolean"==typeof t)return t;if("function"==typeof t)return!0;if(t instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof t){if("me"===t)return!!e.me;if("it"===t)return!!e.it;if("you"===t)return!!e.you;const n=wt(t,e);return void 0!==n?!!n:!!t}return!!t}const ua=bo((()=>{let t,e,n=[yo({name:"if"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="unless"===t.commandName?.toLowerCase()?"unless":"if";if(!t.args||0===t.args.length)throw Error(r+" command requires a condition to evaluate");let i,o;if("unless"===r){if(2>t.args.length)throw Error("unless command requires a condition and at least one command");i=t.args[1]}else if(t.args.length>=2&&t.args[1]?(i=t.args[1],o=3>t.args.length?void 0:t.args[2]):t.modifiers?.then&&(i=t.modifiers.then,o=t.modifiers.else),!i)throw Error('if command requires "then" branch with commands');return{mode:r,condition:await e.evaluate(t.args[0],n),thenCommands:i,elseCommands:o}}async execute(t,e){const{mode:n,condition:r,thenCommands:i,elseCommands:o}=t,s=la(r,e);let a,c;return("unless"===n?!s:s)?(a="then",c=await this.executeCommandsOrBlock(i,e)):o&&"if"===n?(a="else",c=await this.executeCommandsOrBlock(o,e)):a="none",{mode:n,conditionResult:s,executedBranch:a,result:c}}async executeCommandsOrBlock(t,e){return"block"===t?.type?this.executeBlock(t,e):this.executeCommands(Array.isArray(t)?t:[t],e)}async executeBlock(t,e){const n=e.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let r;if(t.commands?.length)for(const i of t.commands)r=await n(i,e);return r}async executeCommands(t,e){let n;for(const r of t)if(r?.execute)n=await r.execute(e);else if("function"==typeof r)n=await r();else if(r&&"object"==typeof r&&"string"==typeof r.type){const t=e.locals.get("_runtimeExecute");if(!t)throw Error("Runtime execute function not available");n=await t(r,e)}else n=r;return n}};return po(e,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),i=e})()),fa=ua,da=ua;let ha=(()=>{let t,e,n=[yo({name:"repeat"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r;if(t.modifiers?.index){const i=await e.evaluate(t.modifiers.index,n);"string"==typeof i&&(r=i)}let i,o=t.modifiers?.block||t.modifiers?.commands;if(!o){const e=[];for(let n=t.args.length-1;n>=0;n--){const r=t.args[n];if("block"===r?.type&&r.commands&&(e.unshift(r),2===e.length))break}2===e.length?(o=e[0],i=e[1]):1===e.length&&(o=e[0])}const s=t.args[0],a="identifier"===s?.type?s.name:null,c=!!t.modifiers?.bottomTested&&await e.evaluate(t.modifiers.bottomTested,n);if("for"===a||t.modifiers?.for){const s=t.args[1],a=s?.value||s?.name,c=t.args[2]?await e.evaluate(t.args[2],n):void 0;if(!a||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:a,collection:Array.isArray(c)?c:[c],indexVariable:r,commands:o,elseCommands:i}}if("times"===a||t.modifiers?.times){const s=t.args[1],a=s?await e.evaluate(s,n):void 0,c="number"==typeof a?a:parseInt(a+"",10);if(isNaN(c))throw Error("times loops require a count number");return{type:"times",count:c,indexVariable:r,commands:o,elseCommands:i}}if("while"===a||t.modifiers?.while){const e=t.args[1]||t.modifiers?.while;if(!e)throw Error("while loops require a condition");return{type:"while",condition:e,indexVariable:r,commands:o,elseCommands:i,bottomTested:c}}if("until"===a&&t.modifiers?.from||"until-event"===a){const s=t.args[1],a=s?.value||s?.name;if(!a)throw Error("until-event loops require an event name");let c=n.me;if(t.args[2]){const r=t.args[2];if("identifier"===r?.type&&"document"===r.name)c=document;else if("identifier"===r?.type&&"window"===r.name&&"undefined"!=typeof window)c=window;else{const r=await e.evaluate(t.args[2],n);r instanceof EventTarget?c=r:"document"===r?c=document:"undefined"!=typeof window&&r===window&&(c=window)}}return{type:"until-event",eventName:a,eventTarget:c,indexVariable:r,commands:o,elseCommands:i}}if("until"===a||t.modifiers?.until){const e=t.args[1]||t.modifiers?.until;if(!e)throw Error("until loops require a condition");return{type:"until",condition:e,indexVariable:r,commands:o,elseCommands:i,bottomTested:c}}if("forever"===a||t.modifiers?.forever)return{type:"forever",indexVariable:r,commands:o,elseCommands:i};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(t,e){const{type:n,variable:r,collection:i,condition:o,count:s,indexVariable:a,commands:c,elseCommands:l,bottomTested:u,eventName:f,eventTarget:d}=t;let h,m;switch(n){case"for":({config:h,iterCtx:m}=function(t,e,n){return{config:{type:"for",shouldContinue:t=>(t.collection?.length??0)>t.index,beforeIteration:(t,e)=>{t.item=t.collection?.[t.index],t.itemVariable&&e.locals&&e.locals.set(t.itemVariable,t.item)}},iterCtx:{index:0,collection:t,itemVariable:e,indexVariable:n}}}(i,r,a));break;case"times":({config:h,iterCtx:m}=function(t,e){return{config:{type:"times",shouldContinue:t=>(t.count??0)>t.index,beforeIteration:(t,e)=>{Object.assign(e,{it:t.index+1})}},iterCtx:{index:0,count:t,indexVariable:e}}}(s,a));break;case"while":({config:h,iterCtx:m}=function(t,e,n,r){return{config:{type:"while",shouldContinue:()=>e(t,n)},iterCtx:{index:0,conditionExpr:t,indexVariable:r}}}(o,la,e,a));break;case"until":({config:h,iterCtx:m}=function(t,e,n,r){return{config:{type:"until",shouldContinue:()=>!e(t,n)},iterCtx:{index:0,conditionExpr:t,indexVariable:r}}}(o,la,e,a));break;case"until-event":({config:h,iterCtx:m}=function(t,e,n){const r={index:0,eventFired:!1,indexVariable:n};return{config:{type:"until-event",shouldContinue:t=>!t.eventFired,eventSetup:{eventName:t,target:e,onEvent:()=>{r.eventFired=!0}}},iterCtx:r}}(f,d,a));break;case"forever":({config:h,iterCtx:m}=function(t,e=1e4){return{config:{type:"forever",maxIterations:e,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:t}}}(a));break;default:throw Error("Unknown repeat type: "+n)}if(u){const t=h.shouldContinue;h.shouldContinue=async e=>0===e.index||await t(e)}try{const t=await async function(t,e,n,r,i){const o=t.maxIterations??1e4;let s,a=0,c=!1;t.eventSetup&&t.eventSetup.target.addEventListener(t.eventSetup.eventName,t.eventSetup.onEvent,{once:!0});try{for(;o>a&&await t.shouldContinue(r);){t.beforeIteration&&await t.beforeIteration(r,n),r.indexVariable&&n.locals&&n.locals.set(r.indexVariable,a);try{s=await i(e,n)}catch(e){if(e instanceof Error){if(e.message.includes("BREAK")){c=!0;break}if(e.message.includes("CONTINUE")){a++,r.index=a,"until-event"===t.type&&await new Promise(t=>setTimeout(t,0));continue}}throw e}a++,r.index=a,"until-event"===t.type&&await new Promise(t=>setTimeout(t,0))}}finally{t.eventSetup&&!r.eventFired&&t.eventSetup.target.removeEventListener(t.eventSetup.eventName,t.eventSetup.onEvent)}return{iterations:a,lastResult:s,interrupted:c}}(h,c,e,m,this.executeCommands.bind(this));if(0===t.iterations&&!t.interrupted&&l){const t=await this.executeCommands(l,e);return Object.assign(e,{it:t}),{type:n,iterations:0,completed:!0,lastResult:t}}return Object.assign(e,{it:t.lastResult}),{type:n,iterations:t.iterations,completed:!t.interrupted,lastResult:t.lastResult,interrupted:t.interrupted}}catch(t){if(t instanceof Error&&(t.message.includes("BREAK")||t.message.includes("CONTINUE")))return{type:n,iterations:0,completed:!0,interrupted:t.message.includes("BREAK")};throw t}}async executeCommands(t,e){if(t&&"object"==typeof t&&"block"===t.type){const n=t,r=e.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let i;if(n.commands)for(const t of n.commands)i=await r(t,e);return i}if(Array.isArray(t)){let n;for(const r of t)n="function"==typeof r?await r(e):r&&"function"==typeof r.execute?await r.execute(e):r;return n}return"function"==typeof t?await t(e):t}};return po(e,"RepeatCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),i=e})();const ma=bo(ha);class pa{async parseInput(t,e,n){return{signalType:this.signalType}}async execute(t,e){const n=Error(this.errorMessage);throw n[this.errorFlag]=!0,"exit"===this.signalType&&(n.returnValue=void 0,n.timestamp=Date.now()),n}}let ya=(()=>{let t,e,n=[yo({name:"break"})],r=[],i=pa;var o=e=class extends i{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}get metadata(){return o.metadata}};return po(e,"BreakCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),o=e})();const ga=bo(ya);let ba=(()=>{let t,e,n=[yo({name:"continue"})],r=[],i=pa;var o=e=class extends i{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}get metadata(){return o.metadata}};return po(e,"ContinueCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),o=e})();const va=bo(ba),wa=bo((()=>{let t,e,n=[yo({name:"halt"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(t.args&&t.args.length>0){const r=t.args[0];return!r||"the"!==r.name&&"the"!==r.value?{target:await e.evaluate(t.args[0],n)}:{target:n.event}}return{}}async execute(t,e){let n=t.target;if(("the"===n&&e.event||"object"==typeof n&&null!==n&&"the"===n.target&&e.event)&&(n=e.event),this.isEvent(n)){const t=n;return t.preventDefault(),t.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in e&&(e.halted=!0);const r=Error("HALT_EXECUTION");throw r.isHalt=!0,r}isEvent(t){return null!==t&&"object"==typeof t&&"preventDefault"in t&&"stopPropagation"in t}};return po(e,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),i=e})()),Ea=bo((()=>{let t,e,n=[yo({name:"return"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{value:await e.evaluate(t.args[0],n)}:{value:void 0}}async execute(t,e){const{value:n}=t;"returnValue"in e&&(e.returnValue=n),Object.assign(e,{it:n});const r=Error("RETURN_VALUE");throw r.isReturn=!0,r.returnValue=n,r}};return po(e,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),i=e})());let xa=(()=>{let t,e,n=[yo({name:"exit"})],r=[],i=pa;var o=e=class extends i{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}get metadata(){return o.metadata}};return po(e,"ExitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),o=e})();const ka=bo(xa),Sa=bo((()=>{let t,e,n=[yo({name:"throw"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("throw command requires a message or error object");return{message:await e.evaluate(t.args[0],n)}}async execute(t,e){const{message:n}=t;let r;throw r=n instanceof Error?n:Error("string"==typeof n?n:n+""),r}};return po(e,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"control-flow",compatibility:"standard"}),mo(e,r),i=e})()),Ta=bo((()=>{let t,e,n=[yo({name:"call"})],r=[];var i=e=class{get metadata(){return i.metadata}parseInput(t,e,n){if(!t.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:t.args[0]})}async execute(t,e){const{expression:n}=t,r=e.locals?.get("__evaluator"),i=r?await r.evaluate(n,e):await ir(n,e);let o,s,a=!1;return"function"==typeof i?(s="function",o=i(),o instanceof Promise&&(a=!0,o=await o)):i instanceof Promise?(s="promise",a=!0,o=await i):(s="value",o=i),Object.assign(e,{it:o,result:o}),{result:o,wasAsync:a,expressionType:s}}};return po(e,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"execution",compatibility:"standard"}),mo(e,r),i=e})());class Aa{constructor(){this.name="pseudo-command"}get metadata(){return Aa.metadata}async parseInput(t,e,n){if(1===t.args.length&&"objectLiteral"===t.args[0].type){const r=t.args[0].properties||[];let i,o,s="",a=[];for(const t of r){const r=t.value;switch(t.key?.name||t.key?.value){case"methodName":s=r?.value||await e.evaluate(r,n)+"";break;case"methodArgs":"arrayLiteral"===r?.type&&r.elements?a=await Promise.all(r.elements.map(t=>e.evaluate(t,n))):"literal"===r?.type&&Array.isArray(r.value)&&(a=await Promise.all(r.value.map(t=>e.evaluate(t,n))));break;case"preposition":const t=r?.value;t&&"null"!==t&&(i=t);break;case"target":case"targetExpression":o=await e.evaluate(r,n)}}if(!s)throw Error("pseudo-command requires method name");if(null==o)throw Error("pseudo-command requires a target expression");return{methodName:s,methodArgs:a,preposition:i,targetExpression:o}}if(2>t.args.length)throw Error("pseudo-command requires method name and target expression");const r=await e.evaluate(t.args[0],n)+"",i=Array.isArray(t.args[1])?await Promise.all(t.args[1].map(t=>e.evaluate(t,n))):[];let o,s;const a=["from","on","with","into","at","to"];for(const r of a)if(t.modifiers?.[r]){s=r,o=await e.evaluate(t.modifiers[r],n);break}if(o||3>t.args.length||(o=await e.evaluate(t.args[2],n)),!o)throw Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:s,targetExpression:o}}async execute(t,e){const{methodName:n,methodArgs:r,targetExpression:i}=t;try{const t=await this.resolveTarget(i,e);if(null==t)throw Error("Target expression resolved to "+t);const o=this.resolveMethod(t,n);if(!o)throw Error(`Method "${n}" not found on target object`);if("function"!=typeof o)throw Error(`"${n}" is not a function (it's a ${typeof o})`);const s=await this.executeMethod(o,t,r);return e.locals.set("result",s),Object.assign(e,{it:s}),{result:s,methodName:n,target:t}}catch(t){throw Error("Pseudo-command failed: "+(t instanceof Error?t.message:t+""))}}async resolveTarget(t,e){return"object"==typeof t&&null!==t?t:"string"==typeof t?e.locals.has(t)?e.locals.get(t):e.variables?.has(t)?e.variables.get(t):e.globals.has(t)?e.globals.get(t):"me"===t&&e.me?e.me:"it"===t&&e.it?e.it:"document"===t?"undefined"!=typeof document?document:null:"window"===t?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(t,e):t}resolvePropertyPath(t,e){const n=t.split(".");let r="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;e.locals.has(n[0])?(r=e.locals.get(n[0]),n.shift()):e.variables?.has(n[0])?(r=e.variables.get(n[0]),n.shift()):e.globals.has(n[0])&&(r=e.globals.get(n[0]),n.shift());for(const t of n){if(null==r)return null;r=r[t]}return r}resolveMethod(t,e){if(!t)return null;if(e in t)return t[e];const n=e.split(".");let r=t;for(let t=0;n.length>t;t++){const e=n[t];if(null==r)return null;if(!(e in r))return null;if(r=r[e],t===n.length-1&&"function"==typeof r)return r}return null}async executeMethod(t,e,n){try{const r=t.apply(e,n);return r&&"object"==typeof r&&"then"in r?await r:r}catch(t){throw Error("Method execution failed: "+(t instanceof Error?t.message:t+""))}}}Aa.metadata=go({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",compatibility:"standard",sideEffects:["method-execution"]});const Ca=bo((()=>{let t,e,n=[yo({name:"focus"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await To(t.args,e,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.focus()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return po(e,"FocusCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),mo(e,r),i=e})()),$a=bo((()=>{let t,e,n=[yo({name:"blur"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await To(t.args,e,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.blur()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return po(e,"BlurCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"execution",compatibility:"standard"}),mo(e,r),i=e})());function Oa(t){return gt(t)?t:t+""}class ja{constructor(t){this.position=t}concat(t,e){const n=null==t?"":t+"",r=e+"";return"append"===this.position?n+r:r+n}pushInto(t,e){return"append"===this.position?t.push(e):t.unshift(e),t}async parseInput(t,e,n){if(!t.args?.length)throw Error(this.name+" requires content");const r=await e.evaluate(t.args[0],n),i=t.modifiers?.to??t.target;if(!i)return{kind:"implicit",content:r};const o=await Js(i,e,n,{scopeElements:async()=>gt(n.me)?[n.me]:[],selectorSource:!0,bareReference:!0});if(o)return function(t,e){switch(t.kind){case"selector":return{kind:"selector",selector:t.selector,content:e};case"attribute":return{kind:"attribute",elements:t.elements,name:t.name,content:e};case"property":return{kind:"property",property:t.target,content:e};case"variable":return{kind:"variable",name:t.name,scope:t.scope,content:e};default:throw Error(`unrequested write-target rung '${t.kind}'`)}}(o,r);const s=await e.evaluate(i,n),a=function(t){if(gt(t))return[t];if(Array.isArray(t)&&t.length>0&&t.every(t=>gt(t)))return t;if(t&&"object"==typeof t&&"number"==typeof t.length&&"function"==typeof t.item){const e=Array.from(t).filter(t=>gt(t));return e.length?e:null}return null}(s);return a?{kind:"elements",elements:a,content:r}:{kind:"value",target:s,content:r}}async execute(t,e){switch(t.kind){case"selector":return this.done(e,this.insertIntoSelector(t.selector,t.content));case"elements":return this.done(e,this.insertIntoEach(t.elements,t.content));case"attribute":{for(const e of t.elements)e.setAttribute(t.name,this.concat(e.getAttribute(t.name),t.content));const n=t.elements[0]?.getAttribute(t.name)??this.concat(null,t.content);return Object.assign(e,{it:n}),{target:"@"+t.name,value:n,targetType:"attribute"}}case"property":{const n=vs(t.property),r=this.combineValue(n,t.content);return gt(n)||ws(t.property,r),Object.assign(e,{it:r}),{target:t.property.element,value:r,targetType:"property"}}case"variable":return this.executeVariable(t,e);case"value":{const n=this.combineValue(t.target,t.content,!0);return Object.assign(e,{it:n}),{target:t.target,value:n,targetType:this.targetTypeOf(t.target)}}case"implicit":return this.execImplicit(e,t.content)}}insertIntoSelector(t,e){return this.insertIntoEach(St(t),e)}insertIntoEach(t,e){const n=Oa(e);for(const e of t)Go(e,n,this.position);return t}combineValue(t,e,n=!1){if(Array.isArray(t))return this.pushInto(t,e);if(t instanceof Set)return t.add(e),t;if(gt(t))return Go(t,Oa(e),this.position),t;if(n&&null!=t&&"string"!=typeof t&&"number"!=typeof t)throw Error(`Unable to ${this.name} a value!`);return this.concat(t,e)}targetTypeOf(t){return Array.isArray(t)?"array":t instanceof Set?"set":gt(t)?"element":"result"}executeVariable(t,e){if("me"===t.name||"you"===t.name){const n="me"===t.name?e.me:e.you;if(gt(n))return Go(n,Oa(t.content),this.position),Object.assign(e,{it:n}),{target:n,value:n,targetType:"element"}}if("it"===t.name||"result"===t.name)return this.execImplicit(e,t.content);const n=wt(t.name,e,t.scope),r=this.combineValue(n,t.content);return Array.isArray(n)||n instanceof Set||gt(n)||Et(t.name,r,e,t.scope),Object.assign(e,{it:r}),{target:t.name,value:r,targetType:this.targetTypeOf(n)}}execImplicit(t,e){const n=t.it??t.result,r=this.combineValue(n,e);return Object.assign(t,{it:r,result:r}),{target:"result",value:r,targetType:this.targetTypeOf(n)}}done(t,e){const n=1===e.length?e[0]:e;return Object.assign(t,{it:n}),{target:n,value:n,targetType:"element"}}}const Na=bo((()=>{let t,e,n=[yo({name:"append"})],r=[],i=ja;var o=e=class extends i{get metadata(){return o.metadata}constructor(){super("append")}};return po(e,"AppendCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({description:"Add content to the end of a string, array, Set, 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','append " (edited)" to #title\'s textContent'],sideEffects:["data-mutation","dom-mutation"],category:"content",compatibility:"standard"}),mo(e,r),o=e})()),Ra=bo((()=>{let t,e,n=[yo({name:"prepend"})],r=[],i=ja;var o=e=class extends i{get metadata(){return o.metadata}constructor(){super("prepend")}};return po(e,"PrependCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=go({description:"Add content to the start of a string, array, Set, or HTML element",syntax:["prepend <content>","prepend <content> to <target>"],examples:['prepend "Hello"','prepend "World" to greeting',"prepend item to myArray",'prepend "<p>First</p>" to #content'],sideEffects:["data-mutation","dom-mutation"],category:"content",compatibility:"lokascript-extension"}),mo(e,r),o=e})()),La=bo((()=>{let t,e,n=[yo({name:"transition"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("transition requires property and value");let r,i;const o=await e.evaluate(t.args[0],n),s=(t=>Array.isArray(t)||bt(t)?t[0]:t)(o);if(gt(s)||"string"==typeof o&&/^[#.]|^(?:me|it|you)$/.test(o))i=s,r=await e.evaluate(t.args[1],n)+"";else{if(t.args.length>=2)throw Error("transition: target element not found");r=o+""}if(!r)throw Error("transition requires a CSS property");if(!t.modifiers?.to)throw Error('transition requires "to <value>"');let a=await e.evaluate(t.modifiers.to,n);void 0===a&&"identifier"===t.modifiers.to.type&&(a=t.modifiers.to.name);const c={property:r,value:a};return void 0!==i&&(c.target=i),t.modifiers?.over&&(c.duration=await e.evaluate(t.modifiers.over,n)),t.modifiers?.with&&(c.timingFunction=await e.evaluate(t.modifiers.with,n)+""),c}async execute(t,e){let{property:n}=t;const{target:r,value:i,duration:o,timingFunction:s}=t;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const a=wo(r,e,"transition"),c=ns(o,300),l=getComputedStyle(a).getPropertyValue(n),u=a.style.transition,f=`${n} ${c}ms ${s||"ease"}`;a.style.transition=u?`${u}, ${f}`:f;let d=i+"",h=!1;if("initial"===d||"inherit"===d||"unset"===d||"revert"===d){const t=a.style.getPropertyValue(n);a.style.removeProperty(n),d=getComputedStyle(a).getPropertyValue(n),t&&a.style.setProperty(n,t),h=!0}a.style.setProperty(n,d);const m=await function(t,e,n){return new Promise(r=>{const i=n=>{n.target===t&&n.propertyName===e&&s({completed:!0,cancelled:!1})},o=n=>{n.target===t&&n.propertyName===e&&s({completed:!1,cancelled:!0})},s=Vs(()=>{t.removeEventListener("transitionend",i),t.removeEventListener("transitioncancel",o),clearTimeout(a)},r);t.addEventListener("transitionend",i),t.addEventListener("transitioncancel",o);const a=setTimeout(()=>{s({completed:!0,cancelled:!1})},n+50)})}(a,n,c);return a.style.transition=u,h&&a.style.removeProperty(n),{element:a,property:n,fromValue:l,toValue:d,duration:c,completed:m.completed}}};return po(e,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Animate CSS properties using CSS transitions",syntax:"transition [<target>] <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition my *opacity to 0 over 200ms","transition #box's *opacity to 0 over 200ms","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"],category:"animation",compatibility:"standard"}),mo(e,r),i=e})()),Ia=bo((()=>{let t,e,n=[yo({name:"measure"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r,i,o;if(t.args?.length){const o=t.args[0];if("identifier"===o.type&&o.name){const s=o.name.toLowerCase();if("me"===s||"it"===s||"you"===s){const s=await e.evaluate(o,n);if(gt(s)&&(r=s,t.args.length>1)){const r=t.args[1];i="identifier"===r.type?r.name:await e.evaluate(r,n)+""}}else i=o.name}else{const s=await e.evaluate(o,n);if(gt(s)||"string"==typeof s&&/^[#.]/.test(s)){if(r=s,t.args.length>1){const r=t.args[1];i="identifier"===r.type?r.name:await e.evaluate(r,n)+""}}else"string"==typeof s&&(i=s)}}t.modifiers?.set&&(o=await e.evaluate(t.modifiers.set,n)+"");const s={};return void 0!==r&&(s.target=r),void 0!==i&&(s.property=i),void 0!==o&&(s.variable=o),s}async execute(t,e){const n=wo(t.target,e,"measure"),r=t.property||"width",i=this.getMeasurement(n,r);return t.variable&&e.locals&&e.locals.set(t.variable,i.value),Object.assign(e,{it:i.value}),{result:i.value,wasAsync:!1,element:n,property:r,value:i.value,unit:i.unit,stored:!!t.variable}}getMeasurement(t,e){const n=getComputedStyle(t);if(e.startsWith("*")){const t=n.getPropertyValue(e.substring(1)),r=parseFloat(t);if(!isNaN(r)){const e=t.match(/([a-zA-Z%]+)$/);return{value:r,unit:e?e[1]:""}}return{value:t,unit:""}}const r=e.toLowerCase(),i=t.getBoundingClientRect(),o={width:()=>i.width,height:()=>i.height,top:()=>i.top,left:()=>i.left,right:()=>i.right,bottom:()=>i.bottom,x:()=>t.offsetLeft,y:()=>t.offsetTop,clientwidth:()=>t.clientWidth,"client-width":()=>t.clientWidth,clientheight:()=>t.clientHeight,"client-height":()=>t.clientHeight,offsetwidth:()=>t.offsetWidth,"offset-width":()=>t.offsetWidth,offsetheight:()=>t.offsetHeight,"offset-height":()=>t.offsetHeight,scrollwidth:()=>t.scrollWidth,"scroll-width":()=>t.scrollWidth,scrollheight:()=>t.scrollHeight,"scroll-height":()=>t.scrollHeight,scrolltop:()=>t.scrollTop,"scroll-top":()=>t.scrollTop,scrollleft:()=>t.scrollLeft,"scroll-left":()=>t.scrollLeft,offsettop:()=>t.offsetTop,"offset-top":()=>t.offsetTop,offsetleft:()=>t.offsetLeft,"offset-left":()=>t.offsetLeft};if(o[r])return{value:o[r](),unit:"px"};const s=n.getPropertyValue(e),a=parseFloat(s);if(!isNaN(a)){const t=s.match(/([a-zA-Z%]+)$/);return{value:a,unit:t?t[1]:"px"}}return{value:0,unit:"px"}}};return po(e,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"animation",compatibility:"standard"}),mo(e,r),i=e})()),Ma=bo((()=>{let t,e,n=[yo({name:"settle"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r,i;if(t.args&&t.args.length>0){const i=await e.evaluate(t.args[0],n);(gt(i)||"string"==typeof i&&(i.startsWith("#")||i.startsWith(".")||"me"===i||"it"===i||"you"===i))&&(r=i)}t.modifiers?.for&&(i=await e.evaluate(t.modifiers.for,n));const o={};return void 0!==r&&(o.target=r),void 0!==i&&(o.timeout=i),o}async execute(t,e){const{target:n,timeout:r}=t,i=wo(n,e,"settle"),o=ns(r,5e3),s=Date.now(),a=getComputedStyle(i),c=is(a.transitionDuration),l=is(a.transitionDelay),u=is(a.animationDuration),f=is(a.animationDelay),d=os(c,l),h=os(u,f),m=Math.max(d,h);var p,y,g;return{element:i,settled:(await(p=i,y=m,g=o,y>0?new Promise(t=>{const e=t=>{t.target===p&&r({completed:!0,type:"transition"})},n=t=>{t.target===p&&r({completed:!0,type:"animation"})},r=Vs(()=>{p.removeEventListener("transitionend",e),p.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(o)},t);p.addEventListener("transitionend",e),p.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},y+50),o=setTimeout(()=>{r({completed:!1,type:"timeout"})},g)}):Promise.resolve({completed:!0,type:"timeout"}))).completed,timeout:o,duration:Date.now()-s}}};return po(e,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"],category:"animation",compatibility:"standard"}),mo(e,r),i=e})());const Pa=bo((()=>{let t,e,n=[yo({name:"take"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error('take requires property, "from", and source');const{value:r}=await zo(t.args[0],e,n),i=r+"";let o;if(2>t.args.length)t.modifiers?.from&&(o=await e.evaluate(t.modifiers.from,n));else{if(!(s=t.args[1])||("identifier"!==s.type||"from"!==s.name)&&"from"!==s.value)throw Error("take syntax: take <property> from <source>");t.args[2]&&(o=await e.evaluate(t.args[2],n))}var s;let a;if(8>t.args.length)t.args.length>3&&(a=await e.evaluate(t.args[3],n));else{const r=[3,4,5,6].map(e=>t.args[e]),i=t=>t?.name??t?.value;"and"===i(r[0])&&"put"===i(r[1])&&"it"===i(r[2])&&"on"===i(r[3])&&t.args[7]&&(a=await e.evaluate(t.args[7],n))}if(!a&&t.modifiers?.on&&(a=await e.evaluate(t.modifiers.on,n)),!a&&t.modifiers?.for&&(a=await e.evaluate(t.modifiers.for,n)),void 0===o&&!i.startsWith("."))throw Error('take requires property, "from", and source');return{property:i,source:o,target:a}}async execute(t,e){const n=t.property.trim();if(n.startsWith(".")){const r=n.substring(1);let i;if(null!=t.source)i=Eo(t.source,e);else{const t=e.me?.ownerDocument??("undefined"!=typeof document?document:null);i=t?Array.from(t.querySelectorAll("."+r)):[]}for(const t of i)t.classList.remove(r);const o=Eo(t.target,e);if(0===o.length)throw Error("take: no recipient element found");for(const t of o)t.classList.add(r);return{targetElement:o[0],property:t.property,value:r}}const r=wo(this.firstOf(t.source),e,"take"),i=wo(t.target?this.firstOf(t.target):void 0,e,"take"),o=this.takeProperty(r,t.property);return this.putProperty(i,t.property,o),{targetElement:i,property:t.property,value:o}}firstOf(t){const e=null!==t&&"object"==typeof t&&"number"==typeof t.length&&"function"==typeof t.item;if(Array.isArray(t)||e){const e=t[0];if(void 0===e)throw Error("take: no matching elements");return e}return t}takeProperty(t,e){const n=e.trim(),r=n.toLowerCase();if("class"===r||"classes"===r){const e=Array.from(t.classList);return t.className="",e}if(n.startsWith(".")){const e=n.substring(1);return t.classList.contains(e)?(t.classList.remove(e),e):null}if(n.startsWith("@")){const e=n.substring(1),r=t.getAttribute(e);return t.removeAttribute(e),r}if(n.startsWith("data-")){const e=t.getAttribute(n);return t.removeAttribute(n),e}if("id"===r){const e=t.id;return t.id="",e}if("title"===r){const e=t.title;return t.title="",e}if("value"===r&&"value"in t){const e=t.value;return t.value="",e}const i=n.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());if(n.includes("-")||i in t.style||n in t.style){let e;return i in t.style?(e=t.style[i],t.style[i]=""):n in t.style?(e=t.style[n],t.style[n]=""):(e=t.style.getPropertyValue(n),t.style.removeProperty(n)),e}const o=t.getAttribute(e);return null!==o?(t.removeAttribute(e),o):null}putProperty(t,e,n){if(null==n)return;const r=e.trim(),i=r.toLowerCase();if("class"===i||"classes"===i)return void(Array.isArray(n)?n.forEach(e=>e&&"string"==typeof e&&t.classList.add(e)):"string"==typeof n&&(t.className=n));if(r.startsWith("."))return void(n&&t.classList.add(r.substring(1)));if(r.startsWith("@"))return void t.setAttribute(r.substring(1),n+"");if(r.startsWith("data-"))return void t.setAttribute(r,n+"");if("id"===i)return void(t.id=n+"");if("title"===i)return void(t.title=n+"");if("value"===i&&"value"in t)return void(t.value=n+"");const o=r.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());r.includes("-")||o in t.style||r in t.style?o in t.style?t.style[o]=n+"":r in t.style?t.style[r]=n+"":t.style.setProperty(r,n+""):t.setAttribute(e,n+"")}};return po(e,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Move classes, attributes, and properties from one element to another",syntax:["take <class> [from <source>] [for <recipient>]","take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take .active from .tab for me","take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"],category:"animation",compatibility:"standard"}),mo(e,r),i=e})()),qa=bo((()=>{let t,e,n=[yo({name:"js"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r,i;if(0===t.args.length)throw Error("js command requires JavaScript code");const o=t.args[0],s=t.args[1];if(o&&"literal"===o.type&&"string"==typeof o.value)r=o.value;else{if(!o||void 0===o.value)throw Error("js command requires JavaScript code");r=o.value+""}s&&"arrayLiteral"===s.type&&Array.isArray(s.elements)&&(i=s.elements.map(t=>"string"==typeof t.value?t.value:t.value+"").filter(t=>t&&t.length>0));const a={code:r};return i&&i.length>0&&(a.parameters=i),a}async execute(t,e){const{code:n,parameters:r=[]}=t;if(!n.trim())return{result:void 0,executed:!1,codeLength:n.length,parameters:r,preserveArrayResult:!0};try{const t=this.createExecutionContext(e,r),i=Function(...Object.keys(t),n),o=await i(...Object.values(t));return void 0!==o&&Object.assign(e,{it:o}),{result:o,executed:!0,codeLength:n.length,parameters:r,preserveArrayResult:!0}}catch(t){throw Error("JavaScript execution failed: "+(t instanceof Error?t.message:"Unknown error"))}}createExecutionContext(t,e){return{me:t.me,it:t.it,you:t.you,locals:t.locals,globals:t.globals,variables:t.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...e.reduce((e,n)=>{let r=t.locals?.get(n);return void 0===r&&(r=t.variables?.get(n)),void 0===r&&(r=t[n]),e[n]=r,e},{})}}};return po(e,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"advanced",compatibility:"standard"}),mo(e,r),i=e})()),Ha=bo((()=>{let t,e,n=[yo({name:"async"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("async command requires at least one command to execute");return{commands:t.args}}async execute(t,e){const{commands:n}=t,r=Date.now();try{const t=await this.executeCommandsAsync(e,n),i=Date.now()-r;return t.length>0&&Object.assign(e,{it:t[t.length-1]}),{commandCount:n.length,results:t,executed:!0,duration:i}}catch(t){throw Error("Async command execution failed: "+(t instanceof Error?t.message:"Unknown error"))}}async executeCommandsAsync(t,e){const n=[];for(let r=0;e.length>r;r++){const i=e[r];try{const e=await this.executeCommand(i,t);n.push(e),Object.assign(t,{it:e})}catch(t){const n=this.getCommandName(i);throw Error(`Command '${n}' (${r+1}/${e.length}) failed: ${t instanceof Error?t.message:"Unknown error"}`)}}return n}async executeCommand(t,e){if("function"==typeof t)return await t(e);if(t&&"object"==typeof t&&"execute"in t&&"function"==typeof t.execute)return await t.execute(e);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(t){return"function"==typeof t?t.name||"anonymous function":t&&"object"==typeof t?t.name||"unnamed command":"unknown"}};return po(e,"AsyncCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"],category:"advanced",compatibility:"lokascript-extension"}),mo(e,r),i=e})()),Ba=bo((()=>{let t,e,n=[yo({name:"log"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{values:[]}}async execute(t,e){const n="undefined"!=typeof window?window.console:console;0===t.values.length?n.log():n.log(...t.values)}validate(t){return"object"==typeof t&&null!==t&&Array.isArray(t.values)}};return po(e,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"utility",compatibility:"standard"}),mo(e,r),i=e})()),Da=bo((()=>{let t,e,n=[yo({name:"tell"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(2>t.args.length)throw Error("tell command requires a target and at least one command");return{target:await e.evaluate(t.args[0],n),commands:t.args.slice(1)}}async execute(t,e){const{target:n,commands:r}=t,i=Eo(n,e);if(0===i.length)throw Error("tell command found no target elements");const o=e.locals.get("_runtimeExecute"),s=[];for(const t of i){const n={...e,me:t,you:t};for(const t of r)try{const e=await this.executeCommand(t,n,o);s.push(e),Object.assign(n,{it:e})}catch(t){throw Error("Command execution failed in tell block: "+(t instanceof Error?t.message:"Unknown error"))}}return{targetElements:i,commandResults:s,executionCount:i.length*r.length}}async executeCommand(t,e,n){if(t&&"object"==typeof t&&"command"===t.type&&n)return await n(t,e);if("function"==typeof t)return await t(e);if(t&&"object"==typeof t&&"function"==typeof t.execute)return await t.execute(e);throw Error("Invalid command: must be a function or object with execute method")}};return po(e,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"utility",compatibility:"standard"}),mo(e,r),i=e})()),Va=bo((()=>{let t,e,n=[yo({name:"copy"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("copy command requires a source (text or element)");const r=await e.evaluate(t.args[0],n);let i="text";if(t.modifiers?.format){const r=await e.evaluate(t.modifiers.format,n);"html"!==r&&"text"!==r||(i=r)}return{source:r,format:i}}async execute(t,e){const{source:n,format:r="text"}=t,i=this.extractText(n,r,e);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(i),this.dispatchCopyEvent(e,"copy:success",{text:i,method:"clipboard-api"}),{success:!0,text:i,format:r,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(i))return this.dispatchCopyEvent(e,"copy:success",{text:i,method:"execCommand"}),{success:!0,text:i,format:r,method:"execCommand"}}catch{}return this.dispatchCopyEvent(e,"copy:error",{text:i,error:"All copy methods failed"}),{success:!1,text:i,format:r,method:"fallback"}}extractText(t,e,n){if("string"==typeof t)return t;if(gt(t))return"html"===e?t.outerHTML:t.textContent||"";if(t===n.me&&gt(n.me)){const t=n.me;return"html"===e?t.outerHTML:t.textContent||""}return t+""}copyUsingExecCommand(t){if("undefined"==typeof document)return!1;const e=document.createElement("textarea");e.value=t,e.style.cssText="position:fixed;top:0;left:-9999px",e.setAttribute("readonly",""),document.body.appendChild(e);try{e.select(),e.setSelectionRange(0,t.length);const n=document.execCommand("copy");return document.body.removeChild(e),n}catch{return e.parentNode?.removeChild(e),!1}}dispatchCopyEvent(t,e,n){if(gt(t.me)){const r=new CustomEvent(e,{detail:n,bubbles:!0,cancelable:!1});t.me.dispatchEvent(r)}}};return po(e,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"utility",compatibility:"lokascript-extension"}),mo(e,r),i=e})());const Fa=bo((()=>{let t,e,n=[yo({name:"pick"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.modifiers?.variant,i=r?.value;if("first"===i||"last"===i){const r=await e.evaluate(t.args[0],n),o=await e.evaluate(t.modifiers.count,n);if(!Array.isArray(r))throw Error(`pick ${i}: source must be an array, got ${typeof r}`);if("number"!=typeof o||!Number.isFinite(o))throw Error(`pick ${i}: count must be a number, got ${typeof o}`);return{variant:i,array:r,count:o}}if("random"===i){const r=await e.evaluate(t.args[0],n);if(!Array.isArray(r))throw Error("pick random: source must be an array");let i;if(t.modifiers.count){const r=await e.evaluate(t.modifiers.count,n);if("number"!=typeof r||!Number.isFinite(r))throw Error("pick random: count must be a number, got "+typeof r);i=r}return{variant:"random",array:r,count:i}}if("range"===i){const r=await e.evaluate(t.args[0],n);if(!Array.isArray(r)&&"string"!=typeof r)throw Error("pick items: source must be an array or string");const i=t.modifiers.rangeStart,o="start"===i?.value?"start":await e.evaluate(t.modifiers.rangeStart,n),s="start"===o?"start":Number(o);let a;if(t.modifiers.rangeEnd)if("end"===t.modifiers.rangeEnd.value)a="end";else{const r=await e.evaluate(t.modifiers.rangeEnd,n);a=Number(r)}const c=t.modifiers.rangeMode;return{variant:"range",array:r,rangeStart:s,rangeEnd:a,rangeMode:c?.value??"default"}}if("match"===i||"matches"===i){const r=await e.evaluate(t.args[0],n);if("string"!=typeof r)throw Error(`pick ${i}: source must be a string, got ${typeof r}`);const o=await e.evaluate(t.modifiers.regex,n),s="string"==typeof o?o:o+"",a=t.modifiers.flags,c=a?.value;return{variant:i,source:r,regex:s,flags:c}}if(t.modifiers?.from){const r=await e.evaluate(t.modifiers.from,n);if(!Array.isArray(r))throw Error("pick from requires an array");if(0===r.length)throw Error("Cannot pick from empty array");return{variant:"random",array:r}}if(0===t.args.length)throw Error("pick command requires items to choose from");return{variant:"random",items:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}}async execute(t,e){const n=t.variant??"random";if("first"===n){const n=t.array??[],r=n.slice(0,t.count??0);return Object.assign(e,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"array",variant:"first"}}if("last"===n){const n=t.array??[],r=t.count??0,i=r>0?n.slice(-r):[];return Object.assign(e,{it:i}),{selectedItem:i,sourceLength:n.length,sourceType:"array",variant:"last"}}if("range"===n){const n=t.array??[];let r="start"===t.rangeStart?0:t.rangeStart??0,i=void 0===t.rangeEnd?r+1:"end"===t.rangeEnd?n.length:t.rangeEnd;"inclusive"===t.rangeMode?i++:"exclusive"===t.rangeMode&&r++;const o=n.slice(r,i);return Object.assign(e,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"array",variant:"range"}}if("match"===n){const n=t.source??"",r=RegExp(t.regex??"",t.flags).exec(n);return Object.assign(e,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"string",variant:"match"}}if("matches"===n){const n=t.source??"",r=t.flags??"g",i=RegExp(t.regex??"",r.includes("g")?r:"g"+r),o=Array.from(n.matchAll(i));return Object.assign(e,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"string",variant:"matches"}}const r=t.items??t.array??[];if(0===r.length)throw Error("Cannot pick from empty collection");if(void 0===t.count){const n=Math.floor(Math.random()*r.length),i=r[n];return Object.assign(e,{it:i}),{selectedItem:i,selectedIndex:n,sourceLength:r.length,sourceType:t.items?"items":"array",variant:"random"}}const i=r.slice(),o=[];for(let e=0;t.count>e&&i.length>0;e++){const t=Math.floor(Math.random()*i.length);o.push(i.splice(t,1)[0])}return Object.assign(e,{it:o}),{selectedItem:o,sourceLength:r.length,sourceType:t.items?"items":"array",variant:"random"}}};return po(e,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"utility",compatibility:"standard"}),mo(e,r),i=e})());const Ua=bo((()=>{let t,e,n=[yo({name:"beep"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return 0===t.args.length?{expressions:[]}:{expressions:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}}async execute(t,e){const n=t.expressions||[];if(0===n.length)return this.debugContext(e),{expressionCount:0,debugged:!0,outputs:[]};const r=[];console.group("\ud83d\udd14 beep! Debug Output");for(const t of n){const e=this.debugExpression(t);r.push(e),console.log("Value:",t),console.log("Type:",e.type),console.log("Representation:",e.representation),console.log("---")}return console.groupEnd(),{expressionCount:n.length,debugged:!0,outputs:r}}debugContext(t){console.group("\ud83d\udd14 beep! Context Debug"),console.log("me:",t.me),console.log("it:",t.it),console.log("you:",t.you),console.log("locals:",t.locals),console.log("globals:",t.globals),console.log("variables:",t.variables),console.groupEnd()}debugExpression(t){return{value:t,type:this.getType(t),representation:this.getRepresentation(t)}}getType(t){return null===t?"null":void 0===t?"undefined":Array.isArray(t)?"array":gt(t)?"HTMLElement":t instanceof Element?"Element":t instanceof Node?"Node":t instanceof Error?"Error":t instanceof Date?"Date":t instanceof RegExp?"RegExp":typeof t}getRepresentation(t){if(null===t)return"null";if(void 0===t)return"undefined";if(Array.isArray(t))return`Array(${t.length}) [${t.slice(0,3).map(t=>this.getRepresentation(t)).join(", ")}${t.length>3?"...":""}]`;if(gt(t)){const e=t;return`<${e.tagName.toLowerCase()}${e.id?"#"+e.id:""}${e.className?"."+e.className.split(" ").join("."):""}/>`}if(t instanceof Error)return"Error: "+t.message;if("string"==typeof t)return t.length>50?`"${t.substring(0,47)}..."`:`"${t}"`;if("object"==typeof t)try{const e=Object.keys(t);return`Object {${e.slice(0,3).join(", ")}${e.length>3?"...":""}}`}catch{return"[Object]"}return t+""}};return po(e,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({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"],category:"utility",compatibility:"lokascript-extension"}),mo(e,r),i=e})()),_a=bo((()=>{let t,e,n=[yo({name:"breakpoint"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{}}async execute(t,e){}validate(t){return"object"==typeof t&&null!==t}};return po(e,"BreakpointCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ho(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=go({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),mo(e,r),i=e})());class za{constructor(){this.name="install"}get metadata(){return za.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("install command requires a behavior name");const r=t.args[0];let i,o,s;if(i="identifier"===r?.type&&"string"==typeof r.name?r.name:await e.evaluate(r,n)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(i))throw Error(`Behavior name must be PascalCase (start with uppercase): "${i}"`);if(t.args.length>=2){const r=await e.evaluate(t.args[1],n);if(r&&"object"==typeof r&&!Array.isArray(r)){o=r;for(const t of Object.keys(o))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(t))throw Error(`Invalid parameter name: "${t}"`)}}return t.modifiers?.on&&(s=await e.evaluate(t.modifiers.on,n)),{behaviorName:i,parameters:o,target:s}}async execute(t,e){const{behaviorName:n,parameters:r={},target:i}=t;try{const t=this.resolveTarget(i,e);if(0===t.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(n,e))throw Error(`Behavior "${n}" is not defined. Define it using the 'behavior' keyword before installing.`);const o=[];for(const i of t){const t=await this.installBehavior(n,i,r,e);o.push(t)}return{success:!0,behaviorName:n,installedCount:o.length,instances:o}}catch(t){throw Error(`Failed to install behavior "${n}": ${t instanceof Error?t.message:t+""}`)}}resolveTarget(t,e){if(null==t){const t=e.me||e.locals.get("me");if(gt(t))return[t];throw Error('No target specified and "me" is not available in context')}if(gt(t))return[t];if(Array.isArray(t)){const e=t.filter(t=>gt(t));if(0===e.length)throw Error("Target array contains no valid HTMLElements");return e}if("string"==typeof t){if("me"===t){const t=e.me||e.locals.get("me");if(gt(t))return[t];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const e=document.querySelectorAll(t),n=Array.from(e).filter(t=>gt(t));if(0===n.length)throw Error(`No elements found matching selector: "${t}"`);return n}throw Error("document is not available (not in browser environment)")}if(t&&"object"==typeof t&&"length"in t){const e=Array.from(t).filter(t=>gt(t));if(0===e.length)throw Error("Target collection contains no valid HTMLElements");return e}if("object"==typeof t&&"element"in t){const e=t.element;if(gt(e))return[e]}throw Error("Cannot resolve target to HTMLElement(s): "+t)}behaviorExists(t,e){const n=e.locals.get("_behaviors");if(n&&"object"==typeof n){const e=n;if(e.has(t))return!0;if(e.resolve&&e.resolve(t))return!0}if("undefined"!=typeof globalThis){const e=globalThis._hyperscript;if(e?.behaviors){if(e.behaviors.has(t))return!0;if(e.behaviors.resolve&&e.behaviors.resolve(t))return!0}}return!1}async installBehavior(t,e,n,r){const i=r.locals.get("_behaviors");if(i&&"object"==typeof i){const r=i;if(r.install&&"function"==typeof r.install)return await r.install(t,e,n)}if("undefined"!=typeof globalThis){const r=globalThis._hyperscript;if(r?.behaviors?.install)return await r.behaviors.install(t,e,n)}throw Error("Behavior system not available in context")}}za.metadata=go({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",compatibility:"standard",sideEffects:["behavior-installation","element-modification"]});class Wa{constructor(){this.name="render"}get metadata(){return Wa.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("render command requires a template");const r=await e.evaluate(t.args[0],n);let i;if(t.args.length>=3&&"with"===await e.evaluate(t.args[1],n)){const r=await e.evaluate(t.args[2],n);r&&"object"==typeof r&&(i=r)}if(!i&&t.modifiers?.with){const r=await e.evaluate(t.modifiers.with,n);r&&"object"==typeof r&&(i=r)}return{template:r,variables:i}}async execute(t,e){const{template:n,variables:r={}}=t,i=this.extractTemplateContent(n,e),o=this.createTemplateContext(e,r),s=[],a=await this.processTemplate(i,o,s),c=this.createDOMElement(a);return Object.assign(e,{it:c}),{element:c,rendered:a,directivesProcessed:s}}extractTemplateContent(t,e){if(t instanceof HTMLTemplateElement)return t.innerHTML;if("string"==typeof t){let n=t;if(!n.includes("<")&&!n.includes("$")){const t=this.resolveVariable(n,e);if(t instanceof HTMLTemplateElement)return t.innerHTML;"string"==typeof t&&(n=t)}const r=n.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return r?r[1]:n}if(t&&"object"==typeof t&&"innerHTML"in t)return t.innerHTML;throw Error("Invalid template format")}createTemplateContext(t,e){return{...t,locals:new Map([...Array.from(t.locals.entries()),...Object.entries(e)])}}async processTemplate(t,e,n){const r=t.split("\n"),i=[];let o=0;for(;r.length>o;){const t=r[o].trim();if(t.startsWith("@repeat ")){const{nextIndex:t,rendered:s}=await this.processRepeatDirective(r,o,e);i.push(s),o=t,n.push("@repeat")}else if(t.startsWith("@if ")){const{nextIndex:t,rendered:s}=await this.processIfDirective(r,o,e,n);i.push(s),o=t,n.push("@if")}else if("@else"===t||"@end"===t)o++;else{const n=this.processVariableInterpolation(t,e);i.push(n),o++}}return i.join("\n")}async processRepeatDirective(t,e,n){const r=t[e].trim(),i=r.match(/^@repeat\s+in\s+(.+)$/);if(!i)throw Error("Invalid @repeat syntax: "+r);const o=this.evaluateExpression(i[1],n),{endIndex:s,blockContent:a}=this.extractDirectiveBlock(t,e+1),c=[];if(Array.isArray(o))for(const t of o){const e={...n,locals:new Map([...n.locals.entries(),["it",t]])},r=await this.processTemplate(a.join("\n"),e,[]);c.push(r)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(t,e,n,r){const i=t[e].trim(),o=i.match(/^@if\s+(.+)$/);if(!o)throw Error("Invalid @if syntax: "+i);const s=!!this.evaluateExpression(o[1],n),{endIndex:a,blockContent:c,elseContent:l}=this.extractIfElseBlock(t,e+1);let u="";return s?u=await this.processTemplate(c.join("\n"),n,[]):l.length>0&&(u=await this.processTemplate(l.join("\n"),n,[]),r.push("@else")),{nextIndex:a+1,rendered:u}}extractDirectiveBlock(t,e){const n=[];let r=1,i=e;for(;t.length>i&&r>0;){const e=t[i].trim();e.startsWith("@repeat ")||e.startsWith("@if ")?(r++,n.push(t[i])):"@end"===e?(r--,r>0&&n.push(t[i])):n.push(t[i]),i++}return{endIndex:i-1,blockContent:n}}extractIfElseBlock(t,e){const n=[],r=[];let i=1,o=e,s=!1;for(;t.length>o&&i>0;){const e=t[o].trim();if(e.startsWith("@if "))i++;else{if("@else"===e&&1===i){s=!0,o++;continue}if("@end"===e&&(i--,0===i))break}s?r.push(t[o]):n.push(t[o]),o++}return{endIndex:o,blockContent:n,elseContent:r}}processVariableInterpolation(t,e){return t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=n.trim();if(t.startsWith("unescaped ")){const n=t.substring(10).trim();return(this.evaluateExpression(n,e)||"")+""}const r=this.evaluateExpression(t,e);return this.escapeHtml((r||"")+"")}catch(e){return Re(`render: template interpolation error for ${n}:`,e),t}})}evaluateExpression(t,e){if("true"===t)return!0;if("false"===t)return!1;if("null"===t)return null;if("undefined"===t)return;const n=Number(t);if(!isNaN(n)&&""!==t.trim())return n;if(t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++){if("object"!=typeof r||null===r)return;r=r[n[t]]}return r}return this.resolveVariable(t,e)}resolveVariable(t,e){return e.locals?.has(t)?e.locals.get(t):"me"===t?e.me:"it"===t?e.it??e.result:"you"===t?e.you:"result"===t?e.result??e.it:e.globals?.has(t)?e.globals.get(t):void 0}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(t){if("undefined"==typeof document)return null;const e=document.createElement("div");return e.innerHTML=t,1===e.children.length?e.firstElementChild:e}}function Za(){if("undefined"!=typeof window&&window.LokaScriptSemantic)return window.LokaScriptSemantic;throw Error('LokaScriptSemantic not found. Load the semantic bundle before the multilingual bundle:\n<script src="lokascript-semantic.browser.global.js"><\/script>\n<script src="hyperfixi-multilingual.js"><\/script>')}Wa.metadata=go({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",compatibility:"standard",sideEffects:["dom-creation","template-execution"]});const Ja=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],Ka=function(t,e){const n=new Pr(null);for(const e of t)n.register(e);return new zr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([$o(),jo(),Jo(),ts(),ks(),Ss(),$s(),Os(),Rs(),Is(),Ps(),Hs(),Fs(),Ws(),Ks(),Xs(),Qs(),ta(),ea(),ra(),sa(),aa(),ca(),fa(),ma(),ga(),va(),wa(),Ea(),ka(),da(),Sa(),Ta(),new Aa,Ca(),$a(),Na(),Ra(),La(),Ia(),Ma(),Pa(),qa(),Ha(),Ba(),Da(),Va(),Fa(),Ua(),_a(),new za,new Wa],{expressionRegistry:uo()}),Xa={async execute(t,e,n){const r=Za(),i=r.parseSemantic(t,e);if(.5>i.confidence||!i.node)throw Error(`Failed to parse "${t}" in language "${e}" (confidence: ${i.confidence.toFixed(2)})`);const o=r.buildAST(i.node),s=yt(n);return Ka.execute(o.ast,s)},parse(t,e){const n=Za(),r=n.parseSemantic(t,e);return.5>r.confidence||!r.node?null:n.buildAST(r.node).ast},translate:(t,e,n)=>Za().translate(t,e,n),getAllTranslations:(t,e)=>Za().getAllTranslations(t,e),createContext:pt,runtime:Ka,version:"1.0.0-multilingual",commands:["hide","show","add","remove","toggle","put","make","wait","fetch","set","get","increment","decrement","default","trigger","send","go","if","repeat","break","continue","halt","return","exit","unless","throw","call","pseudo-command","append","prepend","transition","measure","settle","take","js","async","log","tell","copy","pick","beep","install","render"],supportedLanguages:Ja,bundleType:"multilingual",processNode:async t=>{t===document||t===document.documentElement?await tc():t instanceof HTMLElement&&await Qa(t)},process:async t=>Xa.processNode(t)},Ga=new WeakSet;let Ya=null;async function Qa(t){if(Ga.has(t))return;const e=t.getAttribute("_");if(e)try{const n=function(t){const e=t.getAttribute("data-lang");if(e&&Ja.includes(e))return e;let n=t;for(;n;){const t=n.getAttribute("lang");if(t){const e=t.split("-")[0].toLowerCase();if(Ja.includes(e))return e}n=n.parentElement}return"en"}(t);Ie(`ATTR-ML: Processing element with lang="${n}":`,e.substring(0,60));const r=Za(),i=r.parseSemantic(e,n);if(.5>i.confidence||!i.node)return void Ie(`ATTR-ML: Low confidence (${i.confidence.toFixed(2)}) for: ${e}`);const o=r.buildAST(i.node),s=yt(t);await Ka.execute(o.ast,s),Ga.add(t),Ie("ATTR-ML: Successfully processed element")}catch(t){Ie("ATTR-ML: Error processing element:",t.message)}}async function tc(){const t=document.querySelectorAll("[_]");Ie(`ATTR-ML: Found ${t.length} elements with _ attributes`);const e=[];t.forEach(t=>{t instanceof HTMLElement&&e.push(Qa(t))}),await Promise.all(e),Ie("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:t.length}}))}function ec(){"undefined"!=typeof MutationObserver&&(Ya=new MutationObserver(t=>{for(const e of t)e.addedNodes.forEach(t=>{if(t.nodeType!==Node.ELEMENT_NODE)return;const e=t;e.getAttribute?.("_")&&Qa(e).catch(t=>{Ie("ATTR-ML: Error processing dynamic element:",t)});const n=e.querySelectorAll?.("[_]");n?.forEach(t=>{t instanceof HTMLElement&&Qa(t).catch(t=>{Ie("ATTR-ML: Error processing dynamic descendant:",t)})})})}),Ya.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=Xa,void 0===window.lokascript&&Object.defineProperty(window,"lokascript",{get:()=>(console.warn("[DEPRECATED] window.lokascript is deprecated and will be removed in v3.0.0. Please use window.hyperfixi instead."),window.hyperfixi),enumerable:!0,configurable:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{tc().then(()=>ec())}):tc().then(()=>ec())),t.default=Xa,t.hyperfixi=Xa,Object.defineProperty(t,"l",{value:!0}),t}({});
1
+ var _hyperfixiMultilingualInternal=function(t){"use strict";class e{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return!1;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const n of this.afterExecuteHooks)await n(t,e)}async runOnError(t,e){let n=e;for(const e of this.onErrorHooks){const r=await e(t,n);r instanceof Error&&(n=r)}return n}shouldIntercept(t,e){for(const n of this.interceptCommandHooks)if(n(t,e))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function n(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function r(t){return{ok:!0,value:t}}function i(t){return{ok:!1,error:t}}function o(t){return!0===t.ok}const s="then",a="else",c="end",l="and",u="for",f="while",d="until",h="forever",m="times",p="index",y="in",g="to",b="from",v="with",w="of",E="on",x="event",k="behavior",S="global",T="the",A="start",C=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","open","pick","prepend","process","pseudo-command","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait","for"]),$=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),O=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),j="at end of",N=["into","before","after","at",O,j,"at the start of","at the end of"],R=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"]),L=t=>C.has(t.toLowerCase()),I=t=>$.has(t.toLowerCase()),M=t=>R.has(t.toLowerCase()),P=t=>q.has(t.toLowerCase()),q=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"]),H=new Set(["me","it","you","result","my","its","your"]),B=new Set(["and","or","not","no"]),D=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","is between","is not between","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),V=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"]),F=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"]),U=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),_=new Set([")","]","}",","]);function z(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const i=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function W(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const i=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function Z(t,e){return{prefix:{bp:t,handler:e??((e,n)=>{const r=n.parseExpr(t);return{type:"unaryExpression",operator:e.value,operand:r,argument:r,prefix:!0,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function J(t){return(e,n,r)=>{const i=r.advance();if(!i||!i.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let o=!0;const s=r.peek();return s&&"!"===s.value&&(r.advance(),o=!1),{type:"typeCheckExpression",value:e,typeName:i.value,nullOk:o,negated:t,start:e.start,end:i.end}}}const K=function(...t){const e=new Map;for(const n of t)for(const[t,r]of n){const n=e.get(t);e.set(t,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return e}(new Map([["or",z(10)],["||",z(10)],["and",z(20)],["&&",z(20)],["==",z(30)],["!=",z(30)],["<",z(30)],[">",z(30)],["<=",z(30)],[">=",z(30)],["is",z(30)],["matches",z(30)],["contains",z(30)],["starts with",z(30)],["ends with",z(30)],["does not start with",z(30)],["does not end with",z(30)],["is between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!1,start:t.start,end:o.end}})],["is not between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!0,start:t.start,end:o.end}})],["am between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!1,start:t.start,end:o.end}})],["am not between",z(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const o=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:o,negated:!0,start:t.start,end:o.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=!0,t)}}],["where",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:t,right:r,start:t.start,end:r.end}})],["sorted by",z(28,(t,e,n)=>{const r=n.parseExpr(29);let i="asc";const o=n.peek();if(o&&"string"==typeof o.value){const t=o.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),i="asc"):"desc"!==t&&"descending"!==t||(n.advance(),i="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:i,start:t.start,end:r.end}})],["mapped to",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:t,right:r,start:t.start,end:r.end}})],["split by",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:t,right:r,start:t.start,end:r.end}})],["joined by",z(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:t,right:r,start:t.start,end:r.end}})],["+",{...z(40),...Z(80)}],["-",{...z(40),...Z(80)}],["*",z(50)],["/",z(50)],["%",z(50)],["mod",z(50)],["^",W(60)],["**",W(60)],["as",z(70,(t,e,n)=>{const r=()=>{const t=n.peek();!t||"a"!==t.value&&"an"!==t.value||n.advance();const e=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&e&&"identifier"===e.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(e.name=`${e.name}:${t.value}`,e.end=t.end)}return e};let i=r(),o={type:"asExpression",expression:t,targetType:i,start:t.start,end:i.end??e.end,line:t.line??e.line,column:t.column??e.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const t=r();o={type:"asExpression",expression:o,targetType:t,start:o.start,end:t.end??o.end,line:o.line,column:o.column}}return o})],["not",Z(80)],["!",Z(80)],["no",Z(27)]]),new Map([["===",z(30)],["!==",z(30)],["is not",z(30)],["am",z(30)],["is in",z(30)],["is not in",z(30)],["precedes",z(30)],["does not precede",z(30)],["follows",z(30)],["does not follow",z(30)],["is a",z(30,J(!1))],["is an",z(30,J(!1))],["is not a",z(30,J(!0))],["is not an",z(30,J(!0))],["has",z(30)],["have",z(30)],["match",z(30)],["include",z(30)],["includes",z(30)],["equals",z(30)],["does not contain",z(30)],["does not include",z(30)],["am in",z(30)],["am not in",z(30)],["is really",z(30)],["is not really",z(30)],["is equal",z(30)],["is not equal",z(30)],["contain",z(30)],["do not contain",z(30)],["does not contains",z(30)],["do not match",z(30)],["does not match",z(30)],["is equal to",z(30)],["is not equal to",z(30)],["is really equal to",z(30)],["is not really equal to",z(30)],["really equals",z(30)],["is greater than",z(30)],["is less than",z(30)],["is greater than or equal to",z(30)],["is less than or equal to",z(30)],["in",z(30)],["of",W(30)],["really",z(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["some",Z(80)]]),new Map([["=",W(5)]])),X=new Map,G=new Map,Y=new Map,Q=new Set,tt=new Set,et=new Set,nt=new Set;function rt(t){return X.get(t.toLowerCase())}function it(t){return Y.get(t)}function ot(t,e){if(0!==tt.size)for(const n of tt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function st(t,e,n){if(0!==et.size)for(const r of et)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function at(t,e){if(0!==nt.size)for(const n of nt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function ct(t,e,n){if(t.globals.set(e,n),0!==Q.size)for(const r of Q)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}const lt=new Map,ut=new WeakMap;function ft(t){let e=ut.get(t);return e||(e=new Map,ut.set(t,e)),e}function dt(t){return t.owner||(t.me instanceof Element?t.me:null)}function ht(t,e){const n=dt(t);if(n)return at(e,t),ft(n).get(e)}function mt(t,e,n){const r=dt(t);r&&(ft(r).set(e,n),st(e,n,t))}function pt(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||lt,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function yt(t){if(!t)return pt();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=pt(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}function gt(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function bt(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function vt(t){if(null==t)return 0;if("number"==typeof t)return isFinite(t)?t:0;if("string"==typeof t)return parseFloat(t);if("boolean"==typeof t)return t?1:0;if(Array.isArray(t))return t.length;if("object"==typeof t){if("length"in t&&"number"==typeof t.length)return t.length;if("function"==typeof t.valueOf){const e=t.valueOf();if("number"==typeof e)return e}return NaN}return 0}function wt(t,e,n){return"element"===n?ht(e,t):"global"===n&&e.globals&&e.globals.has(t)?e.globals.get(t):"global"!==n&&e.locals&&e.locals.has(t)?(at(t,e),e.locals.get(t)):e.globals&&e.globals.has(t)?e.globals.get(t):e.variables&&e.variables.has(t)?e.variables.get(t):"global"===n&&e.locals&&e.locals.has(t)?(at(t,e),e.locals.get(t)):"undefined"!=typeof window&&t in window?window[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}function Et(t,e,n,r){if("element"!==r){if("global"===r)return ct(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void ct(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void st(t,e,n);if(n.globals&&n.globals.has(t))return ct(n,t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(n.variables&&n.variables.has(t))n.variables.set(t,e);else{if("undefined"!=typeof window&&t in window)return window[t]=e,void ct(n,t,e);n.locals.set(t,e),st(t,e,n)}}else mt(n,t,e)}function xt(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:wt(t,e)}function kt(t,e,n){return n||"string"!=typeof e||!e.startsWith("#")?t:Array.isArray(t)?t[0]??null:t}function St(t){if("undefined"==typeof document)throw Error("DOM not available");const e=Array.from(document.querySelectorAll(t)).filter(t=>gt(t));if(!e.length)throw Error(`No elements: "${t}"`);return e}function Tt(t){if(gt(t))return[t];if(Array.isArray(t)){const e=t.filter(gt);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(gt);return e.length>0?e:null}return null}const At=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,n]of this.types)if(n.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),n=this.types.get(e);return n?.hyperscriptType??"unknown"}coerce(t,e,n){const r=this.types.get(e);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(r.isType(t))return t;if(this.config.cacheCoercions){const n=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(t),o=r.coerceFrom?.[i];if(o){const r=o(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(t,e){const n=this.types.get(e);if(!n)return!1;if(n.isType(t))return!0;const r=this.inferType(t);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(t,e){const n=this.types.get(e);return n&&(t===e||n.coerceFrom?.[t])?{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:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e||"false"!==e&&"no"!==e&&"0"!==e&&""!==e&&e.length>0},Number:t=>0!==t,Null:()=>!1,Undefined:()=>!1,Array:t=>!!Array.isArray(t)&&t.length>0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const n=t;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,n)=>{e[n+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>!0,defaultValue:null,description:"Unknown/any value type"})}};function Ct(t){const e=At.get("String");return e?e.isType(t):"string"==typeof t}function $t(t){const e=At.get("Number");return e?e.isType(t):"number"==typeof t}function Ot(t){const e=At.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function jt(t){const e=At.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Nt(t){const e=At.get("Function");return e?e.isType(t):"function"==typeof t}function Rt(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Lt(t){return t instanceof Element}function It(t){return t instanceof HTMLElement}const Mt=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Pt(t,e){return Mt.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const qt={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return!1;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>Rt(t)?t.tabIndex:void 0,hidden:t=>Rt(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,next:t=>t.nextElementSibling,previous:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function Ht(t,e){if(e.startsWith("*"))return function(t,e){if(!It(t))return;if(e.startsWith("computed-"))return getComputedStyle(t).getPropertyValue(e.slice(9))||"";const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}(t,e.slice(1));if(e.startsWith("computed-")){const n=e.slice(9);return It(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return Pt(t,e.slice(1));const n=qt[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Pt(t,e);const r=t[e];return Nt(r)?r.bind(t):r}const Bt={1:"one",2:"two",3:"three",4:"four",5:"five"};function Dt(t,e,n,r){if(t.length!==e){return`${n} requires exactly ${i=e,Bt[i]??i+""} argument${1===e?"":"s"}${r?` (${r})`:""}`}var i;return null}function Vt(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function Ft(t,e,n){return Dt(t,1,e,n)??Vt(t,0,e,n)}function Ut(t,e){return Dt(t,2,e,"left, right")}function _t(){return null}function zt(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function Wt(t,e,n,r,i){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${i?` (${i})`:""}`:null}const Zt={conversions:{dynamicResolvers:[]}},Jt={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":Ct(t)?t:jt(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Ot(t))return t;if(null==t)return!1;if(Ct(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return $t(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if($t(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if($t(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!$t(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=Jt.Number(t);return Math.trunc(e)},Float:t=>{const e=Jt.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(Ct(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return new Date(e,n-1,r)}return new Date(t)},JSON:t=>{if(!Ct(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(jt(t))return t;if(Ct(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{const e=document.createDocumentFragment(),n=Array.isArray(t)||t instanceof NodeList?Array.from(t):[t];for(const t of n)if(t instanceof Node)e.append(t);else{const n=document.createElement("template");n.innerHTML=null==t?"":t+"",e.append(n.content)}return e},HTML:t=>Ct(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:Jt.String(t)).join(""):t instanceof Element?t.outerHTML:Jt.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return function(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Kt(n);void 0!==t&&(void 0!==e[n.name]?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(t)):e[n.name]=t)}}),e}(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Kt(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?Jt.Values(t,e):t;if(!jt(n))return"";const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return""+r},Set:t=>new Set(t),Map:t=>new Map(Object.entries(t??{})),Keys:t=>t instanceof Map?Array.from(t.keys()):Object.keys(t??{}),Entries:t=>t instanceof Map?Array.from(t.entries()):Object.entries(t??{}),Reversed:t=>Array.from(t).reverse(),Unique:t=>[...new Set(t)],Flat:t=>Array.from(t).flat(),"Values:Form":(t,e)=>{const n=Jt.Values(t,e);return Jt.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=Jt.Values(t,e);return JSON.stringify(n)}};function Kt(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const Xt={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function Gt(t,e,n){if("string"!=typeof e)throw Error("Conversion type must be a string");if(e.startsWith("Fixed")){const{precision:n}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):0}:{}}(e);return Jt.Number(t).toFixed(n??0)}if(null==t)return t;let r=Jt[e];if(r)return r(t,n);const i=Xt[e.toLowerCase()];if(i&&(r=Jt[i],r))return r(t,n);const o=Zt.conversions[e];if("function"==typeof o)return o(t,n);for(const n of Zt.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Yt={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Gt(n,r,t)},validate:t=>Dt(t,2,"as","value, type")??Vt(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[n,r]=e;if(!Ct(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return Ct(n);case"number":return $t(n)&&!isNaN(n);case"boolean":return Ot(n);case"object":return jt(n);case"array":return Array.isArray(n);case"function":return Nt(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||jt(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>Dt(t,2,"is","value, type")??Vt(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>Dt(t,1,"async","expression")}},Qt=new Set(["__proto__","constructor","prototype"]);function te(t,e){if(t instanceof Element)return Ht(t,e);if(jt(t)){if(Qt.has(e))return;return t[e]}return t[e]}function ee(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return!1;e=Array.from(t)}return 0!==e.length&&e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const ne={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[n,r]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return ee(n)&&!(r in n)?Array.from(n,t=>te(t,r)):te(n,r)}},validate:t=>Dt(t,2,"possessive","element, property")??Vt(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[n]=e;if(t.me){if("string"!=typeof n)throw Error("Property name must be a string");if(t.me instanceof Element)return Ht(t.me,n);if(jt(t.me)){if(Qt.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>Ft(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[n]=e;if(null==t.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=t.it;if(r instanceof Element)return Ht(r,n);if(jt(r)){if(Qt.has(n))return;return r[n]}return r[n]},validate:t=>Ft(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[n]=e;if(t.you){if("string"!=typeof n)throw Error("Property name must be a string");if(t.you instanceof Element)return Ht(t.you,n);if(jt(t.you)){if(Qt.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>Ft(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[n,r]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Ht(r,n);if(jt(r)){if(Qt.has(n))return;return r[n]}return r[n]}},validate:t=>Dt(t,2,"of","property, object")??Vt(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");const i=r||t.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:t=>Wt(t,1,2,"attribute","attributeName, optional element")??Vt(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[n,r,i]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const o=i||t.me;return!!(o&&o instanceof Element)&&o.getAttribute(n)===r},validate:t=>Wt(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Vt(t,0,"attributeWithValue","attribute name")??Vt(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:t=>Ft(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:t=>Ft(t,"idReference","idValue")}};function re(t){return Array.isArray(t)?t:null==t?[]:"string"==typeof t?[t]:t instanceof NodeList||t instanceof HTMLCollection||"number"==typeof t.length?Array.from(t):[t]}var ie;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(ie||(ie={}));const oe=new Set(["+","-","*","/","mod"]),se=new Set(["ms","s","seconds","minutes","hours","days"]);function ae(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function ce(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function le(t){const e=t.input,n=e.length;for(;n>t.position;){const n=e[t.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;ce(t)}}function ue(t,e,n,r,i){const o=r??t.position-n.length,s=t.position;let a=t.column-n.length;if(void 0!==r){a=1;let e=-1;for(let n=0;r>n;n++)"\n"!==t.input[n]&&"\r"!==t.input[n]||(e=n);a=r-e}const c={kind:e,value:n,start:o,end:s,line:fe(t,o),column:a};t.tokens.push(c)}function fe(t,e){let n=1;for(let r=0;e>r&&t.input.length>r;r++){const e=t.input[r];"\n"===e?n++:"\r"===e&&(n++,t.input.length>r+1&&"\n"===t.input[r+1]&&r++)}return n}function de(t){const e=t.position;let n="";for(ce(t),ce(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=ce(t);ue(t,ie.COMMENT,"--"+n,e)}function he(t){const e=t.position,n=ce(t);let r=n;for(;t.input.length>t.position;){const e=ce(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=ce(t))}ue(t,ie.STRING,r,e)}function me(t){const e=t.position;ce(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){ce(t);break}if("\\"===e){if(ce(t),t.input.length>t.position){const e=ce(t);switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=e}}}else n+=ce(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);ue(t,ie.TEMPLATE,n,e)}function pe(t){const e=t.position;let n=ce(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=ce(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=ce(t),"}"===e)break}ue(t,ie.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)ce(t),t.input.length>t.position&&(n+=ce(t));else{if(!ke(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=ce(t)}}ue(t,ie.SELECTOR,n,e)}}function ye(t){const e=t.position;if(Se(t))return void function(t,e){const n=t.input;let r="",i=0,o="";for(;n.length>t.position;){const e=n[t.position];if(o)r+=ce(t),e===o&&(o="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=ce(t);if(n.length>t.position&&(r+=ce(t)),i--,0>=i)break;continue}let e=!1,o="";for(;n.length>t.position;){const i=n[t.position];if(o)r+=ce(t),i===o&&(o="");else if('"'!==i&&"'"!==i){if(">"===i){e="/"===n[t.position-1],r+=ce(t);break}r+=ce(t)}else o=i,r+=ce(t)}if(e||i++,0>=i)break;continue}r+=ce(t)}else o=e,r+=ce(t)}ue(t,ie.SELECTOR,r,e)}(t,e);let n="";for(n+=ce(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=ce(t),"/"===e&&">"===r){n+=ce(t);break}}ue(t,ie.SELECTOR,n,e)}function ge(t){const e=t.position;let n=ce(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!ke(e)&&"_"!==e&&"-"!==e)break;n+=ce(t)}ue(t,ie.SYMBOL,n,e)}function be(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===ae(t,1))return n="'s",ce(t),ce(t),void ue(t,ie.OPERATOR,n,e);const i=t.input.substring(t.position,t.position+2),o=t.input.substring(t.position,t.position+3);["===","!=="].includes(o)?(n=o,ce(t),ce(t),ce(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,ce(t),ce(t)):n=ce(t),ue(t,ie.OPERATOR,n,e)}function ve(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=ce(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(i+=ce(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=ce(t)}if(r>t.position){const e=n[t.position];if("e"===e||"E"===e){const e=r>t.position+1?n[t.position+1]:"",o=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">o||o>"9"))for(i+=ce(t),"+"!==n[t.position]&&"-"!==n[t.position]||(i+=ce(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=ce(t)}}}const o=t.position;let s="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;s+=ce(t)}se.has(s)?ue(t,ie.TIME,i+s,e):(t.position=o,ue(t,ie.NUMBER,i,e))}function we(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;i+=ce(t)}const o=function(t,e,n){const r=e.toLowerCase(),i=t.position;if("'s"===e||"'s"===e)return!1;const o=t.tokens[t.tokens.length-1];if(o&&(o.kind===ie.IDENTIFIER||o.kind===ie.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}le(t);let s="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=ce(t)}if(s){const e=s.toLowerCase(),i=`${r} ${e}`,o=function(t,e,n,r){const i=e.toLowerCase(),o=n.toLowerCase();if("at"===i){const e=t.position;if("the"===o){le(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=ce(t)}const i=n.toLowerCase();if("start"===i||"end"===i){le(t);let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;e+=ce(t)}if("of"===e.toLowerCase())return ue(t,ie.IDENTIFIER,`at the ${i} of`,r),!0}return t.position=e,!1}if("start"===o||"end"===o){le(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;n+=ce(t)}return"of"===n.toLowerCase()?(ue(t,ie.IDENTIFIER,`at ${o} of`,r),!0):(t.position=e,!1)}}return!1}(t,r,e,n);if(o)return!0;const a=function(t,e,n){const r=t.position;let i=`${e} ${n}`,o=t.position;const s=[e,n];for(;8>s.length&&(le(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;e+=ce(t)}if(!e)break;s.push(e.toLowerCase());const n=s.join(" ");D.has(n)&&(i=n,o=t.position)}return D.has(i)&&i!==`${e} ${n}`?(t.position=o,i):(t.position=r,null)}(t,r,e);if(a)return ue(t,ie.OPERATOR,a,n),!0;if(D.has(i))return ue(t,ie.OPERATOR,i,n),!0}return D.has(r)?(t.position=i,ue(t,ie.OPERATOR,e,n),!0):(t.position=i,!1)}(t,i,e);if(o)return;const s=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||B.has(e)||oe.has(t)||oe.has(e)||D.has(e)?ie.OPERATOR:ie.IDENTIFIER}(i);ue(t,s,i,e)}function Ee(t){const e=t.position,n=t.input,r=n.length;ce(t);let i="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;i+=ce(t)}ue(t,ie.IDENTIFIER,i,e)}function xe(t){return/[a-zA-Z]/.test(t)}function ke(t){return/[a-zA-Z0-9]/.test(t)}function Se(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=t.position+1,i="";for(;e.length>r&&/[a-zA-Z0-9-]/.test(e[r]);)i+=e[r],r++;return i.length>0&&-1!==e.indexOf("</"+i+">",r)}function Te(t){if(Se(t))return!0;let e=t.position+1,n=!1;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(ke(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,e++;else{if(" "!==r&&"\t"!==r)return!1;e++}if(e-t.position>50)return!1}return!1}function Ae(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const Ce=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),$e=Ce,Oe=Ce,je=Ce,Ne=Ce,Re=(...t)=>{$e&&console.log("\ud83d\udd27",...t)},Le=(...t)=>{Oe&&console.log("\ud83c\udfaf",...t)},Ie=(...t)=>{je&&console.log("\ud83d\udcdd",...t)},Me=(...t)=>{Ne&&console.log("\ud83d\ude80",...t)};let Pe=!1,qe=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(Pe=!0,qe=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let He={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class Be{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(Be.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const n=t.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(t)}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(t,this.language),i=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const o=r.confidence>=this.confidenceThreshold&&!!r.command,s=!o&&r.confidence>0;if(Pe){const e={};if(r.command?.roles)for(const[t,n]of r.command.roles)e[t]=n.value;const a={input:t.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:o,fallbackTriggered:s,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(t){if(!Pe)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),i=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),qe){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});qe.dispatchEvent(e)}}(a),n=a,He.totalParses++,n.semanticSuccess?He.semanticSuccesses++:n.fallbackTriggered?He.semanticFallbacks++:He.traditionalParses++,He.confidenceHistory.push(n.confidence),He.confidenceHistory.length>100&&He.confidenceHistory.shift(),He.averageConfidence=He.confidenceHistory.reduce((t,e)=>t+e,0)/He.confidenceHistory.length}return o?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:!1,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var n}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const n=this.analyzer.buildCommandNode?.(e);if(!n)throw Error(`Semantic analyzer cannot build an AST node for '${e.name}' (no buildCommandNode wired \u2014 see createSemanticAdapter's buildAST dep)`);return n}buildRepeatCommandNode(t){const e=[],n={},r=t.roles.get("loopType");r&&e.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("patient");"for"==(r?r.value+"":"")&&i&&e.push({type:"identifier",name:"expression"===i.type&&i.raw||i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("event");o&&e.push({type:"string",value:o.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("source");s&&e.push(this.semanticValueToExpression(s));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],n=t.roles.get("destination");if(n)if("property-path"===n.type){const t=n;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(n));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=t.roles.get("patient");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],n=t.roles.get("condition");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:t.name,args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const n=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},r=()=>{n();const r=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(r,e)},i=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(o()),n();","===t[e];)e++,n(),r.push(o()),n();return")"===t[e]&&e++,r},o=()=>{n();const o=r();if(!o)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let s={type:"identifier",name:o,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const o=t[e];if("."===o){e++;const t=r();t&&(s={type:"memberExpression",object:s,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==o)break;s={type:"callExpression",callee:s,arguments:i(),start:0,end:0,line:1,column:0}}}return s};return o()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function De(t){return t.kind===ie.IDENTIFIER&&C.has(t.value.toLowerCase())}function Ve(t){return t.kind===ie.IDENTIFIER&&F.has(t.value.toLowerCase())}function Fe(t){return t.kind===ie.IDENTIFIER&&V.has(t.value.toLowerCase())}function Ue(t){return t.kind===ie.IDENTIFIER&&H.has(t.value.toLowerCase())}function _e(t){return D.has(t.value.toLowerCase())}function ze(t){return t.kind===ie.IDENTIFIER}function We(t){return t.kind===ie.SELECTOR}function Ze(t){return t.kind===ie.SELECTOR&&!t.value.startsWith("<")}function Je(t){return t.kind===ie.STRING||t.kind===ie.NUMBER||t.kind===ie.TEMPLATE}function Ke(t){return t.kind===ie.IDENTIFIER}function Xe(t){return t.kind===ie.TIME}function Ge(t){return t.kind===ie.SYMBOL}function Ye(t){return t.kind===ie.COMMENT}function Qe(t){if(t.kind!==ie.IDENTIFIER)return!1;const e=t.value.toLowerCase();return!(C.has(e)||F.has(e)||V.has(e)||H.has(e))}function tn(t){return t.kind===ie.STRING}function en(t){return t.kind===ie.NUMBER}function nn(t){if(t.kind===ie.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function rn(t){return t.kind===ie.TEMPLATE}function on(t){return t.kind===ie.SELECTOR&&t.value.startsWith("<")}function sn(t){return t.kind===ie.SELECTOR&&t.value.startsWith("#")}function an(t){return t.kind===ie.SELECTOR&&t.value.startsWith(".")}function cn(t){return t.kind===ie.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function ln(t){if(t.kind!==ie.OPERATOR)return!1;const e=t.value.toLowerCase();return!B.has(e)&&!D.has(e)}function un(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function fn(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function dn(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function hn(t,e,n,r){return{type:"binaryExpression",operator:t,left:e,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function mn(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function pn(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function yn(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function gn(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function bn(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function vn(t,e,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...n&&{source:n}}],start:t.start,end:t.end,line:t.line,column:t.column}}Be.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const wn=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"prepend",keywords:["to"],syntax:"prepend <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"throw",keywords:[],syntax:"throw <error>"}];function En(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const xn=[s,l,a,c];function kn(t,e=[]){if(t.isAtEnd())return!0;for(const e of xn)if(t.check(e))return!0;for(const n of e)if(t.check(n))return!0;return!!t.checkIsCommand()}function Sn(t,e=[]){if(!kn(t,e))return t.parseExpression()}function Tn(t,e,n){return!!t.check(e)&&(t.advance(),n.push(t.createIdentifier(e)),!0)}function An(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function Cn(t,e){return!!t.check(e)&&(t.advance(),!0)}function $n(t){const e=t.savePosition();let n;if(t.checkIdentifierLike()){const r=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=r):t.restorePosition(e)}const r=t.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class On{constructor(t){this.args=[],this.isBlocking=!1,this.name=t}static from(t){const e=new On(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new On(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new On(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=!0){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new On(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function jn(t,e){const n=[];let r="";const i=t.peek().start||0,o=t.peek().line||1,s=t.peek().column||1;if(t.checkIdentifierLike()){for(r=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),r+=":",t.checkIdentifierLike()&&(r+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const{name:n,value:r}=$n(t);if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),n.push({type:"functionCall",name:r,args:e,start:i,end:t.getPosition().end,line:o,column:s})}else n.push({type:"string",value:r,start:i,end:t.getPosition().end,line:o,column:s})}const a=[...n];for(;!kn(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}const e=t.savePosition(),n=t.parsePrimary();n&&a.push(n),t.savePosition()===e&&t.advance()}return On.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Nn(t,e){const n=[];if(t.check(T)){const e=t.advance();if(n.push({type:"identifier",name:T,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(x)){const e=t.advance();n.push({type:"identifier",name:x,start:e.start,end:e.end,line:e.line,column:e.column})}}return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Rn(t,e){const n=[],r=()=>t.check(c)||e&&t.check(a);for(;!t.isAtEnd()&&!r();){if(Ye(t.peek())){t.advance();continue}if(!t.checkIsCommand()&&!t.isCommand(t.peek().value))break;t.advance();const e=t.parseCommand();e&&n.push(e),(t.check(s)||t.check(l)||t.check(","))&&t.advance()}return n}const Ln=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function In(t,e,n){return null!==e&&!Ln.has(e.value?.toLowerCase?.()??"")&&(t.checkIsCommand()||t.isCommand(n.value?.toLowerCase()))}function Mn(t,e){const n=[];let r=!1;const i=t.savePosition();let o=null;for(let n=0;500>n&&!t.isAtEnd();n++){const n=t.peek();if(n.value===s){r=!0;break}if(n.value===c||n.value===k||"def"===n.value||n.value===E)break;if(void 0!==n.line&&n.line!==e.line&&In(t,o,n))break;Ye(n)||(o=n),t.advance()}t.restorePosition(i);let l=!1;if(!r){const n=t.savePosition(),r=e.line,i=100;let o=!1,s=null;for(;!t.isAtEnd()&&i>t.current-n;){const e=t.peek(),n=e.value?.toLowerCase();if(o&&void 0!==e.line&&e.line!==r)break;if(n===k||"def"===n||n===E)break;if(n===a||n===c){e.line===r&&(l=!0);break}if(In(t,s,e)){if(void 0!==e.line&&e.line!==r){l=!0;break}o=!0}Ye(e)||(s=e),t.advance()}t.restorePosition(n)}const u=r||l;let f;if(u)f=t.parseExpression();else{const n=[],r=20;let i=0,o=!0;for(;!t.isAtEnd()&&!t.check(s)&&(o||!t.checkIsCommand()&&!t.isCommand(t.peek().value))&&r>i;){o=!1;const e=t.savePosition();n.push(t.parseLogicalAnd()),t.savePosition()===e&&t.advance(),i++}if(0===n.length)throw Error("Expected condition after if/unless");f=1===n.length?n[0]:{type:"expression",tokens:n,start:n[0].start,end:n[n.length-1].end,line:e.line,column:e.column}}if(n.push(f),u){Cn(t,s);const r=Rn(t,!0);if(0===r.length&&t.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");n.push(mn(r,{start:e.start,end:t.getPosition().end,line:e.line,column:e.column}));let i=!1;if(t.check(a))if(t.advance(),t.check("if")){const e=t.peek();t.advance();const r=Mn(t,e);n.push(mn([r],{start:e.start,end:t.getPosition().end,line:e.line,column:e.column})),i=!0}else{const r=Rn(t,!1);n.push(mn(r,{start:e.start,end:t.getPosition().end,line:e.line,column:e.column}))}i||t.consume(c,"Expected 'end' after if block")}else{if(!t.checkIsCommand()&&!t.isCommand(t.peek().value))throw Error("Expected command after if condition in single-line form");{t.advance();const r=t.parseCommand();n.push(mn([r],{start:e.start,end:t.getPosition().end,line:e.line,column:e.column}))}}return On.from(e).withArgs(...n).endingAt(t.getPosition()).build()}function Pn(t,e){const n=[],r={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(n.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();n.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();r.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const i=On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const qn=new Set(["my","its","your"]);function Hn(t){const e={};if(Cn(t,u)){const n=t.parseExpression();return n&&(e.for=n),e}if(!t.check(d))return e;t.advance();const n=t.peek();if(!n||!ze(n))return e;t.advance();let r=n.value;if(t.check(":")){t.advance();const e=t.peek();e&&ze(e)&&(t.advance(),r=`${r}:${e.value}`)}if(e.until={type:"literal",value:r,raw:r},Cn(t,b)){const n=Sn(t);n&&(e.from=n)}return e}function Bn(t,e){const n=[],r=Sn(t,[b]);r&&n.push(r),Tn(t,b,n);const i=Sn(t);return i&&n.push(i),On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Dn(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const r=Sn(t,[l]);if(r&&"binaryExpression"===r.type&&"and"===r.operator)r.left&&n.push(r.left),n.push(t.createIdentifier("and")),r.right&&n.push(r.right);else{r&&n.push(r),Tn(t,l,n);const e=Sn(t,[b,E,u]);e&&n.push(e)}if(An(t,[b,E],n)){const e=Sn(t);e&&n.push(e)}return On.fromIdentifier(e).withArgs(...n).withModifiers(Hn(t)).endingAt(t.getPosition()).build()}const r=Sn(t,[b,E]);if(r&&n.push(r),An(t,[b,E],n)){const e=Sn(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),On.fromIdentifier(e).withArgs(...n).withModifiers(Hn(t)).endingAt(t.getPosition()).build()}function Vn(t,e){if(!t.check("using"))return!1;if(t.advance(),!t.match("view"))throw Error("expected 'view transition' after 'using'");if(!t.match("transition"))throw Error("expected 'transition' after 'using view'");return e.push(t.createIdentifier("using")),e.push(t.createIdentifier("view")),e.push(t.createIdentifier("transition")),!0}function Fn(t,e){const n=t.parseExpression();if(!n)return t.addError("Put command requires content expression"),null;const r=t.peek();if(!r||!N.includes(r.value))return t.addError(`Expected operation keyword (${N.join(", ")}) after put expression, got: ${r?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=O:"at end of"===o||"at the end of"===o?i=j:"at"===i&&(t.check(A)||t.check(T)?(Cn(t,T),t.check(A)&&(t.advance(),t.check(w)&&(t.advance(),i=O))):t.check(c)&&(t.advance(),t.check(w)&&(t.advance(),i=j)));const s=t.parseExpression();return s?On.fromIdentifier(e).withArgs(n,t.createIdentifier(i),s).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Un=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function _n(t,e){const n=t.savePosition();let r=null,i=[];try{r=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end}}(t)??function(t){if(!t.check(S)&&!t.check("local"))return null;const e=t.advance(),n=t.advance();return{type:"identifier",name:n.value,scope:e.value,start:e.start,end:n.end}}(t)??function(t){if(!t.check(T))return null;const e=t.savePosition();t.advance();const n=t.parseExpression();if(!n)return t.restorePosition(e),null;if("binaryExpression"===n.type&&n.operator===w){const t=n.left,e=n.right;return bn(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(g)?n:(t.restorePosition(e),null)}(t),r||(r=t.parseExpression())}catch{t.restorePosition(n),r=null}if(!r){const e=function(t){if(t.match(":")){const e=t.advance();return{expression:{type:"identifier",name:e.value,scope:"element",start:e.start,end:e.end},tokens:[]}}const e=[];for(;!(t.isAtEnd()||t.check(g)||t.check(s)||t.check(l)||t.check(a)||t.check(c));)e.push(t.parsePrimary());if(0===e.length)return{expression:null,tokens:[]};if(e.length>=4){const t=(t,e)=>t[e];if(t(e[0],"value")===T&&t(e[2],"value")===w){const n=e[1],r=e[3];return{expression:bn(dn(t(n,"value")||t(n,"name")||"",{start:n.start??0,end:n.end??0,line:n.line??1,column:n.column??1}),{type:"idSelector"===r.type?"idSelector":"cssSelector",value:t(r,"value")||t(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:e[0].start??0,end:r.end??0,line:e[0].line??1,column:e[0].column??1}),tokens:[]}}}return 1===e.length?{expression:e[0],tokens:[]}:{expression:null,tokens:e}}(t);r=e.expression,i=e.tokens}if(!t.check(g)){const e=t.isAtEnd()?"end of input":t.peek().value;throw Error("Expected 'to' in set command, found: "+e)}t.advance();const o=t.parseExpression()??t.parsePrimary();let u;var f;t.check(E)&&(f=t.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||zn.has(f.value))&&(t.advance(),u=Sn(t));const d=[];r?d.push(r):i.length>0&&d.push(...i),d.push(t.createIdentifier(g)),o&&d.push(o);const h=On.fromIdentifier(e).withArgs(...d);return u&&h.withModifier("on",u),h.endingAt(t.getPosition()).build()}const zn=new Set(["me","my","it","its","you","your","yourself"]),Wn=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]);function Zn(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Jn(t,e){const n=[];for(;!kn(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Kn(t){const e=t.peek();if("/"===e.value)return!0;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return!1}const Xn=new Set(["{",")"]);function Gn(t){const e=t.savePosition(),n=t.peek();let r="",i=null;for(;!t.isAtEnd();){const e=t.peek();if(i&&e.start!==i.end)break;if("$"===e.value&&"{"===t.peekAt(1)?.value){t.advance();let n=t.advance(),o=1;for(;!t.isAtEnd()&&o>0;)n=t.advance(),"{"===n.value?o++:"}"===n.value&&o--;r+=t.getInputSlice(e.start,n.end),i=n;continue}if(Xn.has(e.value))break;i=t.advance(),r+=i.value}if(!r||"/"===r)return t.restorePosition(e),null;const o={start:n.start,end:i?i.end:n.end,line:n.line,column:n.column};return r.includes("${")?{type:"templateLiteral",value:r,...o}:{type:"literal",value:r,raw:r,...o}}function Yn(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function Qn(t){const e=[],n=t.getPosition();do{if(!t.checkIdentifierLike())break;const n=t.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};t.consume(":","Expected ':' after property name in fetch named arguments");const i=t.parsePrimary();i&&e.push({key:r,value:i})}while(t.match(",")&&!t.isAtEnd());const r=t.getPosition();return{type:"objectLiteral",properties:e,start:n.start,end:r.end,line:n.line,column:n.column}}const tr=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class er{constructor(t,e,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new Be({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=n||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors],t.recovered=!0),t}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 t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:!1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}const t=this.peek(),e=t&&rt(t.value)?t.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==e){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const t=this.peekAt(1);if(null!==t&&("init"===t.value||"on"===t.value||"def"===t.value||void 0!==rt(t.value))){this.advance();continue}}if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def")){const e=this.peek(),n=e?rt(e.value):void 0;if(n){const e=this.advance(),r=n(this.getContext(),e);r&&t.push(r);continue}break}{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}}return this.isAtEnd()?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}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){Ie("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];Ie(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){Ie(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(Ie("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,Ie(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),Ie(`\u2705 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 Ie("\u26a0\ufe0f PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};Ie("\u2705 PARSER: No more event handlers, at end of input");break}}return Ie(`\u2705 PARSER: Finished parsing, creating Program node with ${e.length} statements`),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}}return this.isAtEnd()?this.error?{success:!1,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const t=this.peek();return n&&["number","string","identifier"].includes(t.kind)?this.addError(`Unexpected token: ${t.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+t.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,warnings:this.warnings}}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,n=this.prattCache.get(e);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),i=er.PRATT_TABLE.get(r.value);let o;if(i?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();o=i.prefix.handler(t,this.makePrattContext())}else o=this.parseCall();for(;!this.isAtEnd();){const e=this.peek();if(60>=t){const t=this.tryParseStringPostfix(o,e);if(t){o=t;continue}}const n=er.PRATT_TABLE.get(e.value);if(!n?.infix){if(U.has(e.value)||_.has(e.value))break;break}const[r]=n.infix.bp;if(t>r)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(t){Ie("arrow body discarded after error:",t instanceof Error?t.message:t+"")}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),o}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),o}const i=this.advance();if(this.isAtEnd()&&!er.POSTFIX_UNARY_OPERATORS.has(i.value))return this.addError(`Expected expression after '${i.value}' operator`),o;o=n.infix.handler(o,i,this.makePrattContext())}return this.prattCache.set(e,{node:o,endPos:this.current}),o}tryParseStringPostfix(t,e){const n=e.value;let r=null;if(tr.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const i=this.advance();return{type:"stringPostfix",expression:t,unit:r,start:t.start,end:i.end,line:t.line,column:t.column}}canStartOperand(t){if(!t)return!1;const e=t.value;return!U.has(e)&&!_.has(e)&&("number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(e))}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return!e||U.has(e.value)||_.has(e.value)},atEnd:()=>t.current>=t.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):L(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):M(t)}createCommandFromIdentifier(t){const e=[],n=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:!1,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return I(t)}parseCompoundCommand(t){return function(t,e){switch(e.name.toLowerCase()){case"put":return Fn(t,e);case"trigger":case"send":return jn(t,e);case"remove":return Bn(t,e);case"take":return function(t,e){const n=[],r={},i=Sn(t,[b,u]);if(i&&n.push(i),t.check(b)){Tn(t,b,n);const e=Sn(t,[u]);e&&n.push(e)}if(Cn(t,u)){const e=Sn(t);e&&(r.for=e)}return On.fromIdentifier(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(t,e);case"toggle":return Dn(t,e);case"set":return _n(t,e);case"halt":return Nn(t,e);case"measure":return Pn(t,e);case"js":return function(t,e){const n=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&n.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const r=t.peek().start,i=function(t,e){const n=t.getInputSlice(e);if(!n)return e;let r=0;for(;n.length>r;){const t=n[r];if("'"!==t&&"\u2019"!==t&&"\u2018"!==t)if('"'!==t)if("`"!==t)if("/"===t&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===t&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==t&&"E"!==t||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return e+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==t;)"\\"===n[r]&&r++,r++;r++}}return e+n.length}(t,r);for(;!t.isAtEnd()&&!t.check(c)&&t.peek().start<i;)t.advance();t.consume(c,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(r,i).trim(),start:e.start,end:t.getPosition().end},s={type:"arrayLiteral",elements:n.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return On.fromIdentifier(e).withArgs(o,s).endingAt(t.getPosition()).build()}(t,e);case"go":return function(t,e){const n=[];for(;!kn(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(Wn.has(r)){t.advance(),n.push(Zn(r,e));continue}if(Kn(t)){const r=Gn(t);if(r){n.push(r);continue}t.advance(),n.push(Zn(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(Zn(e.value,e));continue}if("number"===e.kind){t.advance();const r=t.peek();if(t.isAtEnd()||"px"!==r.value||r.start!==e.end)n.push({type:"literal",value:Number(e.value),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column});else{const r=t.advance();n.push(Zn(e.value+"px",{...e,end:r.end}))}continue}const i=t.current;if(n.push(t.parsePrimary()),t.current===i)break}return On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(t,e);case"tell":return function(t,e){const n=t.parseExpression();if(!n)throw Error("tell command requires a target expression");t.check(g)&&t.advance();const r=[];for(;!t.isAtEnd();){if(t.checkIsCommand()){try{t.advance();const e=t.parseCommand();if(!e)break;r.push(e)}catch{break}if(t.match(l)||t.match(s))continue;if(t.check(a))break;if(t.check(c)){t.advance();break}if(t.checkIsCommand())continue;break}break}if(0===r.length)throw Error("tell command requires at least one command after the target");return On.fromIdentifier(e).withArgs(n,...r).endingAt(t.getPosition()).build()}(t,e);case"pick":return function(t,e){const n=On.fromIdentifier(e);Cn(t,T);const r=t.peek().value,i=t=>({type:"literal",value:t,start:e.start,end:e.end}),o=()=>{if(!t.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return t.parseExpression()};if("first"===r){t.advance();const e=t.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("last")).withModifier("count",e).endingAt(t.getPosition()).build()}if("random"===r){let e;t.advance(),t.check("of")||t.check("from")||(e=t.parsePrimary());const r=o(),s=n.withArgs(r).withModifier("variant",i("random"));return e&&s.withModifier("count",e),s.endingAt(t.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let e,r;t.advance(),t.match("at","from"),e=t.match("start")?i("start"):t.parsePrimary();let s=!1;(t.match("to")||t.match(".."))&&(t.match("end")?s=!0:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=o(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",e).withModifier("rangeMode",i(a));return s?l.withModifier("rangeEnd",i("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let s;t.matchOperator("|")&&(s=t.advance().value);const a=o(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",e);return s&&c.withModifier("flags",i(s)),c.endingAt(t.getPosition()).build()}return Jn(t,e)}(t,e);case"start":return function(t,e){if(!t.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!t.match("transition"))throw Error("start view: expected 'transition'");const n={};if(t.match("using")){const e=t.parsePrimary();n.transitionName=e}const r=t.parseCommandListUntilEnd("start view transition");return On.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(t,e);case"swap":case"morph":return function(t,e){const n=[];let r=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const i=e.value.toLowerCase();Un.includes(i)&&(r=i,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(w)&&(t.advance(),n.push(t.createIdentifier("of")));const i=t.parseExpression();if(i&&n.push(i),!t.isAtEnd()&&t.check(v)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return Vn(t,n),On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(t,e);case"process":return function(t,e){if(!t.check("partials"))return null;const n=[];if(Tn(t,"partials",n),Tn(t,y,n)){const e=Sn(t,["using"]);e&&n.push(e)}return Vn(t,n),On.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(t,e)??Jn(t,e);default:return Jn(t,e)}}(this.getContext(),t)}parsePutCommand(t){return Fn(this.getContext(),t)}parseSetCommand(t){return _n(this.getContext(),t)}parseHaltCommand(t){return Nn(this.getContext(),t)}parseMeasureCommand(t){return Pn(this.getContext(),t)}parseTriggerCommand(t){return jn(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(Ie("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){Ie("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){Ie(r?"\u2705 Found COMMAND token:":"\u2705 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&&(Ie("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(Ie("\u2705 Parsed command:",r.name),e.push(r),t=!0)}catch(t){Ie("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&Ie("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){Ie("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(Ie("\ud83d\udccd After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)Ie("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))Ie("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){Ie("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}Ie("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const e of t)if(this.check(e)){r=e;break}return this.check("end")||t.some(t=>this.check(t))||(r=""),Ie("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(t="repeat"){const{commands:e}=this.parseCommandListUntilTerminator([]);if(Ie('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw Ie('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${t} block`);return Ie('\u2705 Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else"]),n="else"===e;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:t,hasElse:n}}parseRepeatBody(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===e)this.advance();else if(""===e)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:t,terminator:e}}parseRepeatCommand(t){return function(t,e){const n=[];let r="forever",i=null,o=null,s=null,a=null,c=null,l=null;if(t.check(u)){t.advance(),r=u;const e=t.peek();ze(e)&&(c=e.value,t.advance()),t.check(y)&&(t.advance(),a=t.parseExpression())}else if(t.check(y))t.advance(),r=u,c="it",a=t.parseExpression();else if(t.check(f))t.advance(),r=f,s=t.parseExpression();else if(t.check(d))if(t.advance(),r=d,t.check(x)){t.advance(),r="until-event";const e=t.peek();if(Ie("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!ze(e)&&!Fe(e))throw Error('Expected event name after "event"');if(i=e.value,t.advance(),Ie("\u2705 Got event name:",i,"Next token:",t.peek().value),Ie('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(b)){Ie('\u2705 Found "from", advancing...'),t.advance(),Ie('\ud83d\udccd After consuming "from", current token:',t.peek().value),Cn(t,T)&&Ie('\u2705 Found "the", advancing...');const e=t.peek();Ie("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),o=t.parsePrimary(),Ie("\u2705 After parsePrimary, eventTarget:",o)}else Ie('\u274c No "from" found, skipping target parsing')}else s=t.parseExpression();else t.check(h)?(t.advance(),r=h):(l=t.parseExpression(),t.check(m)&&(t.advance(),r=m));let g,w=null;if(t.check(v)){const e=t.peekAt(1);e&&e.value.toLowerCase()===p&&(t.advance(),t.advance(),w=p)}else if(t.check(p)){t.advance();const e=t.peek();ze(e)?(w=e.value,t.advance()):w=p}let E=null,k=!1;if(r===h){const e=t.parseRepeatBody();if(g=e.commands,"else"===e.terminator)t.advance(),E=t.parseCommandListUntilEnd();else if("until"===e.terminator||"while"===e.terminator){if(k=!0,r=e.terminator,t.advance(),s=t.parseExpression(),!t.check("end"))throw Error('Expected "end" to close repeat block');t.advance()}}else{const e=t.parseCommandListUntilEndOrElse();g=e.commands,e.hasElse&&(t.advance(),E=t.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column});const S={start:e.start,end:e.end,line:e.line,column:e.column};c&&n.push(pn(c,S)),a&&n.push(a),s&&n.push(s),l&&n.push(l),i&&n.push(pn(i,S)),o&&n.push(o),w&&n.push(pn(w,S)),n.push(mn(g,{...S,end:S.end||0})),null!==E&&n.push(mn(E,{...S,end:S.end||0}));const A=On.from(e).withArgs(...n);return k&&A.withModifier("bottomTested",{type:"literal",value:!0,...S}),A.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,i=null;t.check("each")&&t.advance();const o=t.peek();if(!ze(o))throw Error('Expected variable name after "for"');if(r=o.value,t.advance(),!t.check(y))throw Error('Expected "in" after variable name in for loop');if(t.advance(),i=t.parseExpression(),!i)throw Error('Expected collection expression after "in"');let s=null;if(t.check(v)){const e=t.peekAt(1);e&&e.value.toLowerCase()===p&&(t.advance(),t.advance(),s=p)}else if(t.check(p)){t.advance();const e=t.peek();ze(e)?(s=e.value,t.advance()):s=p}const a=t.parseCommandListUntilEnd("for");n.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return n.push(pn(r,c)),n.push(i),s&&n.push(pn(s,c)),n.push(mn(a,{...c,end:c.end||0})),On.from({...e,value:"repeat"}).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const n=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!kn(t)){const r=t.parseExpression();return n.push(r),On.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{if(t.checkTimeExpression()||t.checkLiteral()||t.check("(")){if(r.push({kind:"duration",expr:t.parseExpression()}),t.check("or")){t.advance();continue}break}const e=t.peek();if(!ze(e))throw Error('Expected event name or duration after "for"');const n=e.value;t.advance();const i=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!ze(e))break;i.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({kind:"event",name:n,params:i}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let i=null;t.check(b)&&(t.advance(),Cn(t,T),i=t.parsePrimary());const o={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(gn(r.map(t=>yn("duration"===t.kind?[{key:dn("duration",o),value:t.expr}]:[{key:dn("name",o),value:fn(t.name,`"${t.name}"`,o)},{key:dn("args",o),value:gn(t.params.map(t=>fn(t,`"${t}"`,o)),o)}],o)),o)),i&&n.push(i)}return On.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const n=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=t.advance().value,i=t.previous();if(n.push(dn(r,{start:i.start,end:i.end,line:i.line,column:i.column})),t.check("(")){t.advance();const r=[];for(;!t.isAtEnd()&&!t.check(")");)if(r.push($n(t)),t.check(","))t.advance();else if(!t.check(")"))break;if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),r.length>0){const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(yn(r.map(t=>({key:t.name?dn(t.name,i):fn("_positional","_positional",i),value:t.value})),i))}}return On.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let i=null,o=null;const s=t.peek();if(t.checkAnySelector()||t.checkContextVar()||t.check("<")||ze(s)&&qn.has(s.value)){const e=t.parsePrimary();("possessiveExpression"===e.type||"memberExpression"===e.type&&!e.computed)&&e.object&&e.property?.name?(o=e.object,i={type:"string",value:e.property.name,start:s.start||0,end:t.getPosition().end,line:s.line,column:s.column}):(o=e,t.check("'s")&&t.advance())}const a=t.peek();if(!i&&(ze(a)||"*"===a.value)){let e="";t.check("*")&&(e="*",t.advance());const n=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);n&&(e+=n,i={type:"string",value:e,start:a.start||0,end:t.getPosition().end,line:a.line,column:a.column})}if(!i)throw Error("Transition command requires a CSS property");if(o&&n.push(o),n.push(i),!t.check(g))throw Error('Expected "to" keyword after property in transition command');t.advance();const c=t.parsePrimary();if(r.to=c,t.check("over")){t.advance();const e=t.parsePrimary();r.over=e}if(t.check(v)){t.advance();const e=t.parsePrimary();r.with=e}return On.from(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const n=[];if(t.match("{"))n.push(t.parseCSSObjectLiteral());else{const e=Sn(t,[g]);e&&n.push(e)}if(t.check(g)){t.advance();const e=Sn(t);e&&n.push(e)}return On.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Mn(this.getContext(),t)}parseRemoveCommand(t){return Bn(this.getContext(),t)}parseToggleCommand(t){return Dn(this.getContext(),t)}parseRegularCommand(t){return Jn(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),!1);n.optional=!0,t=n}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,!0)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):Ge(this.peek())&&this.peek().value.startsWith("@")?e=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),e=this.advance().value,this.consume("]","Expected ']' after attribute reference")):e=this.consumeIdentifierLike("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&ze(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),n=this.processEscapeSequences(e);return this.createLiteral(n,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=!0;break;case"false":e=!1;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value,e=t.slice(1,-2).trim(),n=this.createSelector(e);return n.fromQuery=!0,n.raw=t,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Qe)||this.matchPredicate(Ve)||this.matchPredicate(Ue)||this.matchPredicate(De)||this.matchPredicate(Fe))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(t.value):this.parseNavigationFunction(t.value)}const e=this.check(".")||this.check("?.");return"my"!==t.value||e?"its"!==t.value||e?"your"!==t.value||e?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Ge(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const t=this.peek().start;this.advance();const e=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}e.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:e,body:this.parseExpression(),start:t,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.check("["))this.advance(),e=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,t)}else{if(!this.check("-")&&!this.checkPredicate(Qe))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=!1;for(;this.check("-");)this.advance(),t+="-",n=!0;for(this.checkPredicate(Qe)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=!0,this.checkPredicate(Qe)&&(t+=this.advance().value);if(""===t||"-"===t)return this.addError("Expected property name in object literal"),this.createErrorNode();e=n?this.createLiteral(t,t):this.createIdentifier(t)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(t.push({key:e,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Qe))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);n=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,o=0,s=-1,a=-1;for(;!this.isAtEnd()&&(0!==o||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),0>s&&"number"==typeof t.start&&(s=t.start),"number"==typeof t.end&&(a=t.end),"$"===t.value&&this.check("{")&&(i=!0),"{"===t.value&&o++,"}"===t.value&&o--}const c=this.originalInput&&s>=0&&a>s?this.originalInput.slice(s,a):r.join(""),l=i?{type:"templateLiteral",value:c,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(c,c);if(e.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),n=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column},arguments:r,isConstructor:!0,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:i,errorHandler:o,finallyHandler:s}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==o&&{errorHandler:o},...void 0!==s&&{finallyHandler:s},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseErrorAndFinallyBlocks(){let t,e,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(t=this.advance().value),e=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==t&&{errorSymbol:t},...void 0!==e&&{errorHandler:e},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let n=e.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,n,r,i){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==i.start&&{start:i.start},...void 0!==i.end&&{end:i.end},...void 0!==i.line&&{line:i.line},...void 0!==i.column&&{column:i.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(er.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Qe(r)&&!this.isCommand(r.value)||Ue(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!1};let i,o;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),er.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{o=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,t,i,o,e),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(Ie("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return Ie("\u26a0\ufe0f Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseTemporalKeywordModifiers(t){if(!this.check("debounced")&&!this.check("throttled"))return;const e=this.advance().value.toLowerCase(),n="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const i=this.advance(),o=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);t[n]=o,Ie(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${i.value}' (${o}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,Ie(`\ud83d\udd27 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 r}parseEventHandler(){Ie("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const t=this.tokens[this.current+1],n=t?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),e=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),Ie("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),Ie("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),Ie("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(Ie("\ud83d\udd27 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,Ie(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const i=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();i.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),Ie("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const o={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)o.once=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)o.prevent=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)o.stop=!0,Ie("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),n=parseInt(e.value,10);if(isNaN(n))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(o.debounce=n,Ie(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(o.throttle=n,Ie(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else Ie(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let s,a,c,l;if(this.parseTemporalKeywordModifiers(o),e&&(o.once=!0),Object.keys(o).length>0&&Ie("\ud83d\udd27 parseEventHandler: Parsed modifiers:",o),this.match("[")&&(s=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,Ie(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`),this.parseTemporalKeywordModifiers(o)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,Ie("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(Ie("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),Ie("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(Ie(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(Ie(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){Ie("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())Ie("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){Ie("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){Ie(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const n=this.parseCommand();u.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),Ie("\u2705 parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){Ie("\u26a0\ufe0f Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const n={type:"command",name:e.left.name,args:[e.right],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}};u.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}let f,d,h;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:f,errorHandler:d,finallyHandler:h}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const m=this.getPosition(),p={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...void 0!==f&&{errorSymbol:f},...void 0!==d&&{errorHandler:d},...void 0!==h&&{finallyHandler:h},...i.length>0&&{args:i},...s&&{condition:s},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(o).length>0&&{modifiers:o},start:m.start,end:m.end,line:m.line,column:m.column};return Ie(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),p}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let o;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Qe(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let o;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),o=e.value,this.advance())}}const{commands:s,terminator:a}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const f={type:"eventHandler",event:e,commands:s,...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:l},...void 0!==u&&{finallyHandler:u},...void 0!==o&&{target:o},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};i.push(f)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}o={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:n,eventHandlers:i,...void 0!==o?{initBlock:o}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,n=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(Ie("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)Ie("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){Ie('\u2705 parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),n=this.getPosition(),r="Expected command, got: "+e.value;this.addError(r);const i=vn(n,r,e.value);if(t.push(i),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return wn.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return En(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const i=[],o={};for(;!kn(t,["catch","finally",...r.keywords])&&!En(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(i.push(e),!t.match(",")&&En(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&En(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(o[e]=n),!En(t.peek(),r.keywords))break}const s=On.from(e).withArgs(...i).endingAt(t.getPosition());return Object.keys(o).length>0&&s.withModifiers(o),s.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();if(e.push(t),this.match("then","and",","))continue}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(Ie(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(Ie(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return Ie("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),n=e.value.toLowerCase();if(t.includes(n))break;if(De(e))break;this.advance()}}parseCommand(){const t=this.parseCommandCore();if(t&&"command"===t.type&&!t.body&&(this.check("when")||this.check("where"))){const e=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(t.modifiers={...t.modifiers??{},[e]:n})}return t}parseCommandCore(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","prepend","toggle","take","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch","process"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const n={};let r=null;if(!t.isAtEnd()&&Kn(t)&&(r=Gn(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),On.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(n.with=t.parsePrimary());for(let e=0;3>e&&!t.isAtEnd();e++)if(!t.check("as")||n.as){if(!t.check("with")||n.with){if(t.check("do")&&!n.doNotThrow){const e=t.peekAt(1),r=t.peekAt(2);if("not"===e?.value&&"throw"===r?.value){const e=t.advance();t.advance();const r=t.advance();n.doNotThrow={type:"literal",value:!0,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Yn(t)?Qn(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||Cn(t,"a")||Cn(t,"an"),n.as=t.parsePrimary();const i=On.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}(this.getContext(),t);const n=this.parseMultiWordCommand(t,e);if(n)return n;const r=e.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(t);if("for"===r)return this.parseForCommand(t);if("if"===r||"unless"===r)return this.parseIfCommand(t);if("wait"===r)return this.parseWaitCommand(t);if("install"===r)return this.parseInstallCommand(t);if("transition"===r)return this.parseTransitionCommand(t);if("add"===r)return this.parseAddCommand(t);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||function(t,e){return{type:"command",name:t,args:[],partial:!0,start:e.start,end:e.end,line:e.line,column:e.column}}(r,this.getPosition());const i=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let i=!1;t.check(S)&&(i=!0,t.advance());const o=t.parseExpression();if(!o)throw Error("Expected variable or expression after "+n);let s;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${n} command`);s=e}else s=fn(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=o;i&&"identifier"===o.type&&(a={...o,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=hn(r,o,s,c);l.coerceNumeric=!0;const u=[a,dn(g,c),l];return On.from(e).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(i.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const o=this.getPosition();return{type:"command",name:e,args:i,isBlocking:!1,start:o.start,end:o.end,line:o.line,column:o.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}const n=this.createCallExpression(this.createIdentifier(t),e);if("next"===t||"previous"===t){const t=this.parseRelativePositionalModifiers();t&&(n.relativePositional=t)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let t,e,n,r=!1,i=!1;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=!0),{from:t,within:e,inElt:n,inSearch:r,wrapping:i}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parseCall(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),!1);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const n="*"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(t),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Ge(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}const e=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;P(e)&&Ie(`\ud83d\udca1 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return fn(t,e,this.getPosition())}createIdentifier(t){return dn(t,this.getPosition())}createBinaryExpression(t,e,n){return hn(t,e,n,this.getPosition())}createUnaryExpression(t,e,n){return function(t,e,n,r){return{type:"unaryExpression",operator:t,argument:e,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createCallExpression(t,e){return function(t,e,n){return{type:"callExpression",callee:t,arguments:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createMemberExpression(t,e,n){return function(t,e,n,r){return{type:"memberExpression",object:t,property:e,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,n){return{type:"possessiveExpression",object:t,property:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(Ie(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return Ie("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return Ie(`\u2705 createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return Ie(`\u2705 createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),!0;return!1}matchOperator(t){if(this.isAtEnd())return!1;const e=this.peek();return!(!ln(e)||e.value!==t||(this.advance(),0))}check(t){if(this.isAtEnd())return!1;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return!this.isAtEnd()&&t(this.peek())}matchPredicate(t){return!!this.checkPredicate(t)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Ze)}matchSelector(){return this.matchPredicate(Ze)}checkAnySelector(){return this.checkPredicate(We)}checkLiteral(){return this.checkPredicate(Je)}checkIdentifierLike(){return this.checkPredicate(ze)}checkIsCommand(){return this.checkPredicate(De)}checkCommandTerminator(){return this.checkPredicate(un)}checkReference(){return this.checkPredicate(Ke)}checkTimeExpression(){return this.checkPredicate(Xe)}checkEvent(){return this.checkPredicate(Fe)}checkContextVar(){return this.checkPredicate(Ue)}checkComment(){return this.checkPredicate(Ye)}checkIdentifier(){return this.checkPredicate(Qe)}checkKeyword(){return this.checkPredicate(Ve)}checkString(){return this.checkPredicate(tn)}matchString(){return this.matchPredicate(tn)}checkNumber(){return this.checkPredicate(en)}matchNumber(){return this.matchPredicate(en)}checkBoolean(){return this.checkPredicate(nn)}matchBoolean(){return this.matchPredicate(nn)}checkTemplateLiteral(){return this.checkPredicate(rn)}matchTemplateLiteral(){return this.matchPredicate(rn)}checkQueryReference(){return this.checkPredicate(on)}matchQueryReference(){return this.matchPredicate(on)}checkIdSelector(){return this.checkPredicate(sn)}checkClassSelector(){return this.checkPredicate(an)}checkCssSelector(){return this.checkPredicate(cn)}checkBasicOperator(){return this.checkPredicate(ln)}matchBasicOperator(){return this.matchPredicate(ln)}matchTimeExpression(){return this.matchPredicate(Xe)}matchIdentifierLike(){return this.matchPredicate(ze)}matchComparisonOperator(){return this.matchPredicate(_e)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Qe,t)}consumeIdentifierLike(t){return this.consumePredicate(ze,t)}consumeEvent(t){return this.consumePredicate(Fe,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(t){const e=this.current+t;return e>=0&&this.tokens.length>e?this.tokens[e]:null}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let n=e.start||0,r=e.line||1,i=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1,0===n&&this.current>0&&(n=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;n=t.start||0,r=t.line||1,i=t.column||1,0===n&&(n=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const n=this.tokens[e];if(n&&("+"===n.value||"-"===n.value)){t=n;break}}n=t.start||0,r=t.line||1,i=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;Ie("\u26a0\ufe0f synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();r.push(t.value)}this.consume("]","Expected ']' after attribute literal");const i=r.join("");if(!i.includes("="))return{type:"attributeAccess",attributeName:i.replace(/^@/,""),start:t,end:this.previous().end,line:e,column:n};const o="["+i+"]";return{type:"literal",value:o,raw:o,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),i=this.tokens[this.current],o=this.tokens[this.current+1];if("identifier"===i?.kind&&("]"===o?.value||o&&r.has(o.value)&&"string"===this.tokens[this.current+2]?.kind)){let t="["+this.advance().value;if(this.check("]"))this.advance(),t+="]";else{const e=this.advance().value,n=this.advance().value;t+=e+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),t+="]"}return this.createSelector(t)}const s=[];if(!this.check("]"))do{if(this.check("]"))break;s.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:s,start:t,end:this.previous().end,line:e,column:n}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),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:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>t.peekAt(e),getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:!0,configurable:!0}),e}}function nr(t,e){const n=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const n=t.length;for(;n>e.position&&(le(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==ae(e,1))if('"'!==n){if("'"===n||"'"===n){const t=ae(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==ie.IDENTIFIER&&n.kind!==ie.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)he(e);else{const t=e.position;ce(e),ce(e),ue(e,ie.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===ae(e,1)){const t=e.position;ce(e),ce(e),ue(e,ie.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=t&&t.kind===ie.IDENTIFIER&&C.has(t.value.toLowerCase()),i=t&&t.kind===ie.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===ie.OPERATOR&&")"!==t.value&&"]"!==t.value||r||i||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(xe(ae(e))||"{"===ae(e)||"-"===ae(e))){pe(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===ie.IDENTIFIER&&V.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==ie.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(ce(e),ue(e,ie.SYMBOL,"[")):(ce(e),ue(e,ie.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const t=ae(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){Ee(e);continue}}Ae(n)?be(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(ue(e,ie.UNKNOWN,n),ce(e)):we(e):ve(e)}else ce(e),ue(e,ie.OPERATOR,"]")}else ce(e),ue(e,ie.OPERATOR,"}");else ce(e),ue(e,ie.OPERATOR,"{");else ge(e)}else pe(e);else Te(e)?ye(e):be(e);else me(e)}else he(e);else de(e)}return e.tokens}(t);return new er(n,e,t).parse()}function rr(t,e){const n=t.registry?.get(e);if(!n)throw Error(`Expression '${e}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function ir(t){if(t&&"object"==typeof t&&"success"in t){if(t.success)return"value"in t?t.value:void 0;const e=t.errors||[];throw Error(e.length>0?e[0].message:"Expression evaluation failed")}return t}async function or(t,e){if(!t)throw Error("Cannot evaluate null or undefined AST node");if("literal"===t.type)return t.value;if("identifier"===t.type)return dr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return dr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,i=t.left;if("="===n){const n=await or(t.right,e);if("identifier"===i?.type&&"string"==typeof i.name){const t=i.name;return t.startsWith("$")?ct(e,t.slice(1),n):"global"===i.scope?ct(e,t,n):"element"===i.scope?mt(e,t,n):(e.locals||(e.locals=new Map),e.locals.set(t,n)),n}throw Error(`Assignment target must be a variable identifier (got '${i?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await or(t.left,e);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===i?.type&&"identifier"===i.callee?.type?i.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(i.arguments)){const r=i.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const i=await or(t.right,e);if(i&&"function"==typeof i.querySelectorAll){const t=Array.from(i.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===i?.type&&i.fromQuery&&"string"==typeof i.value){const n=await or(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(i.value))}}if("of"===n&&"selector"===i?.type&&"string"==typeof i.value&&/^\*[a-zA-Z][\w-]*$/.test(i.value)){const n=await or(t.right,e);return rr(e,"styleRef").evaluate(e,i.value.slice(1),n)}if("of"===n){const n=hr(t.left);if(n){const r=await or(t.right,e);let i=r;for(const t of n){if(null==i)return;i=Lt(i)?Ht(i,t):i[t]}return"function"==typeof i?i.bind(r):i}}const o=await or(t.left,e);if("and"===n){if(!o)return o;const n=await or(t.right,e);return rr(e,"and").evaluate(e,o,n)}if("or"===n){if(o)return o;const n=await or(t.right,e);return rr(e,"or").evaluate(e,o,n)}const s=await or(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(o):o,l=t.ignoringCase?a(s):s;switch(n){case"+":{let n=o,r=s;return t.coerceNumeric&&("string"==typeof n&&(n=vt(n)),"string"==typeof r&&(r=vt(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:ir(await rr(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return ir(await rr(e,"subtraction").evaluate(e,{left:o,right:s}));case"*":return ir(await rr(e,"multiplication").evaluate(e,{left:o,right:s}));case"/":return ir(await rr(e,"division").evaluate(e,{left:o,right:s}));case"%":case"mod":return ir(await rr(e,"modulo").evaluate(e,{left:o,right:s}));case"^":case"**":return ir(await rr(e,"power").evaluate(e,{left:o,right:s}));case">":case"is greater than":return rr(e,"greaterThan").evaluate(e,o,s);case"<":case"is less than":return rr(e,"lessThan").evaluate(e,o,s);case">=":case"is greater than or equal to":return rr(e,"greaterThanOrEqual").evaluate(e,o,s);case"<=":case"is less than or equal to":return rr(e,"lessThanOrEqual").evaluate(e,o,s);case"==":return rr(e,"equals").evaluate(e,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=yr(t,o,s);return void 0!==n?n:rr(e,"equals").evaluate(e,c,l)}case"!=":return rr(e,"notEquals").evaluate(e,c,l);case"is not":case"is not equal":case"is not equal to":{const n=yr(t,o,s);return void 0!==n?!n:rr(e,"notEquals").evaluate(e,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return rr(e,"strictEquals").evaluate(e,c,l);case"!==":case"is not really":case"is not really equal to":return rr(e,"strictNotEquals").evaluate(e,c,l);case"as":return rr(e,"as").evaluate(e,o,br(s));case"contains":case"contain":case"includes":case"include":return rr(e,"contains").evaluate(e,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return rr(e,"doesNotContain").evaluate(e,c,l);case"starts with":return rr(e,"startsWith").evaluate(e,c,l);case"ends with":return rr(e,"endsWith").evaluate(e,c,l);case"does not start with":return!await rr(e,"startsWith").evaluate(e,c,l);case"does not end with":return!await rr(e,"endsWith").evaluate(e,c,l);case"match":case"matches":return rr(e,"matches").evaluate(e,c,pr(t.right,l));case"does not match":case"do not match":return!await rr(e,"matches").evaluate(e,c,pr(t.right,l));case"in":case"is in":case"am in":return mr(o,s);case"is not in":case"am not in":return!mr(o,s);case"of":return s&&"object"==typeof s?s[o]:void 0;case"precedes":return gr(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!gr(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return gr(o,s,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!gr(o,s,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await or(t.expression,e),r=br(t.targetType);return rr(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await or(t.value,e),r=await or(t.min,e),i=await or(t.max,e),o=t=>"string"==typeof t?t.toLowerCase():t,[s,a,c]=t.ignoringCase?[o(n),o(r),o(i)]:[n,r,i],l=await rr(e,"between").evaluate(e,s,a,c);return t.negated?!l:l}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return!0;if(Object.prototype.toString.call(t).slice(8,-1)===e)return!0;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await or(t.value,e),t.typeName+"",!1!==t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await or(t.collection,e);if(null==n)return n;const r=async(t,n)=>or(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=re(t),i=[];for(const t of r)await n(e,t)&&i.push(t);return i}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const i=[...re(t)],o=await Promise.all(i.map(t=>r(e,t))),s=i.map((t,e)=>e);s.sort((t,e)=>{const n=o[t],r=o[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=s.map(t=>i[t]);return"desc"===n?a.reverse():a}(n,t.right,t.order??"asc",r);case"mapped to":return async function(t,e,n){const r=re(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return o=await or(t.right,e),null==(i=n)?[]:(i+"").split(null==o?"":o+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return re(t).map(t=>null==t?"":t+"").join(n)}(n,await or(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var i,o}(n,e);case"unaryExpression":return async function(t,e){const n=t.operand??t.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${t.operator})`);const r=await or(n,e);switch(t.operator){case"not":case"!":return rr(e,"not").evaluate(e,r);case"no":return rr(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return rr(e,"exists").evaluate(e,r);case"does not exist":return rr(e,"doesNotExist").evaluate(e,r);case"is empty":return rr(e,"isEmpty").evaluate(e,r);case"is not empty":return rr(e,"isNotEmpty").evaluate(e,r);default:throw Error("Unknown unary operator: "+t.operator)}}(n,e);case"memberExpression":return async function(t,e){const n=await or(t.object,e);if(t.computed){const r=await or(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return xr(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await or(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await xr(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await or(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>or(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,i=await async function(t,e,n){return kr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:or(t,n))):Promise.all(t.map(t=>or(t,n)))}(t.arguments,r,e);switch(r){case"closest":return rr(e,"closest").evaluate(e,...i);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?Sr(await or(n.from,e)):e.me,o=n.within?Sr(await or(n.within,e)):void 0,s=n.inElt?await or(n.inElt,e):void 0;return rr(e,r).evaluate(e,i[0],t,{within:o,inElt:s,inSearch:n.inSearch,wrapping:n.wrapping})}return rr(e,r).evaluate(e,...i)}case"first":return rr(e,"first").evaluate(e,...i);case"last":return rr(e,"last").evaluate(e,...i);default:if("function"==typeof n)return n(...i);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>or(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const i=await or(t.callee.object,e);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){let n=t.value;if("string"==typeof n&&!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return rr(e,"styleRef").evaluate(e,n.slice(1));if("string"==typeof n&&t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=await async function(t,e){const n=Or(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>lr(t.expr,e)));return jr(n,r)}(n,e),o=Cr(t,r);i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await rr(e,"elementWithSelector").evaluate(e,o)}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!t.fromQuery&&n.includes("{")&&(n=await function(t,e){return Er(t,/\{([^}]*)\}/g,async(t,n)=>(await lr(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Cr(t,n):n;return kt(await rr(e,"elementWithSelector").evaluate(e,r),n,t.fromQuery)}(n,e);case"contextReference":return async function(t,e){switch(t.contextType){case"me":case"you":case"it":return rr(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return rr(e,"me").evaluate(e);case"your":case"yourself":return rr(e,"you").evaluate(e);case"its":return rr(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??rr(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return rr(e,"document").evaluate(e);case"window":return rr(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await or(t.object,e),r=t.property.name;return rr(e,"possessive").evaluate(e,n,r)}(n,e);case"eventHandler":return async function(t,e){return{event:t.event,selector:t.selector,commands:t.commands,handler:async n=>{const r={...e,event:n,target:n.target,currentTarget:n.currentTarget};for(const e of t.commands)await or(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await or(t.test,e)?or(t.consequent,e):t.alternate?or(t.alternate,e):void 0}(n,e);case"string":return n.value;case"arrayLiteral":return async function(t,e){const n=[];for(const r of t.elements)n.push(await or(r,e));return n}(n,e);case"objectLiteral":return async function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await or(t,e)+"",n[i]=await or(r.value,e)}return n}(n,e);case"attributeAccess":return async function(t,e){const n=t.attributeName;return e.me&&e.me instanceof Element?e.me.getAttribute(n):"@"+n}(n,e);case"propertyOfExpression":return async function(t,e){const n=t.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await or(t.target,e);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return rr(e,"possessive").evaluate(e,i,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await Er(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(t,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const t=n.split(".");let r=wr(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(wr(n,e)??"")+""}catch{return""}}),n=await Er(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const i=n||r;try{return await lr(i,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await or(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return vr(n,e);default:{const n=G.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}er.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),er.PRATT_TABLE=K,er.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class sr extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function ar(t,e){const n=t;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(t,e){const n=t.value;if("string"!=typeof n)throw new sr("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new sr("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(t,e){const n=Or(t),r=n.filter(t=>"expr"in t).map(t=>cr(t.expr,e));return jr(n,r)}(n,e),o=Cr(t,r),s=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new sr("selector");i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return Array.from(s.querySelectorAll(o))}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}const r=!t.fromQuery&&n.includes("{")?function(t,e){return t.replace(/\{([^}]*)\}/g,(t,n)=>(cr(n.trim(),e)??"")+"")}(n,e):n,i=Cr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new sr("selector");return kt(Array.from(o.querySelectorAll(i)),r,t.fromQuery)}(n,e);case"identifier":return function(t,e,n){return"me"===t||"my"===t||"I"===t?e.me:"you"===t||"your"===t||"yourself"===t?e.you:"it"===t||"its"===t?e.it??e.result:"result"===t?e.result??e.it:"window"===t?"undefined"!=typeof window?window:globalThis:"document"===t?"undefined"!=typeof document?document:void 0:"element"===n?ht(e,t):e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):t.startsWith("$")&&e.globals?.has(t.slice(1))?e.globals.get(t.slice(1)):void 0!==e[t]?e[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}(n.name,e,n.scope);case"contextReference":return function(t,e){switch(t){case"me":return e.me;case"you":return e.you;case"it":return e.it??e.result;case"event":return e.event;case"target":return e.target??e.event?.target??e.me;default:throw new sr("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>ar(t,e));case"objectLiteral":return function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:ar(t,e)+"",n[i]=ar(r.value,e)}return n}(n,e);case"asExpression":return Gt(ar(n.expression,e),br(n.targetType),e);case"stringPostfix":return`${ar(n.expression,e)}${n.unit}`;case"blockLiteral":return vr(n,e);case"memberExpression":{const t=ar(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new sr("memberExpression");const r=t[n.computed?ar(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new sr(n?.type??"unknown")}}function cr(t,e){const n=nr(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return ar(n.node,e)}async function lr(t,e){const n=nr(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}const r=e.registry?e:{...e,registry:await fr()};return or(n.node,r)}let ur=null;async function fr(){if(!ur){const t=await Promise.resolve().then(function(){return ho});ur=t.createFullExpressionRegistry()}return ur}async function dr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?rr(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?rr(e,"you").evaluate(e):"it"===n||"its"===n?rr(e,"it").evaluate(e):"result"===n?rr(e,"result").evaluate(e):"window"===n?rr(e,"window").evaluate(e):"document"===n?rr(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?(ot(n,e),e.globals.get(n)):"element"===t.scope?ht(e,n):e.locals&&e.locals.has(n)?(at(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&ot(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?(ot(n.slice(1),e),e.globals.get(n.slice(1))):void 0!==e[n]?e[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function hr(t){const e=t;if(!e)return null;if("identifier"===e.type&&"string"==typeof e.name)return[e.name];if("memberExpression"===e.type&&!e.computed){const t=hr(e.object);if(!t)return null;const n=e.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...t,r]}return null}function mr(t,e){return Array.isArray(e)?e.includes(t):"string"==typeof e?e.includes(t+""):t instanceof Node&&e instanceof Node?t===e||e.contains(t):null!=e&&"object"==typeof e&&t in e}function pr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function yr(t,e,n){if(void 0!==n)return;const r=t.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==e||"object"!=typeof e)return;const i=e[r.name];return"boolean"==typeof i?!0===i:void 0}function gr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function br(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t+""}function vr(t,e){const n=t.parameters??[];return(...r)=>{const i=new Map(e.locals??new Map);n.forEach((t,e)=>i.set(t,r[e]));const o={...e,locals:i};try{return ar(t.body,o)}catch(e){if(e instanceof sr)return or(t.body,o);throw e}}}function wr(t,e){if(e.locals?.has(t))return at(t,e),e.locals.get(t);if("me"===t&&e.me)return e.me;if("you"===t&&e.you)return e.you;if("it"===t){const t=e.it??e.result;if(t)return t}if("result"===t){const t=e.result??e.it;if(t)return t}return"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function Er(t,e,n){const r=[];let i;for(;null!==(i=e.exec(t));)r.push({index:i.index,length:i[0].length,replacement:await n(i[0],...i.slice(1))});let o=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:i}=r[t];o=o.substring(0,e)+i+o.substring(e+n)}return o}function xr(t,e,n){if("string"==typeof e&&e.startsWith("@")){const n=e.substring(1);return t&&"function"==typeof t.getAttribute?t.getAttribute(n):void 0}return t instanceof Element&&"string"==typeof e?Ht(t,e):ee(t)&&!(e in t)?rr(n,"possessive").evaluate(n,t,e):t?.[e]}const kr=new Set(["closest","previous","next"]);function Sr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const Tr=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"),Ar=/[:&()[\]/]/g;function Cr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(Tr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(Ar,"\\$&")}(e)}const $r=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Or(t){const e=[];let n,r=0;for($r.lastIndex=0;null!==(n=$r.exec(t));)n.index>r&&e.push({lit:t.slice(r,n.index)}),e.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return t.length>r&&e.push({lit:t.slice(r)}),e}function jr(t,e){let n="";const r=[];let i=0;for(const o of t){if("lit"in o){n+=o.lit;continue}const t=e[i++];Lt(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class Nr{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??!1}registerListener(t,e,n,r,i){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,i),this.debugMode&&Me(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&Me("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&Me("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&Me("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,n){this.addCleanup(t,{type:"custom",cleanup:e,description:n||"Custom cleanup"})}registerGlobal(t,e="custom",n){this.globalCleanups.push({type:e,cleanup:t,description:n||"Global cleanup"}),this.debugMode&&Me("CleanupRegistry: Registered global cleanup: "+(n||e))}addCleanup(t,e){const n=this.elementCleanups.get(t);n?n.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&Me(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let n=0;for(const t of e){try{t.cleanup(),n++}catch(t){this.debugMode&&Me("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&Me(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(t){let e=this.cleanupElement(t);const n=t.querySelectorAll("*");for(const t of n)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&Me("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&Me(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,n=0,r=0,i=0;for(const o of this.globalCleanups)switch(o.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}class Rr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&Me("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(n,e)}unregister(t){const e=t.toLowerCase(),n=this.sources.get(e);if(n){for(const[t,n]of this.subscriptions.entries())n.source===e&&(n.unsubscribe(),this.subscriptions.delete(t));return n.destroy?.(),this.sources.delete(e)}return!1}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,n){const r=this.get(t);if(!r)return void Me("[EventSourceRegistry] Unknown event source: "+t);r.initialize?.();const i=r.subscribe(e,n);return this.subscriptions.set(i.id,i),i}unsubscribe(t){const e=this.subscriptions.get(t);return!!e&&(e.unsubscribe(),this.subscriptions.delete(t))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,n]of this.sources.entries())if(n.supports?.(t)??n.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Lr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,n){const r=t.toLowerCase();this.providers.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:e)}registerGlobal(t,e,n){const r=t.toLowerCase();this.globalProviders.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const o=await r.provide(e);return r.cache&&n&&n.set(i,o),o}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);const o=r.provide(e);if(o instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,o),o}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,i){if("string"==typeof r&&e.get(r))try{return e.resolveSync(r,t,n)}catch{return e.resolve(r,t,n)}return Reflect.get(t,r,i)},has:(t,n)=>!("string"!=typeof n||!e.has(n))||Reflect.has(t,n)})}async resolveAll(t){const e=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,o]of r)try{n[i]=await this.resolve(i,t,e)}catch(t){Me(`[ContextProviderRegistry] Failed to resolve '${i}':`,t),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Ir={evaluate:(t,e)=>or(t,e)};class Mr{static toTyped(t){return{me:t.me,...void 0!==t.owner&&{owner:t.owner},it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},...void 0!==t.registry&&{registry:t.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Pr{constructor(t,e,n){this.impl=t,this.hookRegistry=n??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,n={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:n,event:t.event??void 0,executionContext:t}}get name(){const t=this.impl.name;if(t)return t;const e=this.impl.metadata?.name;return"string"==typeof e?e:""}get metadata(){const t=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:"string"==typeof t?t:t?t.join(" | "):""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(Re(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void Re(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Mr.toTyped(t);let o,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(Re(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const e=n.modifiers,r=e?.when||e?.where;if(r&&!await or(r,t))return void Re(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);o=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},Ir,t)}else o=e;else Re(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),o=e;if(Re("CommandAdapterV2: Calling execute with parsed input:",o),2===this.impl.execute.length)s=await this.impl.execute(o,i);else{const t=Array.isArray(o)?o:[o];s=await this.impl.execute(i,...t)}return Re("CommandAdapterV2: Command result:",s),Object.assign(t,Mr.fromTyped(i,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,s),s}catch(t){if(Fr(t)||Re(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return{isValid:!this.impl.validate||this.impl.validate(t),errors:[],suggestions:[]}}}class qr{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);Me(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=e.toLowerCase();Me(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Pr(t,void 0,this.hookRegistry);this.adapters.set(n,r),C.add(n);const i=t.metadata?.aliases;if(i&&Array.isArray(i))for(const e of i){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),C.add(n)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const n=this.getAdapter(t);return n?n.validate(e):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Hr=null;function Br(){return Hr||(Hr=function(t){const e=t?.commands??new qr,n=t?.eventSources??new Rr,r=t?.context??new Lr,i=new Set,o={commands:e,eventSources:n,context:r,use(t){if(i.has(t.name))Me(`[LokaScriptRegistry] Plugin '${t.name}' is already installed`);else{if(t.commands)for(const n of t.commands)e.register(n);if(t.eventSources)for(const e of t.eventSources)n.register(e.name,e);if(t.contextProviders)for(const{name:e,provide:n,options:i}of t.contextProviders)r.register(e,n,i);t.setup?.(o),i.add(t.name)}},reset(){i.clear()}};return o}()),Hr}class Dr{constructor(t={}){this.contextCache=new WeakMap;const e=Br();this.options={enableContextProviders:t.enableContextProviders??!0,enableEventSources:t.enableEventSources??!0,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,Me(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),Me(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return Me("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return Me(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return Me(`[RegistryIntegration] Found event source '${n}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(t,e,n);if(!r)throw Error(`Failed to subscribe to event source '${t}'`);return Me(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,Me("[RegistryIntegration] Destroyed")}}function Vr(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=!0,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Fr(t){return t instanceof Error&&(null!==n(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function Ur(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const _r=new WeakMap;function zr(t,e=new Set){if(null===t||"object"!=typeof t)return e;if(Array.isArray(t)){for(const n of t)zr(n,e);return e}const n=t;"identifier"===n.type&&"string"==typeof n.name&&e.add(n.name);for(const t of Object.keys(n))"start"!==t&&"end"!==t&&"line"!==t&&"column"!==t&&zr(n[t],e);return e}class Wr{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...t},this.registry=t.registry,this.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=lt,this.hookRegistry=new e,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Nr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new Dr("object"==typeof t.registryIntegration?t.registryIntegration:{}),Me("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,n)=>await this.installBehaviorOnElement(t,e,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const n of t)for(const t of n.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&Me(`RuntimeBase: Auto-cleaned ${e} 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(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}trackListener(t,e,n,r,i){this.cleanupRegistry.registerListener(t,e,n,r,i)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...t){this.options.enableErrorReporting&&console.error(...t)}logWarn(...t){this.options.enableErrorReporting&&console.warn(...t)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),Me("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){Me(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,n)=>this.execute(t,n||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return Me("\u26a0\ufe0f RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(t,e);if(!o(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw Vr(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const r=n(t);if(r?.isReturn){const t=r.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw t}case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(n,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"def":return this.installFunction(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=t,r=await this.executeCommandSequenceWithResult(n.commands||[],e);if(!o(r))throw Vr(r.error);return r.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(t,e);if(!o(n))throw Vr(n.error);return n.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:n,args:r,modifiers:i}=t,o=n.toLowerCase();if(Re(`RUNTIME BASE: Processing command '${o}'`),this.registry.has(o)){const t=await this.registry.getAdapter(o);if(!t)throw Error(`Command '${o}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:i||{},commandName:o,runtime:this})}catch(t){throw Fr(t)||this.logError(`Error executing command '${o}':`,t),t}}const s=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(s),Error(s)}toSignal(t){const e=n(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:n,args:o,modifiers:s}=t,a=n.toLowerCase();if(Re(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const t=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(t),Error(t)}const c=await this.registry.getAdapter(a);if(!c)throw Error(`Command '${a}' is registered but failed to load adapter.`);try{return r(await c.execute(e,{args:o||[],modifiers:s||{},commandName:a,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return i(e);throw this.logError(`Error executing command '${a}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const i of t){if(this.hasErrorDiagnostics(i)){const t=i.diagnostics?.[0];Me("\u26a0\ufe0f RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===i.type){const t=await this.processCommandWithResult(i,e);if(!o(t)){const n=t.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==n.returnValue&&Object.assign(e,{it:n.returnValue,result:n.returnValue}),r(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(i,e);if(!o(t))return t;n=t.value}}return r(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await or(t,n);return Ur(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},s=await async function(t,e){try{return r(await or(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return i({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return i({type:"exit",returnValue:e.returnValue});if(e.isBreak)return i({type:"break"});if(e.isContinue)return i({type:"continue"});if(e.isReturn)return i({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!o(s))return s;const a=s.value;if(Ur(a)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:a.command,args:[{type:"literal",value:a.selector}]},e);try{return r(await this.executeCommandFromPattern(a.command,a.selector,e))}catch(t){const e=this.toSignal(t);if(e)return i(e);throw t}}return r(a)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}installFunction(t,e){const r=this,i=t.params??[],s=t.body??[],a=t.errorHandler,c=t.finallyHandler,l=t.errorSymbol;e.globals.set(t.name,async(...t)=>{const u={...e,locals:new Map(e.locals)};i.forEach((e,n)=>{e&&u.locals.set(e,t[n])});const f=async t=>{const e=await r.executeCommandSequenceWithResult(t,u);if(!o(e))throw n(e.error);return e.value};if(!a&&!c)return await f(s);try{return await f(s)}catch(t){if(!a||Fr(t))throw t;return l&&u.locals.set(l,t),await f(a)}finally{c&&await f(c)}})}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],i=[],o=[],s=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"def"===e.type?i.push(e):"initBlock"===e.type?o.push(e):s.push(e);for(const t of i)this.execute(t,e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Fr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of o)try{n=await this.execute(t,e)}catch(t){if(Fr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Fr(t)&&(t.isHalt||t.isExit))break;throw t}return n}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const n of t.commands)try{await this.execute(n,e)}catch(t){if(Fr(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let n;for(const r of t.commands)try{n=await this.execute(r,e)}catch(t){if(Fr(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return n}async executeObjectLiteral(t,e){const n={};if(!t.properties)return n;for(const r of t.properties){let t;t="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,e)+"";const i=await this.execute(r.value,e);n[t]=i}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:o}=t,s=t.imperativeInstaller;"function"==typeof s?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:s}),Me(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:o}),Me(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){Me("BEHAVIOR: installBehaviorOnElement called: "+t);let r=this.behaviorRegistry.get(t);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(r=this.behaviorRegistry.get(t)),!r))throw Error(`Behavior "${t}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(Me(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),Me(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));Me("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const i={me:e,owner:e,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},o=this.enhanceContext(i);if(r.parameters)for(const t of r.parameters)o.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||o.locals.set(t,e);if(r.initBlock){Me("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,o),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),Me("BEHAVIOR: Init block completed for "+t)}catch(e){if(Me(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Fr(e)))throw e}}if(Me(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${t}`),r.eventHandlers){const e=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,o),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}Me("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:i,target:o,args:s,selector:a,condition:c,attributeName:l,watchTarget:u,modifiers:f,errorSymbol:d,errorHandler:h,finallyHandler:m}=t,p=r&&r.length>0?r:[n];Me(`BEHAVIOR: executeEventHandler: event='${n}', target='${o}'`);let y=[],g=null;if(o){const t="string"==typeof o?o.toLowerCase():"";if("window"===t||"the window"===t)g=window;else if("document"===t||"the document"===t||"body"===t)g=document;else if("me"===t||"myself"===t)y=e.me?[e.me]:[];else if("string"==typeof o&&e.locals.has(o)){const t=e.locals.get(o);Me(`BEHAVIOR: Target resolution: found local '${o}', isElement: ${this.isElement(t)}`),this.isElement(t)?y=[t]:Array.isArray(t)?y=t.filter(t=>this.isElement(t)):"string"==typeof t&&(y=this.queryElements(t,e))}else Me(`BEHAVIOR: Target resolution: querying for '${o}'`),y=this.queryElements(o,e)}else y=e.me?[e.me]:[];if(0===y.length&&!g)return void Me(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(y,l,i,e);if("change"===n&&u)return void this.setupChangeObserver(u,i,e);const b=t.customEventSource;if(b&&this.registryIntegration){Me(`BEHAVIOR: executeEventHandler - Using custom event source '${b}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),o={...e,locals:r,it:t,event:t},s=this.enhanceContext(o);Me(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},s)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(b,{event:n,handler:t,target:o,selector:a},e);Me(`BEHAVIOR: Subscribed to custom event source '${b}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${b}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${b}':`,t)}return}const v=Wr.createEventHandler(this,i,e,a,s,{errorSymbol:d,errorHandler:h,finallyHandler:m},1===p.length?c:void 0);let w,E=null;if(f){let t=v;if(f.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(f.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(f.debounce){const e=f.debounce;let n;w=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},E=()=>{n&&(clearTimeout(n),n=void 0)}}else if(f.throttle){const e=f.throttle;let n=0;w=r=>{const i=Date.now();e>i-n||(n=i,t(r))}}else w=t}else w=v;const x=f?.once?{once:!0}:void 0;if(g){for(const t of p)g.addEventListener(t,w,x),y.length>0?this.cleanupRegistry.registerListener(y[0],g,t,w):this.cleanupRegistry.registerGlobal(()=>g.removeEventListener(t,w),"listener",`Global ${t} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const t of y){for(const e of p){if("resize"===e&&"undefined"!=typeof ResizeObserver){const e=new ResizeObserver(t=>{for(const n of t){const t=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(t.synthetic=!0,w(t),x?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,w,x),this.cleanupRegistry.registerListener(t,t,e,w)}E&&this.cleanupRegistry.registerCustom(t,E,"debounce-timeout")}}static createEventHandler(t,e,n,r,i,o,s){return async a=>{const c=_r.get(a)??0;if(c>=100)return;if(_r.set(a,c+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{Me(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const l=new Map(n.locals),u={...n,locals:l,it:a,event:a};l.has("target")||u.locals.set("target",a.target);const f=t.enhanceContext(u);if(i&&i.length>0){const t=a,e=t.detail;for(const n of i)f.locals.set(n,t[n]??e?.[n]??null)}if(s){const e=a;for(const t of zr(s))!f.locals.has(t)&&t in e&&f.locals.set(t,e[t]);let n;try{n=await t.evaluateExpression(s,f)}catch(t){return void Me("Event filter threw; skipping handler body:",t)}if(!n)return}const d=async e=>{for(const n of e)try{await t.execute(n,f)}catch(e){if(Fr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(f,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}},h=o?.errorHandler,m=o?.finallyHandler;if(h||m)try{await d(e)}catch(t){if(!h||Fr(t))throw t;o?.errorSymbol&&f.locals.set(o.errorSymbol,t),await d(h)}finally{m&&await d(m)}else await d(e)}}setupMutationObserver(t,e,n,r){Me(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const i of t){const t=new MutationObserver(async t=>{for(const o of t)if("attributes"===o.type&&o.attributeName===e){Le(`MUTATION DETECTED: attribute '${e}' changed on`,i);const t={...r,me:i,it:o,locals:new Map(r.locals)},s=o.oldValue,a=i.getAttribute(e);t.locals.set("oldValue",s),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Fr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(i,t),Me("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){Me("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(t,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(t=>this.isElement(t))),Me(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const t of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){Le("CONTENT CHANGE DETECTED on",t,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",t);const o=i.oldValue,s=t.textContent;null!==o&&r.locals.set("oldValue",o),r.locals.set("newValue",s);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Fr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(t,r),Me("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const n=e.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=t;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return Me(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}function Zr(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}function Jr(t,e){if(e.startsWith("computed-")){const n=e.substring(9);return getComputedStyle(t).getPropertyValue(n)||""}const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}const Kr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:_t},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:_t},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:_t},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:_t},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result??t.it,validate:_t},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:t=>Ft(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:t=>Ft(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:t=>Ft(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:t=>Ft(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let n=e[0];if(n&&"object"==typeof n&&"type"in n){const t=n;"identifier"===t.type&&t.name?n=t.name:"literal"===t.type&&"string"==typeof t.value&&(n=t.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return t.me?t.me.closest(n):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:_t},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:_t},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:_t},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const i=r.querySelectorAll(n);return Array.from(i)},validate:t=>Ft(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const i=r||t.me;if(i&&i instanceof HTMLElement)return Jr(i,n)},validate:t=>Wt(t,1,2,"styleRef","property, optional element")??Vt(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&t.me?i=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return Jr(i,r)},validate:t=>Dt(t,2,"possessiveStyleRef","possessor, property")??Vt(t,0,"possessiveStyleRef","possessor")??Vt(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&t.me?i=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return Jr(i,n)},validate:t=>Dt(t,2,"ofStyleRef","property, reference")??Vt(t,0,"ofStyleRef","property")??Vt(t,1,"ofStyleRef","reference")}};function Xr(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Gr="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 Yr;function Qr(){return Yr({validate:t=>({success:!0,data:t})})}function ti(t,e){if(Gr)return Qr();const n=Yr({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:Xr("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(e?.strict){const e=Object.keys(t),n=Object.keys(r).filter(t=>!e.includes(t));if(n.length>0)return{success:!1,error:Xr("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[e,n]of Object.entries(t)){const t=r[e];if(!(e in r)&&!n.t)return{success:!1,error:Xr("missing-argument",`Required field "${e}" is missing`,e)};const o=n.validate(t);if(!o.success)return{success:!1,error:Xr("validation-error",o.error.message||`Field "${e}" validation failed`,o.error.path?`${e}.${o.error.path}`:e)};void 0!==o.data&&(i[e]=o.data)}return{success:!0,data:i}}});return n.strict=()=>ti(t,{strict:!0}),n}Yr=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:!0,data:e.data}:{success:!1,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:!0,validate:e=>null==e?{success:!0,data:void 0}:t(e)};return Yr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:!1,error:Xr("runtime-error",`String must be at least ${t} characters long`)}:r}};return Yr(n)}),t.max||(t.max=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:!1,error:Xr("runtime-error",`String must be at most ${t} characters long`)}:r}};return Yr(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:!0,validate:n=>void 0===n?{success:!0,data:t}:e(n)};return Yr(n)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?t(i.data)?i:{success:!1,error:Xr("runtime-error",e||"Refinement validation failed")}:i}};return Yr(r)}),new Proxy(t,{get:(t,e,n)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,n):function(...t){return n}})};const ei=t=>function(t={}){return Gr?Qr():Yr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:Xr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:Xr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:Xr("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:!1,error:Xr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:Xr("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),ni=t=>ti(t),ri=t=>function(t){return Gr?Qr():Yr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:Xr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:Xr("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const i=t[r].validate(e[r]);if(!i.success)return{success:!1,error:Xr("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(t),ii=()=>Qr();class oi{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(this.ttl>=Date.now()-e.timestamp)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU(),this.cache.set(t,{result:e,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[n,r]of this.accessOrder)e>r&&(e=r,t=n);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,n)=>t+(e-n.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const si=new class{constructor(){this.domQueryCache=new oi(200,3e3),this.exprResultCache=new oi(500,2e3),this.cssMatchCache=new oi(100,5e3),this.formValueCache=new oi(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(t);return this.domQueryCache.set(e,r),r}querySelectorAll(t){const e="querySelectorAll:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,r),r}getElementById(t){const e="getElementById:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(t);return this.domQueryCache.set(e,r),r}getElementsByClassName(t){const e="getElementsByClassName:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,r),r}matches(t,e){const n=`matches:${this.getElementCacheKey(t)}:${e}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=t.matches(e);return this.cssMatchCache.set(n,i),i}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),n=this.formValueCache.get("formValue:"+e);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(t,e){const n=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+n,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(t.cache.keys()))"string"==typeof n&&n.includes(e)&&t.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),n=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${n}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([n,r])=>{t-r.timestamp>e.ttl&&e.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{si.cleanup()},1e4);const ai=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const n=performance.now()-e;return this.startTimes.delete(t),n}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=si.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function ci(){si.cleanup(),ai.getMetrics().memoryUsage>52428800&&ai.reset()}let li=null;function ui(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const n=t.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${e} cannot be converted to number: "${t}"`);return r}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const n=t[0];if(Array.isArray(n))throw Error(e+" is a nested array, cannot convert to number");return ui(n,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const n=parseFloat(t);if(!isNaN(n))return n}}const n=t.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function fi(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?null:n}return"boolean"==typeof t?t?1:0:null==t?0:null}function di(t,e){if(!Number.isFinite(t)){if(Number.isNaN(t))throw Error(e+" resulted in non-finite value: NaN");throw Error(`${e} resulted in non-finite value: ${t>0?"Infinity":"-Infinity"}`)}return t}function hi(t){try{return ui(t,"_"),!0}catch{return!1}}function mi(t,e,n){if("==="===n)return t===e;if("!=="===n)return t!==e;if(null==t||null==e)return function(t,e,n){if(null==t&&null==e)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(t,e,n);const[r,i]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const n=parseFloat(t),r=parseFloat(e);return isNaN(n)||isNaN(r)?[t,e]:[n,r]}const n=fi(t),r=fi(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>i;case"<":return i>r;case">=":return r>=i;case"<=":return i>=r;case"==":return pi(t,e);case"!=":return!pi(t,e);default:return!1}}function pi(t,e){if(t===e)return!0;if(typeof t==typeof e)return("string"==typeof t||"number"==typeof t)&&t===e;if("number"==typeof t&&"string"==typeof e){const n=parseFloat(e);return!isNaN(n)&&t===n}if("string"==typeof t&&"number"==typeof e){const n=parseFloat(t);return!isNaN(n)&&n===e}return"boolean"==typeof t?pi(t?1:0,e):"boolean"==typeof e?pi(t,e?1:0):t+""==e+""}function yi(t,e=[]){return{isValid:!1,errors:t,suggestions:e}}function gi(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function bi(t,e,n,r,i,o=!0,s){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:o,...void 0!==s&&{error:s}}),r}function vi(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}"undefined"!=typeof window&&function(t=3e4){li&&clearInterval(li),li=setInterval(ci,t)}();const wi=ri([ii(),ii()]),Ei=ri([ii(),ei()]),xi={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return bi(this,t,[e,n],e==n,r)}catch(i){throw bi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Ut(t,"equals"),inputSchema:wi,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"]}},ki={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e===n;return r&&bi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"strictEquals")},Si={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!=n;return r&&bi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"notEquals")},Ti={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!==n;return r&&bi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"strictNotEquals")},Ai={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=mi(e,n,"<");return r&&bi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"lessThan")},Ci={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=mi(e,n,"<=");return r&&bi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"lessThanOrEqual")},$i={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=mi(e,n,">");return r&&bi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"greaterThan")},Oi={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=mi(e,n,">=");return r&&bi(this,t,[e,n],o,i),o},validate:t=>Ut(t,"greaterThanOrEqual")},ji={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return bi(this,t,[e,n],e&&n,r)}catch(i){throw bi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Ut(t,"and"),inputSchema:wi,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"]}},Ni={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e||n;return r&&bi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ut(t,"or")},Ri={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&bi(this,t,[e],r,n?Date.now():0),r},validate:t=>Dt(t,1,"not","operand")},Li={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||(Ct(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!jt(e)||0!==Object.keys(e).length)),n&&bi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"isEmpty","value")},Ii={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||!1===e||(Array.isArray(e)||e instanceof NodeList?0===e.length:(Ct(e),!1)),n&&bi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"no","value")},Mi={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!await Li.evaluate(t,e);return n&&bi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"isNotEmpty","value")},Pi={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=qi(e);return n&&bi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"exists","value")};function qi(t){return null!=t&&(Array.isArray(t)?t.length>0:!("undefined"!=typeof NodeList&&t instanceof NodeList)||t.length>0)}const Hi={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!qi(e);return n&&bi(this,t,[e],i,r),i},validate:t=>Dt(t,1,"doesNotExist","value")},Bi={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let o;if(e&&n){if(vi(e)&&vi(n))return o=e.contains(n),r&&bi(this,t,[e,n],o,i),o;if(Ct(e)&&e.match(/^[.#][\w-]+$/)){const s=document.querySelector(e);if(s&&vi(n))return o=s.contains(n),r&&bi(this,t,[e,n],o,i),o;if(s&&Ct(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return o=!!a&&s.contains(a),r&&bi(this,t,[e,n],o,i),o}}if(Ct(n)&&n.match(/^[.#][\w-]+$/)&&vi(e)){const s=document.querySelector(n);return o=!!s&&e.contains(s),r&&bi(this,t,[e,n],o,i),o}}if(Ct(e)&&Ct(n))o=e.includes(n);else if(Array.isArray(e)||"undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e);o=t.includes(n)||n instanceof Node&&t.some(t=>t instanceof Node&&t.contains(n))}else o=!(!jt(e)||!Ct(n))&&n in e;return r&&bi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"contains","container, value")},Di={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=!await Bi.evaluate(t,e,n);return r&&bi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"doesNotContain","container, value")},Vi={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=null!=e&&null!=n&&(e+"").startsWith(n+"");return r&&bi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"startsWith","str, prefix")},Fi={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=null!=e&&null!=n&&(e+"").endsWith(n+"");return r&&bi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"endsWith","str, suffix")},Ui={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const i=t.evaluationHistory;let o=n,s=r;if(null!=o&&null!=s&&o>s){const t=o;o=s,s=t}const a=null!=o&&null!=s&&e>=o&&s>=e;return i&&bi(this,t,[e,n,r],a,i?Date.now():0),a},validate:t=>Dt(t,3,"between","value, min, max")},_i={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let i;if(e instanceof Element&&Ct(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{i=function(t,e){return si.matches(t,e)}(e,t)}catch(t){i=!1}else i=!1}else if(Ct(e)&&Ct(n)){const t=e,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){i=t.includes(r)}}else i=!1;return bi(this,t,[e,n],i,r)}catch(i){throw bi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Dt(t,2,"matches","element, selector"),inputSchema:Ei,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"]}},zi={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let o=!1;if(e instanceof Element&&Ct(n)){const t=n;t.startsWith(".")?o=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(o=e.hasAttribute(t.slice(1,-1)))}return r&&bi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"has","element, selector")},Wi={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,o=!await zi.evaluate(t,e,n);return r&&bi(this,t,[e,n],o,i),o},validate:t=>Dt(t,2,"doesNotHave","element, selector")},Zi={equals:xi,strictEquals:ki,notEquals:Si,strictNotEquals:Ti,lessThan:Ai,lessThanOrEqual:Ci,greaterThan:$i,greaterThanOrEqual:Oi,and:ji,or:Ni,not:Ri,no:Ii,isEmpty:Li,isNotEmpty:Mi,exists:Pi,doesNotExist:Hi,contains:Bi,doesNotContain:Di,startsWith:Vi,endsWith:Fi,between:Ui,matches:_i,has:zi,doesNotHave:Wi};class Ji{trackPerformance(t,e,n,r){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(t,e,n,r=(n?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:e,duration:Date.now()-e,success:n})}toBoolean(t){return!(!1===t||0===t||0n===t||""===t||null==t||$t(t)&&isNaN(t))}success(t,e){return{success:!0,value:t,type:e}}failure(t,e,n,r,i=[]){return{success:!1,error:{name:t,type:e,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:!1,errors:[{type:t,message:e,suggestions:n}],suggestions:n}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":jt(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":Ct(t)?"String":$t(t)?"Number":Ot(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):Ct(t)?t.split(""):null==t?[]:jt(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if($t(t)&&Number.isFinite(t))return t;if(Ct(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Ot(t)?t?1:0:null}}const Ki=ni({value:ei().describe("String literal value")}).strict(),Xi=ni({value:function(t={}){return Gr?Qr():Yr({validate:e=>{const n=Number(e);return isNaN(n)?{success:!1,error:Xr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:!1,error:Xr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:!1,error:Xr("runtime-error","Number must be at most "+t.max)}:{success:!0,data:n}}})}(Qi||{}).describe("Number literal value")}).strict(),Gi=ni({value:(Gr?Qr():Yr({validate:t=>"boolean"!=typeof t?{success:!1,error:Xr("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}})).describe("Boolean literal value")}).strict(),Yi=ni({left:ii().describe("Left operand"),right:ii().describe("Right operand")}).strict();var Qi;const to={stringLiteral:new class extends Ji{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=Ki,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid){const e=this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(t,n,!1),e}let i=e.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,t));const o=this.success(i,"string");return this.trackSimple(t,n,!0,i),o}catch(e){return this.trackSimple(t,n,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let n=t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=this.resolveExpression(n.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,n)=>{try{const t=this.resolveVariable(n,e);return void 0!==t?t+"":""}catch(t){return""}}),n}resolveExpression(t,e){if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++)r=r[n[t]];return r}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?(at(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Ji{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Xi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?Number.isFinite(e.value)?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Ji{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Gi,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Ji{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Yi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ui(e.left,"left operand")+ui(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Ji{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=Yi,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,!0,i),this.success(i,"string")}catch(e){return this.trackSimple(t,n,!1),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=Yi.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(Ct(t))return t;if($t(t))return""+t;if(Ot(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Ji{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Yi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ui(e.left,"left operand")*ui(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}},eo={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const n=void 0!==e?e:t.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:Ct(n)?n.length>0?n[0]:null:jt(n)&&"length"in n&&$t(n.length)&&n.length>0?n[0]:null},validate:t=>zt(t,1,"first","collection")},no={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const n=void 0!==e?e:t.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const t=n.children;return t.length>0?t[t.length-1]:null}return Ct(n)?n.length>0?n[n.length-1]:null:jt(n)&&"length"in n&&$t(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>zt(t,1,"last","collection")},ro={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!$t(n))throw Error("Index must be a number");const i=n,o=void 0!==r?r:t.it;if(null==o)return null;if(Array.isArray(o)){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}if(o instanceof NodeList||o instanceof HTMLCollection){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}if(o instanceof Element){const t=o.children,e=0>i?t.length+i:i;return e>=0&&t.length>e?t[e]:null}if(Ct(o)){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}if(jt(o)&&"length"in o&&$t(o.length)){const t=0>i?o.length+i:i;return t>=0&&o.length>t?o[t]:null}return null},validate:t=>Wt(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function io(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;const t=n.querySelector(e);if(t)return t;n=n.nextElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?io(r,e):null}function oo(t,e){let n=t.previousElementSibling;for(;n;){const t=Array.from(n.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(n.matches(e))return n;n=n.previousElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?oo(r,e):null}function so(t,e,n,r){if(n.inSearch){if(null==n.inElt)return;return function(t,e,n,r){const i=Array.from(e??[]),o=[];for(const e of i)(e.matches&&e.matches(n)||e===t)&&o.push(e);for(let e=0;o.length-1>e;e++)if(o[e]===t)return o[e+1];if(r){const t=o[0];if(t&&t.matches&&t.matches(n))return t}}(t,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),e,!!n.wrapping)}const i=n.within??("undefined"!=typeof document?document.body:null);if(i)return r?function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=0;i.length>e;e++){const n=i[e];if(2===n.compareDocumentPosition(t))return n}return r?i[0]:void 0}(t,i,e,!!n.wrapping):function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=i.length-1;e>=0;e--){const n=i[e];if(4===n.compareDocumentPosition(t))return n}return r?i[i.length-1]:void 0}(t,i,e,!!n.wrapping)}function ao(t){let e=0,n=t;for(;n&&n.parentElement;)e+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,e+=1e3;return e}const co={first:eo,last:no,at:ro,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r,i]=e,o=r||t.me;return o&&o instanceof Element?n?i?so(o,n,i,!0):io(o,n):o.nextElementSibling:null},validate:t=>zt(t,3,"next","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[n,r,i]=e,o=r||t.me;return o&&o instanceof Element?n?i?so(o,n,i,!1):oo(o,n):o.previousElementSibling:null},validate:t=>zt(t,3,"previous","optional selector, optional fromElement, optional modifiers")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[n,r,i]=e,o=i||t.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=ao(t);for(const t of r)if(ao(t)>i)return t;return null}(o,n,s):null},validate:t=>Wt(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[n,r,i]=e,o=i||t.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=ao(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(i>ao(e))return e}return null}(o,n,s):null},validate:t=>Wt(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}};class lo{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ui(t,"left operand");return{success:!0,value:di(r+ui(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:!1,errors:[gi("runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){const e=function(t){if(null==t)return yi([gi("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return yi([gi("type-mismatch","Expected object, got "+typeof t)],["Provide an object with left and right operands"]);const e=t;if(!("left"in e)||!("right"in e)){const t=[];return"left"in e||t.push("left"),"right"in e||t.push("right"),yi([gi("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return hi(n)?hi(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[gi("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[gi("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const uo={addition:new lo,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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ui(t,"left operand");return{success:!0,value:di(r-ui(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:!1,errors:[gi("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new lo).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ui(t,"left operand");return{success:!0,value:di(r*ui(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:!1,errors:[gi("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new lo).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=!0){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(ui(t,"left operand"),ui(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[gi("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new lo).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e){if(0===e)throw Error("Modulo by zero");return t%e}(ui(t,"left operand"),ui(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[gi("runtime-error","Modulo failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(t){return(new lo).validate(t)}},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(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ui(t,"left operand"),i=ui(n,"right operand");return{success:!0,value:di(Math.pow(r,i),"power"),type:"number"}}catch(t){return{success:!1,errors:[gi("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new lo).validate(t)}}};function fo(){return Zr(Kr,Zi,Yt,co,ne,to,uo)}var ho=Object.freeze({__proto__:null,conversion:Yt,conversionExpressions:Yt,createCommonRegistry:function(){return Zr(Kr,Zi,to,Yt,co)},createCoreRegistry:function(){return Zr(Kr,Zi,to)},createExpressionRegistry:Zr,createFullExpressionRegistry:fo,createFullRegistry:function(){return Zr(Kr,Zi,to,Yt,co,ne)},logical:Zi,logicalExpressions:Zi,positional:co,positionalExpressions:co,properties:ne,propertiesExpressions:ne,references:Kr,referencesExpressions:Kr,special:to,specialExpressions:to});function mo(t,e,n,r,i,o){function s(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?r.static?t:t.prototype:null,f=e||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),d=!1,h=n.length-1;h>=0;h--){var m={};for(var p in r)m[p]="access"===p?{}:r[p];for(var p in r.access)m.access[p]=r.access[p];m.addInitializer=function(t){if(d)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(t||null))};var y=(0,n[h])("accessor"===c?{get:f.get,set:f.set}:f[l],m);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=s(y.get))&&(f.get=a),(a=s(y.set))&&(f.set=a),(a=s(y.init))&&i.unshift(a)}else(a=s(y))&&("field"===c?i.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),d=!0}function po(t,e,n){for(var r=arguments.length>2,i=0;e.length>i;i++)n=r?e[i].call(t,n):e[i].call(t);return r?n:void 0}function yo(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}function go(t){return function(e,n){Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function bo(t){return{...t}}function vo(t){return()=>new t}function wo(t,e){return t?`[${t}] ${e}`:e}function Eo(t,e,n){if(gt(t))return t;if(!t){const t=e.me;if(!t)throw Error(wo(n,"No target element \u2014 provide explicit target or ensure context.me is set"));return ko(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error(wo(n,'Context reference "me" is not available'));return ko(e.me)}if("it"===r){if(!gt(e.it))throw Error(wo(n,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===r){if(!e.you)throw Error(wo(n,'Context reference "you" is not available'));return ko(e.you)}const i=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw Error(wo(n,"DOM not available \u2014 cannot resolve element selector"));const o=i.querySelector(r);if(!o)throw Error(wo(n,"Element not found with selector: "+r));if(!gt(o))throw Error(wo(n,"Element found but is not an HTMLElement: "+r));return o}throw Error(wo(n,"Invalid target type: "+typeof t))}function xo(t,e){if(Array.isArray(t))return t.filter(gt);if(bt(t))return Array.from(t).filter(gt);if(gt(t))return[t];if(!t){const t=e.me;return t&&gt(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&gt(e.me)?[e.me]:[];if("it"===n)return gt(e.it)?[e.it]:[];if("you"===n)return e.you&&gt(e.you)?[e.you]:[];const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let t=n;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.querySelectorAll(t);return Array.from(e).filter(gt)}}return[]}function ko(t){if(gt(t))return t;throw Error("Value is not an HTMLElement")}function So(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(wo(n,'No "me" element in context'));if(!gt(e.me))throw Error(wo(n,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(wo(n,'No "it" value in context'));if(!gt(e.it))throw Error(wo(n,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(wo(n,'No "you" element in context'));if(!gt(e.you))throw Error(wo(n,"context.you is not an HTMLElement"));return e.you;default:throw Error(wo(n,"Unknown possessive: "+t))}}"function"==typeof SuppressedError&&SuppressedError;const To=["on","from","to","in","with","at"];async function Ao(t,e,n,r,i={},o){let s=t;if(i.filterPrepositions&&t&&(s=t.filter(t=>{const e=t;return"identifier"!==e?.type||"string"!=typeof e.name||!To.includes(e.name.toLowerCase())})),(!s||0===s.length)&&i.fallbackModifierKey&&o){const t=o[i.fallbackModifierKey];t&&(s=[t])}if(!s||0===s.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!gt(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of s){const i=await e.evaluate(t,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(gt(i))a.push(i);else if(bt(i)){const t=Array.from(i).filter(gt);a.push(...t)}else if(Array.isArray(i)){const t=i.filter(gt);a.push(...t)}else{if("string"!=typeof i){if(null==i)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`)}try{let t=i;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),o=Array.from(r).filter(gt);a.push(...o)}catch(t){throw Error(`Invalid CSS selector: "${i}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!gt(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}class Co{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await Ao(t.args,e,n,r)}}(t,e,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>gt(t))||"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay)}showElement(t,e="block"){const n=t.dataset.originalDisplay;void 0!==n?(t.style.display=n||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let $o=(()=>{let t,e,n=[go({name:"hide"})],r=[],i=Co;var o=e=class extends i{constructor(){super(...arguments),this.mode="hide"}get metadata(){return o.metadata}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>gt(t))}};return yo(e,"HideCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),po(e,r),o=e})();const Oo=vo($o);let jo=(()=>{let t,e,n=[go({name:"show"})],r=[],i=Co;var o=e=class extends i{constructor(){super(...arguments),this.mode="show"}get metadata(){return o.metadata}async execute(t,e){const n=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,n)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>gt(t))&&"string"==typeof e.defaultDisplay}};return yo(e,"ShowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),po(e,r),o=e})();const No=vo(jo);function Ro(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function Lo(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),n=t.indexOf("=");if(-1===n)return{name:t.trim()};const r=t.slice(0,n).trim();let i=t.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function Io(t,e){for(const n of t)e(n);return t}function Mo(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function Po(t,e,n){const r=t.hasAttribute(e);void 0!==n?r&&t.getAttribute(e)===n?t.removeAttribute(e):t.setAttribute(e,n):r?t.removeAttribute(e):t.setAttribute(e,"")}function qo(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&Bo(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&Bo(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&Bo(n)?[n]:[]}function Ho(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function Bo(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!Ho(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function Do(t,e){return t.map(t=>{if(Ho(t)){const n=function(t){const e=t.trim(),n=e.match(/^\{(.+)\}$/);return n?n[1].trim():e}(t),r=e.locals.get(n)??e.globals.get(n);return null!=r?r+"":(Re(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}function Vo(t){return"string"==typeof t&&t.trim().startsWith("*")}function Fo(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const n=e.substring(1).trim();return n?{property:n}:null}(t);if(!e)return null;const n=e.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function Uo(t,e,n){t.style.setProperty(e,n)}const _o=["dialog","details","summary","select"];function zo(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Wo(t,e,n){return function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return!1;const n=zo(t);return"string"==typeof n&&n.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return!1;const n=zo(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:zo(t),extractedFromNode:!0}:function(t){if(!t||"object"!=typeof t)return!1;if("attributeAccess"===t.type)return!0;if("selector"===t.type||"cssSelector"===t.type){const e=zo(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:zo(r)),extractedFromNode:!0}:{value:await e.evaluate(t,n),extractedFromNode:!1};var r}class Zo{async resolveTargets(t,e,n,r){return Ao(t,e,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return Wo(t,e,n)}parseClassNames(t){return qo(t)}isAttribute(t){return Ro(t.trim())}isCSSProperty(t){return Vo(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>gt(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Jo=(()=>{let t,e,n=[go({name:"add"})],r=[],i=Zo;var o=e=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return o.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:o}=function(t){const e=Lo(t);return{name:e.name,value:e.value??""}}(i);return{type:"attribute",name:r,value:o,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const o=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:o+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const i=this.parseClassNames(r);if(0===i.length)throw Error("add command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=Do(t.classes,e);n.length>0&&Mo(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,Io(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":!function(t,e){Mo(t,Object.entries(e),(t,[e,n])=>{t.style.setProperty(e,n)})}(t.targets,t.styles)}var n,r}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1;if("string"!=typeof t.value)return!1}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return!1;if(Array.isArray(e.styles))return!1;const n=e.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(t=>"string"==typeof t))return!1}return!0}};return yo(e,"AddCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),o=e})();const Ko=vo(Jo),Xo={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function Go(t){return t.includes("<")&&t.includes(">")}function Yo(t,e,n){!function(t,e,n){"replace"!==n?gt(e)?function(t,e,n){switch(n){case"beforebegin":t.parentElement?.insertBefore(e,t);break;case"afterbegin":t.insertBefore(e,t.firstChild);break;case"beforeend":t.appendChild(e);break;case"afterend":t.parentElement?.insertBefore(e,t.nextSibling)}}(t,e,n):function(t,e,n){const r=n,i=["beforebegin","afterbegin","beforeend","afterend"];if(!i.includes(r))throw Error(`Invalid insert position '${n}'. Expected one of ${i.join(", ")} (or 'replace').`);Go(e)?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e)}(t,e,n):function(t,e){gt(e)?(t.innerHTML="",t.appendChild(e)):Go(e)?t.innerHTML=e:t.textContent=e}(t,e)}(t,e,function(t){const e=Xo[t];if(void 0===e)throw Error(`Unknown semantic position '${t}'. Valid positions: ${Object.keys(Xo).join(", ")}.`);return e}(n))}function Qo(t){return!!t.parentNode&&(t.remove(),!0)}let ts=(()=>{let t,e,n=[go({name:"remove"})],r=[],i=Zo;var o=e=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return o.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if(gt(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&gt(r[0]))return{type:"element",targets:r.filter(t=>gt(t))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:Lo(i).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const i=this.parseClassNames(r);if(0===i.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=Do(t.classes,e);n.length>0&&Mo(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,Io(t.targets,t=>{t.removeAttribute(n)});break;case"styles":!function(t,e){Mo(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)Qo(e)}var n}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return!1;return!0}};return yo(e,"RemoveCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),o=e})();const es=vo(ts);function ns(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function rs(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=ns(t);return n?n.milliseconds:e}return e}function is(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=ns(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function os(t){return t&&"none"!==t?t.split(",").map(t=>{const e=parseFloat(t.trim());return isNaN(e)?0:t.includes("s")&&!t.includes("ms")?1e3*e:e}):[0]}function ss(t,e){let n=0;for(let r=0;t.length>r;r++)n=Math.max(n,(t[r]||0)+(e[r]||0));return n}function as(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function cs(t){return"DIALOG"===t.tagName}function ls(t){return"DETAILS"===t.tagName}function us(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&Po(t,n)}}function fs(t,e,n,r){const i=us(t,e,n),o=setTimeout(i,r);return()=>{clearTimeout(o)}}function ds(t,e,n,r){const i=us(t,e,n),o=()=>{i(),t.removeEventListener(r,o)};return t.addEventListener(r,o,{once:!0}),()=>{t.removeEventListener(r,o)}}function hs(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(!1===n?t.removeAttribute(r):t.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(e){case"textContent":return void(t.textContent=r);case"innerHTML":return void(t.innerHTML=r);case"innerText":return void(t.innerText=r);case"id":return void(t.id=r);case"className":return void(t.className=r);case"value":return void("value"in t&&(t.value=r));case"checked":return void("checked"in t&&(t.checked=!!n))}if(e.includes(".")){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++)if(i=i[r[t]],null==i)return;return void(i[r[r.length-1]]=n)}if(e.includes("-")||e in t.style)t.style.setProperty(e,r);else try{t[e]=n}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}function ms(t){return null==t||""===t}const ps=/^the\s+(.+?)\s+of\s+(.+)$/i,ys=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 gs(t){return"string"==typeof t&&ps.test(t)}function bs(t,e){const n=t.match(ps);if(!n)return null;try{return{element:Eo(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function vs(t,e,n){if(function(t){return!(!t||"object"!=typeof t)&&"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(t))return async function(t,e,n){const r=t.property?.name;if(!r)return null;let i=await e.evaluate(t.target,n);return Array.isArray(i)&&(i=i[0]),gt(i)?{element:i,property:r}:null}(t,e,n);if(function(t){return!(!t||"object"!=typeof t)&&"propertyAccess"===t.type&&("string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name)}(t))return async function(t,e,n){const r="string"==typeof t.property?t.property:t.property?.name;if(!r)return null;let i=await e.evaluate(t.object,n);return Array.isArray(i)&&(i=i[0]),gt(i)?{element:i,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,i=r.property;let o=await e.evaluate(t,n);if(Array.isArray(o)&&(o=o[0]),!gt(o))return null;const s=i?.name||i?.value;return s?{element:o,property:s}:null}return null}function ws(t){const{element:e,property:n}=t;return n.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,n.substring(1)):Ht(e,n)}function Es(t,e){const{element:n,property:r}=t;r.startsWith("*")?Uo(n,r.substring(1),e+""):hs(n,r,e)}async function xs(t,e,n){let r,i;if(t?.for){const i=await e.evaluate(t.for,n);r="number"==typeof i?i:"string"==typeof i?rs(i):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function ks(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return!1;if("identifier"!==t.type)return!1;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return _o.includes(e)}(e)}(e);if(gt(t)||Array.isArray(t)&&t.every(t=>gt(t)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return _o.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const Ss=vo((()=>{let t,e,n=[go({name:"toggle"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(t){if(!t||"asExpression"!==t.type)return!1;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=!0;const e=t.args[0].expression;t={...t,args:[e,...t.args.slice(1)]}}const i=t.args[0],o=i?.name;if("between"===o&&t.args.length>=4){const{duration:r,untilEvent:i}=await xs(t.modifiers,e,n),o=async t=>{const r=t;return"selector"===r?.type?r.value:e.evaluate(t,n)},s=await o(t.args[1]),a=await o(t.args[3]),c=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&c.push(t.args[e])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await Ao(c,e,n,"toggle",l,t.modifiers);return{type:"classes-between",classA:(s+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:i}}const s=await vs(i,e,n);if(s)return{type:"property",target:s};if("selector"===i.type&&"string"==typeof i.value&&i.value.startsWith("*")){let r=i.value,o=1;if("*"===r&&t.args.length>1&&"identifier"===t.args[1].type&&(r="*"+t.args[1].name,o=2),"*"===r&&t.modifiers?.on){const i=t.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:o,untilEvent:s}=await xs(t.modifiers,e,n),a=Fo(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:o,untilEvent:s}}}}const s=Fo(r);if(s){const{duration:r,untilEvent:i}=await xs(t.modifiers,e,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:s,targets:await Ao(t.args.slice(o),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await xs(t.modifiers,e,n),{value:l}=await Wo(i,e,n);if(gs(l)){const t=bs(l,n);if(t)return{type:"property",target:t}}const{type:u,expression:f}=ks(l,i),d={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:i}=Lo(f);return{type:"attribute",name:r,value:i,targets:await Ao(t.args.slice(1),e,n,"toggle",d,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Fo(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await Ao(t.args.slice(1),e,n,"toggle",d,t.modifiers)}}case"element":{let o;if(gt(l))o=[l];else if(Array.isArray(l)&&l.every(t=>gt(t)))o=l;else if(f){const t=document.querySelectorAll(f);o=Array.from(t).filter(t=>gt(t))}else o=await Ao([i],e,n,"toggle",d,t.modifiers);const s=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(o);if("dialog"===s){const i=r?"modal":await async function(t,e,n,r){if(e?.as){const t=await n.evaluate(e.as,r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await n.evaluate(t[1],r);if("string"==typeof e){const i=e.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&t.length>=3){const e=await n.evaluate(t[2],r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,n);return{type:"dialog",mode:i,targets:o}}return"details"===s?{type:"details",targets:as(o)}:"select"===s?{type:"select",targets:o}:{type:"classes",classes:qo(f),targets:o,duration:a,untilEvent:c}}default:{const r=qo(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Ao(t.args.slice(1),e,n,"toggle",d,t.modifiers),duration:a,untilEvent:c}}}}async execute(t,e){switch(t.type){case"classes":{const n=Do(t.classes,e);if(0===n.length)return[...t.targets];if(Mo(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&fs(e,"class",n[0],t.duration),t.untilEvent&&ds(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,Io(t.targets,t=>{Po(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&fs(e,"attribute",t.name,t.duration),t.untilEvent&&ds(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Io(t.targets,e=>function(t,e){const n=window.getComputedStyle(t);switch(e){case"display":"none"===n.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=n.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=ws(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||ys.has(r)||ys.has(r.toLowerCase())){const n=!e;return Es(t,n),n}if("number"==typeof e){const n=0===e?1:0;return Es(t,n),n}if("string"==typeof e){const r="__ht_"+n,i=t.element[r];return""===e&&void 0!==i?(Es(t,i),i):(t.element[r]=e,Es(t,""),"")}Es(t,!e)}(t.target),[t.target.element];case"dialog":return Io(t.targets,e=>{return r=t.mode,void((n=e).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return Io(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Io(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const n=e.classList.contains(t.classA),r=e.classList.contains(t.classB);n?(e.classList.remove(t.classA),e.classList.add(t.classB)):r?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&fs(e,"class",t.classA,t.duration),t.untilEvent&&ds(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}};return yo(e,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),i=e})());const Ts=vo((()=>{let t,e,n=[go({name:"put"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let o=-1,s=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&i.includes(c)){o=e,s=c;break}}let a=null,c=null;if(-1===o){const e=i.find(e=>t.modifiers[e]);if(e)a=t.args[0],s=e,c=t.modifiers[e];else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],s=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],s=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2]}else a=t.args.slice(0,o)[0]||null,c=t.args.slice(o+1)[0]||null;if(!a)throw Error("put requires content");if(!s)throw Error("put requires position keyword");const l=await e.evaluate(a,n),u=this.mapPosition(s);let f,d,h=null;if(c){const t=r(c),i=await vs(c,e,n);if(i)return{value:l,targets:[i.element],position:"into",memberPath:i.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)h=t.value;else if("identifier"===t?.type){const i=t.name;if("my"===i||"me"===i||"I"===i){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"into",memberPath:r.name}}else if("its"===i||"it"===i){const t=await e.evaluate(c,n);"string"==typeof t&&(h=t)}else h=i}if(h&&r?.name)f=r.name;else if(!h&&!f){const t=await e.evaluate(c,n);"string"==typeof t&&(h=t)}}else if("identifier"===t&&"me"===c.name)h=null;else if("selector"===t||"cssSelector"===t)h=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&gs(t)){const e=bs(t,n);if(e)return{value:l,targets:[e.element],position:"into",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?h=t:d=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))h=t;else{const r=Tt(await e.evaluate(c,n));if(r)return{value:l,targets:r,position:u,memberPath:f};d=t}}else{const t=await e.evaluate(c,n),r=Tt(t);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof t&&(this.looksLikeCss(t)?h=t:d=t)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(h,n),position:u,memberPath:f}}async execute(t,e){const{value:n,targets:r,position:i,memberPath:o,variableName:s}=t;if(s)return e.locals&&e.locals.set(s,n),e[s]=n,void Object.assign(e,{it:n});if(o)for(const t of r)this.setProperty(t,o,n);else for(const t of r)Yo(t,this.parseValue(n),i);return r}mapPosition(t){switch(t){case"into":return"into";case"before":return"before";case"after":return"after";case"at start of":return"prepend";case"at end of":return"append";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!gt(e.me))throw Error("put: no target and context.me is null");return[e.me]}return St(t)}parseValue(t){return gt(t)?t:null==t?"":t+""}looksLikeCss(t){return!!t&&(!!/^[#.\[]/.test(t)||(!(!/[>+~\s]/.test(t)||1>=t.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(t.toLowerCase())))}setProperty(t,e,n){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++){if(!i[r[t]])throw Error(`Property path "${e}" does not exist`);i=i[r[t]]}i[r[r.length-1]]=n}};return yo(e,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),i=e})()),As={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function Cs(t){return t.replace(/[&<>"']/g,t=>As[t])}let $s=(()=>{let t,e,n=[go({name:"make"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.modifiers.an??t.modifiers.a??t.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const i=r.raw;let o="string"==typeof i&&i.startsWith("<")?i:await e.evaluate(r,n);if(null==o)throw Error("Make command requires class name or DOM element expression");"string"==typeof o&&o.startsWith("<")&&(o=await async function(t,e){if(!t.includes("{"))return t;const n=/\{([^{}]+)\}/g,r=[];let i;for(;null!==(i=n.exec(t));){let t=i[0];try{const n=await lr(i[1].trim(),e);null!=n&&(t=Cs(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:t})}let o=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,text:i}=r[t];o=o.slice(0,e)+i+o.slice(e+n)}return o}(o,n));const s=void 0!==t.modifiers.an?"an":"a",a=await async function(t,e,n){if(!t)return[];if("arrayLiteral"===t.type&&Array.isArray(t.args)){const r=[];for(const i of t.args)r.push(await e.evaluate(i,n));return r}const r=await e.evaluate(t,n);return Array.isArray(r)?r:[r]}(t.modifiers.from,e,n),c=await async function(t,e,n){if(!t)return;if(("symbol"===t.type||"identifier"===t.type)&&"string"==typeof t.name)return t.name;const r=await e.evaluate(t,n);return"string"==typeof r?r:void 0}(t.modifiers.called,e,n);return{article:s,expression:o,constructorArgs:a,variableName:c}}async execute(t,e){const{expression:n,constructorArgs:r=[],variableName:i}=t,o="string"==typeof n&&n.startsWith("<"),s=o&&n.endsWith("/>")?function(t){const e=t.slice(1,-2);let n="div",r=e;const i=e.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=e.slice(i[0].length));const o=document.createElement(n),s=r.split(/(?=[.#])/);for(const t of s)if(t.startsWith("#")){const e=t.slice(1);e&&(o.id=e)}else if(t.startsWith(".")){const e=t.slice(1);e&&o.classList.add(e)}return o}(n):o&&/<\/[a-zA-Z]/.test(n)?function(t){const e=document.createElement("template");e.innerHTML=t.trim();const n=e.content.firstElementChild;if(n&&gt(n))return n;const r=document.createElement("div");r.innerHTML=t.trim();const i=r.firstElementChild;return i&&gt(i)?i:r}(n):function(t,e,n){if(gt(t))return t;const r=t+"";let i;if("undefined"!=typeof window&&(i=window[r]),i||"undefined"==typeof global||(i=global[r]),!i&&n.variables?.has(r)&&(i=n.variables.get(r)),!i||"function"!=typeof i)throw Error(`Constructor '${r}' not found or is not a function`);return 0===e.length?new i:new i(...e)}(n,r,e);return Object.assign(e,{it:s}),i&&Et(i,s,e),s}};return yo(e,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),i=e})();const Os=vo($s),js=vo((()=>{let t,e,n=[go({name:"empty"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ao(t.args,e,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.innerHTML=""}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return yo(e,"EmptyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),i=e})());function Ns(t){if("string"!=typeof t)return;const e=t.toLowerCase().trim();return"non-modal"===e||"nonmodal"===e?"non-modal":"modal"===e?"modal":void 0}function Rs(t){return t.hasAttribute("popover")}const Ls=vo((()=>{let t,e,n=[go({name:"open"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=(t.args??[]).filter(t=>{const e=t;if("identifier"!==e?.type)return!0;const n=e.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=as(await Ao(r,e,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)),o=await async function(t,e,n,r){if(e?.as){const t=Ns(await n.evaluate(e.as,r));if(t)return t}for(const e of t){const t=e;if("asExpression"!==t?.type)continue;const n=t.targetType,r=Ns(n?.name??n?.value);if(r)return r}for(let e=0;t.length-1>e;e++){const i=t[e];if("identifier"===i?.type&&"as"===i.name?.toLowerCase()){const i=await n.evaluate(t[e+1],r);if("string"==typeof i){const t=i.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}}return"modal"}(t.args??[],t.modifiers??{},e,n);return{targets:i,dialogMode:o}}async execute(t,e){for(const e of t.targets)if(cs(e))e.open||("modal"===t.dialogMode?e.showModal():e.show());else if(ls(e))e.open=!0;else if(Rs(e)){const t=e;if("function"==typeof t.showPopover)try{t.showPopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>gt(t))||"modal"!==e.dialogMode&&"non-modal"!==e.dialogMode)}};return yo(e,"OpenCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),i=e})());function Is(t){return t.hasAttribute("popover")}const Ms=vo((()=>{let t,e,n=[go({name:"close"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:as(await Ao(t.args,e,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers))}}async execute(t,e){for(const e of t.targets)if(cs(e))e.open&&e.close();else if(ls(e))e.open=!1;else if(Is(e)){const t=e;if("function"==typeof t.hidePopover)try{t.hidePopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return yo(e,"CloseCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),po(e,r),i=e})());function Ps(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e}const qs=vo((()=>{let t,e,n=[go({name:"select"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ao(t.args,e,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if(0!==t.targets.length)for(const e of t.targets){if(Ps(e)){e.select();continue}const t=e.ownerDocument??("undefined"!=typeof document?document:null),n=t?.defaultView;if(!t||!n)continue;const r=n.getSelection?.();if(r)try{const n=t.createRange();n.selectNodeContents(e),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return yo(e,"SelectCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"dom",compatibility:"standard"}),po(e,r),i=e})());function Hs(t){return"FORM"===t.tagName}const Bs=vo((()=>{let t,e,n=[go({name:"reset"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ao(t.args,e,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)Hs(e)&&e.reset()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return yo(e,"ResetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),po(e,r),i=e})());function Ds(t,e,n,r){return t?new Promise(n=>{const i=()=>{o({event:null,timedOut:!1,cancelled:!0})},o=Fs(()=>{t.removeEventListener(e,s),r&&r.removeEventListener("abort",i)},n),s=t=>{o({event:t,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(t.addEventListener(e,s),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function Vs(t){return new Promise(e=>setTimeout(e,t))}function Fs(t,e){let n=!1;return r=>{n||(n=!0,t(),e(r))}}const Us=vo((()=>{let t,e,n=[go({name:"wait"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,n);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n);const r=t.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,t.args[1],e,n):this.parseTimeWait(t.args[0],e,n)}async execute(t,e){const n=Date.now();if("time"===t.type)return await Vs(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,i=(await Ds(r,t.eventName)).event;if(Object.assign(e,{it:i}),t.destructure)for(const n of t.destructure)n in i&&e.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const t of i.destructure)t in r&&e.locals.set(t,r[t]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(t,e,n){return{type:"time",milliseconds:is(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const i=await n.evaluate(t,r);if("string"!=typeof i)throw Error("wait for: event name must be a string");const o=i.match(/^(\w+)\(([^)]+)\)$/),s=o?o[1]:i,a=o?o[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await n.evaluate(e,r);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=r.me??void 0;return{type:"event",eventName:s,target:c,destructure:a}}async parseEventArrayWait(t,e,n,r){let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}i||(i=r.me??void 0);const o=[];for(const e of t){const t=e;if("objectLiteral"!==t.type||!t.properties)continue;let s,a="",c=[];for(const e of t.properties){const t=e.key?.name||e.key?.value;"name"===t&&e.value?a=e.value.value||"":"args"===t&&e.value?.elements?c=e.value.elements.map(t=>t.value||t.name||""):"duration"===t&&e.value&&(s=e.value)}if(s){const t=await n.evaluate(s,r);o.push({type:"time",milliseconds:is(t)})}else a&&o.push({type:"event",eventName:a,target:i,destructure:c.length>0?c:void 0})}return 1===o.length?o[0]:{type:"race",conditions:o}}async parseRaceCondition(t,e,n){const r=[];t.modifiers.for?r.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n)):t.args[0]&&r.push(await this.parseTimeWait(t.args[0],e,n));const i=await e.evaluate(t.modifiers.or,n),o=Array.isArray(i)?i:[i];for(const t of o)try{r.push({type:"time",milliseconds:is(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);r.push(e?{type:"event",eventName:e[1],target:n.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(t,e){const n=new AbortController,r=n.signal,i=t.map(t=>"time"===t.type?Vs(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Ds(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(i)}finally{n.abort()}}};return yo(e,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"async",compatibility:"standard"}),po(e,r),i=e})()),_s=new Map;let zs=[/^4\d{2}$/,/^5\d{2}$/],Ws=(()=>{let t,e,n=[go({name:"fetch"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(t.args[0],e,n),i=this.parseResponseType(t.modifiers.as);return{url:r,responseType:i,options:await this.parseRequestOptions(t.modifiers.with,e,n),throwOnError:!t.modifiers.doNotThrow&&"response"!==i}}async execute(t,e){const n=Date.now(),{url:r,responseType:i,options:o}=t,s=new AbortController;let a;e.me&&(a=()=>s.abort(),e.me.addEventListener("fetch:abort",a,{once:!0}));const c={...o,signal:s.signal},l=_s.get(i);if(l?.accept){const t=new Headers(c.headers);t.has("Accept")||t.set("Accept",l.accept),c.headers=t}if(e.me){const t={...c,sender:e.me,headers:c.headers||{}};this.dispatchEvent(e.me,"fetch:beforeRequest",t),c.headers=t.headers}let u;o.timeout&&(u=setTimeout(()=>s.abort(),o.timeout));try{let o=await fetch(r,c);if(e.me){const t={response:o};this.dispatchEvent(e.me,"fetch:afterResponse",t),o=t.response}if(t.throwOnError&&function(t){const e=t+"";return zs.some(t=>t.test(e))}(o.status)){const t=Error(`Fetch failed for ${r}: HTTP ${o.status} ${o.statusText}`.trim());throw t.response=o,t.isFetchStatusError=!0,t}const s=await this.handleResponse(o,i,e);e.me&&this.dispatchEvent(e.me,"fetch:afterRequest",{result:s});const a={status:o.status,statusText:o.statusText,headers:o.headers,data:s,url:o.url,duration:Date.now()-n};return Object.assign(e,{it:s}),a}catch(t){if(e.me&&this.dispatchEvent(e.me,"fetch:error",{reason:t instanceof Error?t.message:t+"",error:t}),t instanceof Error&&"AbortError"===t.name)throw Error("Fetch aborted for "+r);if(t instanceof Error&&!0===t.isFetchStatusError)throw t;throw Error(`Fetch failed for ${r}: ${t instanceof Error?t.message:t+""}`)}finally{u&&clearTimeout(u),e.me&&a&&e.me.removeEventListener("fetch:abort",a)}}async parseURL(t,e,n){const r=await e.evaluate(t,n);if("string"!=typeof r||!r){const e=t;if(null==r&&"identifier"===e?.type&&e.name)throw Error(`fetch: URL expression "${e.name}" evaluated to ${r+""} \u2014 check the variable is set, or quote it if you meant a literal URL (fetch 'https://example.com/path')`);throw Error("fetch: URL must be a non-empty string")}return r}parseResponseType(t){if(!t)return"text";if(("identifier"===t.type||"expression"===t.type)&&t.name){const e=t.name.toLowerCase();if("object"===e)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(e))return"arraybuffer"===e?"arrayBuffer":e;if(_s.has(e))return e;throw Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(t,e,n){if(!t)return{};const r=await e.evaluate(t,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const i={};return"method"in r&&(i.method=(r.method+"").toUpperCase()),"headers"in r&&(i.headers=this.parseHeaders(r.headers)),"body"in r&&(i.body=this.parseBody(r.body)),"credentials"in r&&(i.credentials=r.credentials),"mode"in r&&(i.mode=r.mode),"cache"in r&&(i.cache=r.cache),i}parseHeaders(t){if(t instanceof Headers)return t;const e=new Headers;if("object"==typeof t&&null!==t)for(const[n,r]of Object.entries(t))e.set(n,r+"");return e}parseBody(t){return null==t?null:t instanceof FormData||t instanceof Blob||t instanceof ArrayBuffer||t instanceof URLSearchParams||"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):t+""}async handleResponse(t,e,n){switch(e){case"response":return t;case"json":return t.json();case"html":return this.parseHTML(await t.text());case"blob":return t.blob();case"arrayBuffer":return t.arrayBuffer();case"text":return t.text();default:{const r=_s.get(e);return r?r.handler(t,n):t.text()}}}parseHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),n=document.createDocumentFragment();return Array.from(e.body.childNodes).forEach(t=>n.appendChild(t.cloneNode(!0))),1===n.childNodes.length&&gt(n.firstChild)?n.firstChild:n}dispatchEvent(t,e,n){t.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,cancelable:!0}))}};return yo(e,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"async",compatibility:"standard"}),po(e,r),i=e})();const Zs=vo(Ws);async function Js(t,e,n){const r=await e.evaluate(t,n),i=Array.isArray(r)?r[0]:r;return gt(i)?i:null}async function Ks(t,e,n,r){if(!t)return null;const i=t,o=i.type;if(r.nodeWriters&&o){const e=it(o);if(e)return{kind:"node-write",node:t,writer:e}}if(r.selectorSource&&"selector"===o&&"string"==typeof i.value)return{kind:"selector",selector:i.value};const s=await async function(t,e,n,r){const i=t;if("attributeAccess"===i?.type)return{elements:await r(),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const t=await Js(i.right,e,n);if(t)return{elements:[t],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const t=await Js(i.object,e,n);if(t)return{elements:[t],name:i.property.attributeName}}return null}(t,e,n,r.scopeElements);if(s)return{kind:"attribute",elements:s.elements,name:s.name};const a=await vs(t,e,n);if(a)return r.styleSplit&&a.property.startsWith("*")?{kind:"style",element:a.element,property:a.property.substring(1)}:{kind:"property",target:a};if(r.bareReference&&("identifier"===o||"variable"===o||"symbol"===o)&&"string"==typeof i.name){const t=i.scope;return{kind:"variable",name:i.name,scope:"element"===t||"global"===t?t:void 0}}return null}const Xs=vo((()=>{let t,e,n=[go({name:"set"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],i=r?.name||r?.value,o=r?.scope,s=await Ks(r,e,n,{scopeElements:()=>this.resolveTargets(t.modifiers.on,e,n),nodeWriters:!0,styleSplit:!0});if(s)return function(t,e){switch(t.kind){case"node-write":return{type:"node-write",node:t.node,value:e,writer:t.writer};case"attribute":return{type:"attribute",elements:t.elements,name:t.name,value:e};case"style":return{type:"style",element:t.element,property:t.property,value:e+""};case"property":return{type:"property",element:t.target.element,property:t.target.property,value:e};default:throw Error(`set: unrequested write-target rung '${t.kind}'`)}}(s,await this.extractValue(t,e,n));if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,t,e,n);if(i)return i}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await e.evaluate(r,n):i,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;if(gt(t)||t instanceof Node)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(gs(a)){const r=bs(a,n);if(r){const i=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(a,t,e,n)}if("string"==typeof a&&Vo(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:i+""}}if("string"==typeof a&&Ro(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"attribute",elements:await this.resolveTargets(t.modifiers.on,e,n),name:r,value:i}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=So(r[1],n),o=await this.extractValue(t,e,n);return{type:"property",element:i,property:r[2],value:o}}}if(gt(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&gt(a[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(t,e,n),scope:"element"===o||"global"===o?o:void 0}}async execute(t,e){switch(t.type){case"variable":return"element"===t.scope?mt(e,t.name,t.value):"global"===t.scope?Et(t.name,t.value,e,"global"):Et(t.name,t.value,e),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":for(const e of t.elements)e.setAttribute(t.name,t.value+"");return Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return hs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Uo(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[n,r]of Object.entries(t.properties))hs(e,n,r);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};case"node-write":return await t.writer(t.node,t.value,e),Object.assign(e,{it:t.value}),{target:t.node.name??"",value:t.value,targetType:"variable"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,n,r){const i=t.object,o=t.property;if(i?.name&&o?.name){const t=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const i=So(t,r),s=await this.extractValue(e,n,r);return{type:"property",element:i,property:o.name,value:s}}}const s=t.object,a=t.computed;if(s){const i=s;let c;if("memberExpression"===i.type&&!i.computed&&"style"===i.property?.name&&i.object){const t=await n.evaluate(i.object,r);c=(t&&"object"==typeof t&&"style"in t?t.style:void 0)??await n.evaluate(s,r)}else c=await n.evaluate(s,r);if(null!=c&&"object"==typeof c){const i=a?await n.evaluate(t.property,r)+"":o?.name||"";if(i)return{type:"member-assignment",container:c,property:i,value:await this.extractValue(e,n,r)}}}return null}async extractValue(t,e,n){if(t.modifiers.to)return e.evaluate(t.modifiers.to,n);const r=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(r>=0&&t.args.length>r+1)return e.evaluate(t.args[r+1],n);if(t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,n){return Eo(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return xo(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const i=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw Error('Invalid "the X of Y" syntax');const[,o,s]=i,a=Eo(s,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:o.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return!1;const e=t;if(!e.type||"string"!=typeof e.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return!1;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Array.isArray(e.elements)&&e.elements.every(gt)&&"value"in e;case"property":return"string"==typeof e.property&&gt(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&gt(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return!1}}};return yo(e,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"data",compatibility:"standard"}),po(e,r),i=e})()),Gs=vo((()=>{let t,e,n=[go({name:"get"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("get command requires an expression argument");const r=t.args[0],i=await e.evaluate(r,n);return i instanceof NodeList&&1===i.length||Array.isArray(i)&&1===i.length?{value:i[0]}:{value:i}}execute(t,e){return e.it=t.value,Object.assign(e,{result:t.value}),{value:t.value}}validate(t){return"object"==typeof t&&null!==t&&"value"in t}};return yo(e,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"data",compatibility:"standard"}),po(e,r),i=e})());function Ys(t){return t&&"object"==typeof t&&t.type||"unknown"}let Qs=(()=>{let t,e,n=[go({name:"increment"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="decrement"===t.commandName?.toLowerCase()?"decrement":"increment",i=await async function(t,e,n,r){if(!t.args||0===t.args.length)throw Error(r+" command requires a target");const i=t.args[0];let o,s,a;const c=Ys(i);if("identifier"===c)o=i.name,i.scope&&(s=i.scope);else if("literal"===c)o=i.value;else{const t=it(c);if(t){const r=await e.evaluate(i,n),s="number"==typeof r?r:null==r?0:Number(r)||0;o=s,a={node:i,writer:t,currentValue:s}}else{const t=await e.evaluate(i,n);o=Array.isArray(t)&&t.length>0?t[0]:t}}let l=1,u=s;for(let r=1;t.args.length>r;r++){const i=t.args[r];if(i&&"literal"===i.type){const t=i.value;"global"===t?u="global":"number"==typeof t&&(l=t)}else if(i&&"literal"!==i.type){const t=await e.evaluate(i,n);"number"==typeof t&&(l=t)}}const f=t.modifiers?.by;if(f){const t=f.value;if("literal"===Ys(f)&&"number"==typeof t)l=t;else if("literal"!==Ys(f)){const t=await e.evaluate(f,n);"number"==typeof t&&(l=t)}}return{target:o,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(t,e,n,r);return{...i,operation:r}}async execute(t,e){const{target:n,property:r,scope:i,amount:o=1,operation:s="increment",customWrite:a}=t;if(a){const t=isFinite(o)?o:1,n="increment"===s?a.currentValue+t:a.currentValue-t;return await a.writer(a.node,n,e),Object.assign(e,{it:n}),n}const c=function(t,e,n,r){if("number"==typeof t)return t;if(gt(t)){const n=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?vt(n.getAttribute(e)):vt(n[e]):vt(n.value||n.textContent)}return"string"==typeof t?"element"===n?vt(wt(t,r,"element")):"global"===n?vt(wt(t,r,"global")):t.includes(".")?function(t,e){const n=t.split("."),r=n[1],i=xt(n[0],e);return i?vt(i[r]):0}(t,r):vt("me"===t&&r.me?r.me.value||0:"it"===t?r.it||0:"you"===t&&r.you?r.you.value||0:wt(t,r)):vt(t)}(n,r,i,e);let l;if(isNaN(c))l=NaN;else{const t=isFinite(o)?o:1;l="increment"===s?c+t:c-t}return function(t,e,n,r,i){if(gt(t)){const n=t;return void(e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?n.setAttribute(e,r+""):n[e]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof t){if("element"===n)return void Et(t,r,i,"element");if("global"===n)return void Et(t,r,i,"global");if(t.includes("."))return void function(t,e,n){const r=t.split("."),i=r[1],o=xt(r[0],n);o&&(o[i]=e)}(t,r,i);if("me"===t&&i.me)return void(i.me.value=r);if("it"===t)return void Object.assign(i,{it:r});if("you"===t&&i.you)return void(i.you.value=r);Et(t,r,i)}}(n,r,i,l,e),Object.assign(e,{it:l}),l}};return yo(e,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"data",compatibility:"standard"}),po(e,r),i=e})();const ta=vo(Qs),ea=vo(Qs),na=vo((()=>{let t,e,n=[go({name:"default"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("default command requires a target");const r=await this.extractValue(t,e,n),i=t.args[0],o=function(t){if("contextReference"!==t?.type)return null;const e=t.name;return"string"!=typeof e?null:e.startsWith(":")?{name:e.slice(1),scope:"element"}:e.startsWith("$")?{name:e.slice(1),scope:"global"}:null}(i);if(o)return{type:"variable",name:o.name,value:r,scope:o.scope};const s=await Ks(i,e,n,{scopeElements:async()=>n.me?[n.me]:[],bareReference:!0});if(s)return function(t,e){switch(t.kind){case"attribute":return{type:"attribute",elements:t.elements,name:t.name,value:e};case"property":return{type:"property",element:t.target.element,property:t.target.property,value:e};case"variable":{const n=t.name.startsWith("$"),r=n?t.name.slice(1):t.name,i=n?"global":t.scope;return{type:"variable",name:r,value:e,...i?{scope:i}:{}}}default:throw Error(`default: unrequested write-target rung '${t.kind}'`)}}(s,r);const a=await e.evaluate(t.args[0],n);if(gt(a))return{type:"element",element:a,value:r};if(Array.isArray(a)&&gt(a[0]))return{type:"element",element:a[0],value:r};if("string"==typeof a)return{type:"variable",name:a,value:r};throw Error("Invalid target type: "+typeof a)}async extractValue(t,e,n){if(t.modifiers?.to)return e.evaluate(t.modifiers.to,n);const r=t.args[1],i="identifier"===r?.type&&"to"===(r.name+"").toLowerCase();if(i&&t.args.length>=3)return e.evaluate(t.args[2],n);if(!i&&t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('default command requires a value (use "to <value>")')}async execute(t,e){switch(t.type){case"variable":return this.defaultVariable(e,t.name,t.value,t.scope);case"attribute":return this.defaultAttribute(e,t.elements,t.name,t.value);case"property":return this.defaultElementProperty(e,t.element,t.property,t.value);case"element":return this.defaultElementValue(e,t.element,t.value)}}defaultVariable(t,e,n,r){const i=wt(e,t,r);return null!=i?{target:e,value:n,wasSet:!1,existingValue:i,targetType:"variable"}:(Et(e,n,t,r),Object.assign(t,{it:n}),{target:e,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(t,e,n,r){if(0===e.length)throw Error("No element context available for attribute default");const i=e.filter(t=>null===t.getAttribute(n));if(0===i.length)return{target:"@"+n,value:r,wasSet:!1,existingValue:e[0].getAttribute(n),targetType:"attribute"};for(const t of i)t.setAttribute(n,r+"");return Object.assign(t,{it:r}),{target:"@"+n,value:r,wasSet:!0,targetType:"attribute"}}defaultElementProperty(t,e,n,r){const i=function(t,e){if(e.startsWith("@"))return t.getAttribute(e.substring(1));switch(e){case"textContent":return t.textContent;case"innerHTML":return t.innerHTML;case"innerText":return t.innerText;case"id":return t.id;case"className":return t.className;case"value":return"value"in t?t.value:void 0;case"checked":return"checked"in t?t.checked:void 0}if(e.includes(".")){const n=e.split(".");let r=t;for(const t of n){if(null==r)break;r=r[t]}return r}return e.includes("-")||e in t.style?t.style.getPropertyValue(e)||t.style[e]:t[e]}(e,n);return ms(i)?(hs(e,n,r),Object.assign(t,{it:r}),{target:n,value:r,wasSet:!0,targetType:"property"}):{target:n,value:r,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(t,e,n){const r=function(t){return"value"in t?t.value:t.textContent}(e);return ms(r)?(function(t,e){"value"in t?t.value=e+"":t.textContent=e+""}(e,n),Object.assign(t,{it:n}),{target:"element",value:n,wasSet:!0,targetType:"element"}):{target:"element",value:n,wasSet:!1,existingValue:r,targetType:"element"}}};return yo(e,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"data",compatibility:"standard"}),po(e,r),i=e})());function ra(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e||"SELECT"===e}const ia=vo((()=>{let t,e,n=[go({name:"clear"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.args?.[0],i=r?.type,o=r?.name;if(r&&("variable"===i||"identifier"===i&&"string"==typeof o))try{const t=await e.evaluate(r,n);if(!gt(t)&&!Array.isArray(t))return{type:"variable",name:o}}catch{return{type:"variable",name:o}}return{type:"form-fields",targets:await Ao(t.args,e,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if("variable"===t.type)return e.locals.set(t.name,null),void Object.assign(e,{it:null});for(const e of t.targets)ra(e)&&("SELECT"===e.tagName?e.selectedIndex=-1:e.value="")}validate(t){if("object"!=typeof t||null===t)return!1;if("variable"===t.type)return"string"==typeof t.name;if("form-fields"===t.type){const e=t.targets;return Array.isArray(e)&&e.every(t=>gt(t))}return!1}};return yo(e,"ClearCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"data",compatibility:"standard"}),po(e,r),i=e})());function oa(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e||"false"!==e&&("null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0)}let sa=(()=>{let t,e,n=[go({name:"trigger"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",i=r;if(!t.args?.length)throw Error(i+" command requires an event name");const o=t=>t?.type||"unknown",s=t.args[0];let a,c,l;if("functionCall"===o(s)||"callExpression"===o(s)){a=s.name||s.callee?.name;const t=s.args||s.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===o(s)||"keyword"===o(s))a=s.name;else{const t=await e.evaluate(s,n);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,n,i);else{const r=t.args.findIndex((t,e)=>{if(0===e)return!1;const n=t.name||t.value;return"on"===n||"to"===n});if(-1!==r&&t.args.length-1>r){const o=t.args.slice(r+1),s=o.findIndex(t=>"with"===(t.name||t.value)),a=-1===s?o:o.slice(0,s);l=await this.resolveTargets(a,e,n,i)}else{if(!n.me)throw Error(i+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(n);e.it=n}async resolveTargets(t,e,n,r){const i=[];for(const r of t){const t=await e.evaluate(r,n);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&n.me)i.push(n.me);else if("you"===t&&n.you)i.push(n.you);else if("it"===t&&n.it)i.push(n.it);else if(gt(t))i.push(t);else if(t instanceof NodeList)i.push(...Array.from(t).filter(gt));else if(Array.isArray(t))i.push(...t.filter(gt));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);i.push(...Array.from(e).filter(gt));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);i.push(t)}else i.push(document);else i.push(window)}if(!i.length)throw Error(r+": no valid targets");return i}async parseEventDetail(t,e,n){if(!t?.length)return;if(1===t.length){const r=t[0];if("objectLiteral"!==r?.type)return await e.evaluate(r,n)}const r={};for(const i of t){const t=await e.evaluate(i,n);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,n]=t.split(":",2);r[e.trim()]=oa(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:!0,cancelable:!0,composed:!1},i=t.findIndex(t=>"with"===(t.name||t.value));if(-1===i)return r;for(const o of t.slice(i+1)){const t=await e.evaluate(o,n);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?r.bubbles=!0:"nobubbles"===e?r.bubbles=!1:"cancelable"===e?r.cancelable=!0:"nocancelable"===e?r.cancelable=!1:"composed"===e&&(r.composed=!0)}}return r}};return yo(e,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"event",compatibility:"standard"}),po(e,r),i=e})();const aa=vo(sa),ca=vo(sa),la=vo((()=>{let t,e,n=[go({name:"go"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{args:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{args:[]}}async execute(t,e){const{args:n}=t;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,e),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,e),type:"scroll"}}isUrlNavigation(t){return-1!==t.findIndex(t=>"url"===t)}isBareUrl(t){return!!t.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(t)}findBareUrl(t){for(const e of t)if("to"!==e&&"the"!==e)return"string"==typeof e&&this.isBareUrl(e)?e:null;return null}async navigateToBareUrl(t,e){if(e.includes("new")&&e.includes("window")){if("undefined"!=typeof window&&window.open){const e=window.open(t,"_blank");e?.focus&&e.focus()}}else t.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=t):"undefined"!=typeof window&&(window.location.assign?.(t)??(window.location.href=t));return t}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(t,e){const n=t.findIndex(t=>"url"===t),r=t[n+1];if(!r)throw Error('URL is required after "url" keyword');const i="string"==typeof r?r:r+"",o=t.includes("new")&&t.includes("window");if(!this.isValidUrl(i))throw Error(`Invalid URL: "${i}"`);if(o){if("undefined"!=typeof window&&window.open){const t=window.open(i,"_blank");t?.focus&&t.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(t){try{return t.startsWith("/")||t.startsWith("#")||new URL(t),!0}catch{return!1}}async scrollToElement(t,e){const n=this.parseScrollPosition(t),r=this.parseScrollTarget(t),i=this.parseScrollOffset(t),o=!t.includes("instantly"),s=this.resolveScrollTarget(r,e);if(!s)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const t=o?"smooth":"instant",e=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){s.scrollIntoView?.({behavior:t,block:e,inline:r});const{x:o,y:a}=this.calculateScrollPosition(s,n,i);window.scrollTo?.({left:o,top:a,behavior:t})}else s.scrollIntoView?.({behavior:t,block:e,inline:r})}return s}mapVerticalPosition(t){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[t]||"start"}mapHorizontalPosition(t){return{left:"start",center:"center",right:"end",nearest:"nearest"}[t]||"nearest"}parseScrollPosition(t){const e={vertical:"top",horizontal:"nearest"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,o=!1;for(const s of t)"string"==typeof s&&(n.includes(s)?(e.vertical=s,i=!0):r.includes(s)&&(e.horizontal=s,o=!0));return o&&!i&&(e.vertical="nearest"),e}parseScrollTarget(t){const e=t.findIndex(t=>"of"===t);if(-1!==e&&t.length>e+1){let n=t[e+1];return"the"===n&&t.length>e+2&&(n=t[e+2]),n}for(const e of t)if("object"==typeof e&&e&&e.nodeType)return e;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const e of t)if("string"==typeof e&&!n.includes(e)&&(e.startsWith("#")||e.startsWith(".")||e.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(e)))return e;return"body"}parseScrollOffset(t){for(let e=0;t.length>e;e++){const n=t[e];if("string"==typeof n){const t=n.match(/^([+-]?\d+)(px)?$/);if(t)return parseInt(t[1],10)}if(("+"===n||"-"===n)&&t.length>e+1){const r=t[e+1],i="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(t,e){if("object"==typeof t&&t&&t.nodeType)return t;const n="string"==typeof t?t:t+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&gt(e.me))return e.me;if("it"===n&&gt(e.it))return e.it;if("you"===n&&gt(e.you))return e.you;const r=wt(n,e);if(gt(r))return r;if("undefined"!=typeof document)try{const t=document.querySelector(n);if(t)return t}catch{try{const t=document.getElementsByTagName(n);if(t.length>0)return t[0]}catch{}}return null}calculateScrollPosition(t,e,n){if("undefined"==typeof window||!t.getBoundingClientRect)return{x:0,y:0};const r=t.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,o=window.pageYOffset||document.documentElement?.scrollTop||0,s=window.innerWidth||800,a=window.innerHeight||600;let c=i,l=o;switch(e.horizontal){case"left":c=r.left+i;break;case"center":c=r.left+i+r.width/2-s/2;break;case"right":c=r.right+i-s}switch(e.vertical){case"top":l=r.top+o+n;break;case"middle":l=r.top+o+r.height/2-a/2+n;break;case"bottom":l=r.bottom+o-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}};return yo(e,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"navigation",compatibility:"standard"}),po(e,r),i=e})());function ua(t,e){if("boolean"==typeof t)return t;if("function"==typeof t)return!0;if(t instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof t){if("me"===t)return!!e.me;if("it"===t)return!!e.it;if("you"===t)return!!e.you;const n=wt(t,e);return void 0!==n?!!n:!!t}return!!t}const fa=vo((()=>{let t,e,n=[go({name:"if"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="unless"===t.commandName?.toLowerCase()?"unless":"if";if(!t.args||0===t.args.length)throw Error(r+" command requires a condition to evaluate");let i,o;if("unless"===r){if(2>t.args.length)throw Error("unless command requires a condition and at least one command");i=t.args[1]}else if(t.args.length>=2&&t.args[1]?(i=t.args[1],o=3>t.args.length?void 0:t.args[2]):t.modifiers?.then&&(i=t.modifiers.then,o=t.modifiers.else),!i)throw Error('if command requires "then" branch with commands');return{mode:r,condition:await e.evaluate(t.args[0],n),thenCommands:i,elseCommands:o}}async execute(t,e){const{mode:n,condition:r,thenCommands:i,elseCommands:o}=t,s=ua(r,e);let a,c;return("unless"===n?!s:s)?(a="then",c=await this.executeCommandsOrBlock(i,e)):o&&"if"===n?(a="else",c=await this.executeCommandsOrBlock(o,e)):a="none",{mode:n,conditionResult:s,executedBranch:a,result:c}}async executeCommandsOrBlock(t,e){return"block"===t?.type?this.executeBlock(t,e):this.executeCommands(Array.isArray(t)?t:[t],e)}async executeBlock(t,e){const n=e.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let r;if(t.commands?.length)for(const i of t.commands)r=await n(i,e);return r}async executeCommands(t,e){let n;for(const r of t)if(r?.execute)n=await r.execute(e);else if("function"==typeof r)n=await r();else if(r&&"object"==typeof r&&"string"==typeof r.type){const t=e.locals.get("_runtimeExecute");if(!t)throw Error("Runtime execute function not available");n=await t(r,e)}else n=r;return n}};return yo(e,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),i=e})()),da=fa,ha=fa;let ma=(()=>{let t,e,n=[go({name:"repeat"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r;if(t.modifiers?.index){const i=await e.evaluate(t.modifiers.index,n);"string"==typeof i&&(r=i)}let i,o=t.modifiers?.block||t.modifiers?.commands;if(!o){const e=[];for(let n=t.args.length-1;n>=0;n--){const r=t.args[n];if("block"===r?.type&&r.commands&&(e.unshift(r),2===e.length))break}2===e.length?(o=e[0],i=e[1]):1===e.length&&(o=e[0])}const s=t.args[0],a="identifier"===s?.type?s.name:null,c=!!t.modifiers?.bottomTested&&await e.evaluate(t.modifiers.bottomTested,n);if("for"===a||t.modifiers?.for){const s=t.args[1],a=s?.value||s?.name,c=t.args[2]?await e.evaluate(t.args[2],n):void 0;if(!a||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:a,collection:Array.isArray(c)?c:[c],indexVariable:r,commands:o,elseCommands:i}}if("times"===a||t.modifiers?.times){const s=t.args[1],a=s?await e.evaluate(s,n):void 0,c="number"==typeof a?a:parseInt(a+"",10);if(isNaN(c))throw Error("times loops require a count number");return{type:"times",count:c,indexVariable:r,commands:o,elseCommands:i}}if("while"===a||t.modifiers?.while){const e=t.args[1]||t.modifiers?.while;if(!e)throw Error("while loops require a condition");return{type:"while",condition:e,indexVariable:r,commands:o,elseCommands:i,bottomTested:c}}if("until"===a&&t.modifiers?.from||"until-event"===a){const s=t.args[1],a=s?.value||s?.name;if(!a)throw Error("until-event loops require an event name");let c=n.me;if(t.args[2]){const r=t.args[2];if("identifier"===r?.type&&"document"===r.name)c=document;else if("identifier"===r?.type&&"window"===r.name&&"undefined"!=typeof window)c=window;else{const r=await e.evaluate(t.args[2],n);r instanceof EventTarget?c=r:"document"===r?c=document:"undefined"!=typeof window&&r===window&&(c=window)}}return{type:"until-event",eventName:a,eventTarget:c,indexVariable:r,commands:o,elseCommands:i}}if("until"===a||t.modifiers?.until){const e=t.args[1]||t.modifiers?.until;if(!e)throw Error("until loops require a condition");return{type:"until",condition:e,indexVariable:r,commands:o,elseCommands:i,bottomTested:c}}if("forever"===a||t.modifiers?.forever)return{type:"forever",indexVariable:r,commands:o,elseCommands:i};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(t,e){const{type:n,variable:r,collection:i,condition:o,count:s,indexVariable:a,commands:c,elseCommands:l,bottomTested:u,eventName:f,eventTarget:d}=t;let h,m;switch(n){case"for":({config:h,iterCtx:m}=function(t,e,n){return{config:{type:"for",shouldContinue:t=>(t.collection?.length??0)>t.index,beforeIteration:(t,e)=>{t.item=t.collection?.[t.index],t.itemVariable&&e.locals&&e.locals.set(t.itemVariable,t.item)}},iterCtx:{index:0,collection:t,itemVariable:e,indexVariable:n}}}(i,r,a));break;case"times":({config:h,iterCtx:m}=function(t,e){return{config:{type:"times",shouldContinue:t=>(t.count??0)>t.index,beforeIteration:(t,e)=>{Object.assign(e,{it:t.index+1})}},iterCtx:{index:0,count:t,indexVariable:e}}}(s,a));break;case"while":({config:h,iterCtx:m}=function(t,e,n,r){return{config:{type:"while",shouldContinue:()=>e(t,n)},iterCtx:{index:0,conditionExpr:t,indexVariable:r}}}(o,ua,e,a));break;case"until":({config:h,iterCtx:m}=function(t,e,n,r){return{config:{type:"until",shouldContinue:()=>!e(t,n)},iterCtx:{index:0,conditionExpr:t,indexVariable:r}}}(o,ua,e,a));break;case"until-event":({config:h,iterCtx:m}=function(t,e,n){const r={index:0,eventFired:!1,indexVariable:n};return{config:{type:"until-event",shouldContinue:t=>!t.eventFired,eventSetup:{eventName:t,target:e,onEvent:()=>{r.eventFired=!0}}},iterCtx:r}}(f,d,a));break;case"forever":({config:h,iterCtx:m}=function(t,e=1e4){return{config:{type:"forever",maxIterations:e,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:t}}}(a));break;default:throw Error("Unknown repeat type: "+n)}if(u){const t=h.shouldContinue;h.shouldContinue=async e=>0===e.index||await t(e)}try{const t=await async function(t,e,n,r,i){const o=t.maxIterations??1e4;let s,a=0,c=!1;t.eventSetup&&t.eventSetup.target.addEventListener(t.eventSetup.eventName,t.eventSetup.onEvent,{once:!0});try{for(;o>a&&await t.shouldContinue(r);){t.beforeIteration&&await t.beforeIteration(r,n),r.indexVariable&&n.locals&&n.locals.set(r.indexVariable,a);try{s=await i(e,n)}catch(e){if(e instanceof Error){if(e.message.includes("BREAK")){c=!0;break}if(e.message.includes("CONTINUE")){a++,r.index=a,"until-event"===t.type&&await new Promise(t=>setTimeout(t,0));continue}}throw e}a++,r.index=a,"until-event"===t.type&&await new Promise(t=>setTimeout(t,0))}}finally{t.eventSetup&&!r.eventFired&&t.eventSetup.target.removeEventListener(t.eventSetup.eventName,t.eventSetup.onEvent)}return{iterations:a,lastResult:s,interrupted:c}}(h,c,e,m,this.executeCommands.bind(this));if(0===t.iterations&&!t.interrupted&&l){const t=await this.executeCommands(l,e);return Object.assign(e,{it:t}),{type:n,iterations:0,completed:!0,lastResult:t}}return Object.assign(e,{it:t.lastResult}),{type:n,iterations:t.iterations,completed:!t.interrupted,lastResult:t.lastResult,interrupted:t.interrupted}}catch(t){if(t instanceof Error&&(t.message.includes("BREAK")||t.message.includes("CONTINUE")))return{type:n,iterations:0,completed:!0,interrupted:t.message.includes("BREAK")};throw t}}async executeCommands(t,e){if(t&&"object"==typeof t&&"block"===t.type){const n=t,r=e.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let i;if(n.commands)for(const t of n.commands)i=await r(t,e);return i}if(Array.isArray(t)){let n;for(const r of t)n="function"==typeof r?await r(e):r&&"function"==typeof r.execute?await r.execute(e):r;return n}return"function"==typeof t?await t(e):t}};return yo(e,"RepeatCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),i=e})();const pa=vo(ma);class ya{async parseInput(t,e,n){return{signalType:this.signalType}}async execute(t,e){const n=Error(this.errorMessage);throw n[this.errorFlag]=!0,"exit"===this.signalType&&(n.returnValue=void 0,n.timestamp=Date.now()),n}}let ga=(()=>{let t,e,n=[go({name:"break"})],r=[],i=ya;var o=e=class extends i{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}get metadata(){return o.metadata}};return yo(e,"BreakCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),o=e})();const ba=vo(ga);let va=(()=>{let t,e,n=[go({name:"continue"})],r=[],i=ya;var o=e=class extends i{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}get metadata(){return o.metadata}};return yo(e,"ContinueCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),o=e})();const wa=vo(va),Ea=vo((()=>{let t,e,n=[go({name:"halt"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(t.args&&t.args.length>0){const r=t.args[0];return!r||"the"!==r.name&&"the"!==r.value?{target:await e.evaluate(t.args[0],n)}:{target:n.event}}return{}}async execute(t,e){let n=t.target;if(("the"===n&&e.event||"object"==typeof n&&null!==n&&"the"===n.target&&e.event)&&(n=e.event),this.isEvent(n)){const t=n;return t.preventDefault(),t.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in e&&(e.halted=!0);const r=Error("HALT_EXECUTION");throw r.isHalt=!0,r}isEvent(t){return null!==t&&"object"==typeof t&&"preventDefault"in t&&"stopPropagation"in t}};return yo(e,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),i=e})()),xa=vo((()=>{let t,e,n=[go({name:"return"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{value:await e.evaluate(t.args[0],n)}:{value:void 0}}async execute(t,e){const{value:n}=t;"returnValue"in e&&(e.returnValue=n),Object.assign(e,{it:n});const r=Error("RETURN_VALUE");throw r.isReturn=!0,r.returnValue=n,r}};return yo(e,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),i=e})());let ka=(()=>{let t,e,n=[go({name:"exit"})],r=[],i=ya;var o=e=class extends i{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}get metadata(){return o.metadata}};return yo(e,"ExitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),o=e})();const Sa=vo(ka),Ta=vo((()=>{let t,e,n=[go({name:"throw"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("throw command requires a message or error object");return{message:await e.evaluate(t.args[0],n)}}async execute(t,e){const{message:n}=t;let r;throw r=n instanceof Error?n:Error("string"==typeof n?n:n+""),r}};return yo(e,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"control-flow",compatibility:"standard"}),po(e,r),i=e})()),Aa=vo((()=>{let t,e,n=[go({name:"call"})],r=[];var i=e=class{get metadata(){return i.metadata}parseInput(t,e,n){if(!t.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:t.args[0]})}async execute(t,e){const{expression:n}=t,r=e.locals?.get("__evaluator"),i=r?await r.evaluate(n,e):await or(n,e);let o,s,a=!1;return"function"==typeof i?(s="function",o=i(),o instanceof Promise&&(a=!0,o=await o)):i instanceof Promise?(s="promise",a=!0,o=await i):(s="value",o=i),Object.assign(e,{it:o,result:o}),{result:o,wasAsync:a,expressionType:s}}};return yo(e,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"execution",compatibility:"standard"}),po(e,r),i=e})());class Ca{constructor(){this.name="pseudo-command"}get metadata(){return Ca.metadata}async parseInput(t,e,n){if(1===t.args.length&&"objectLiteral"===t.args[0].type){const r=t.args[0].properties||[];let i,o,s="",a=[];for(const t of r){const r=t.value;switch(t.key?.name||t.key?.value){case"methodName":s=r?.value||await e.evaluate(r,n)+"";break;case"methodArgs":"arrayLiteral"===r?.type&&r.elements?a=await Promise.all(r.elements.map(t=>e.evaluate(t,n))):"literal"===r?.type&&Array.isArray(r.value)&&(a=await Promise.all(r.value.map(t=>e.evaluate(t,n))));break;case"preposition":const t=r?.value;t&&"null"!==t&&(i=t);break;case"target":case"targetExpression":o=await e.evaluate(r,n)}}if(!s)throw Error("pseudo-command requires method name");if(null==o)throw Error("pseudo-command requires a target expression");return{methodName:s,methodArgs:a,preposition:i,targetExpression:o}}if(2>t.args.length)throw Error("pseudo-command requires method name and target expression");const r=await e.evaluate(t.args[0],n)+"",i=Array.isArray(t.args[1])?await Promise.all(t.args[1].map(t=>e.evaluate(t,n))):[];let o,s;const a=["from","on","with","into","at","to"];for(const r of a)if(t.modifiers?.[r]){s=r,o=await e.evaluate(t.modifiers[r],n);break}if(o||3>t.args.length||(o=await e.evaluate(t.args[2],n)),!o)throw Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:s,targetExpression:o}}async execute(t,e){const{methodName:n,methodArgs:r,targetExpression:i}=t;try{const t=await this.resolveTarget(i,e);if(null==t)throw Error("Target expression resolved to "+t);const o=this.resolveMethod(t,n);if(!o)throw Error(`Method "${n}" not found on target object`);if("function"!=typeof o)throw Error(`"${n}" is not a function (it's a ${typeof o})`);const s=await this.executeMethod(o,t,r);return e.locals.set("result",s),Object.assign(e,{it:s}),{result:s,methodName:n,target:t}}catch(t){throw Error("Pseudo-command failed: "+(t instanceof Error?t.message:t+""))}}async resolveTarget(t,e){return"object"==typeof t&&null!==t?t:"string"==typeof t?e.locals.has(t)?e.locals.get(t):e.variables?.has(t)?e.variables.get(t):e.globals.has(t)?e.globals.get(t):"me"===t&&e.me?e.me:"it"===t&&e.it?e.it:"document"===t?"undefined"!=typeof document?document:null:"window"===t?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(t,e):t}resolvePropertyPath(t,e){const n=t.split(".");let r="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;e.locals.has(n[0])?(r=e.locals.get(n[0]),n.shift()):e.variables?.has(n[0])?(r=e.variables.get(n[0]),n.shift()):e.globals.has(n[0])&&(r=e.globals.get(n[0]),n.shift());for(const t of n){if(null==r)return null;r=r[t]}return r}resolveMethod(t,e){if(!t)return null;if(e in t)return t[e];const n=e.split(".");let r=t;for(let t=0;n.length>t;t++){const e=n[t];if(null==r)return null;if(!(e in r))return null;if(r=r[e],t===n.length-1&&"function"==typeof r)return r}return null}async executeMethod(t,e,n){try{const r=t.apply(e,n);return r&&"object"==typeof r&&"then"in r?await r:r}catch(t){throw Error("Method execution failed: "+(t instanceof Error?t.message:t+""))}}}Ca.metadata=bo({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",compatibility:"standard",sideEffects:["method-execution"]});const $a=vo((()=>{let t,e,n=[go({name:"focus"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ao(t.args,e,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.focus()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return yo(e,"FocusCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),po(e,r),i=e})()),Oa=vo((()=>{let t,e,n=[go({name:"blur"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ao(t.args,e,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.blur()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>gt(t))}};return yo(e,"BlurCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"execution",compatibility:"standard"}),po(e,r),i=e})());function ja(t){return gt(t)?t:t+""}class Na{constructor(t){this.position=t}concat(t,e){const n=null==t?"":t+"",r=e+"";return"append"===this.position?n+r:r+n}pushInto(t,e){return"append"===this.position?t.push(e):t.unshift(e),t}async parseInput(t,e,n){if(!t.args?.length)throw Error(this.name+" requires content");const r=await e.evaluate(t.args[0],n),i=t.modifiers?.to??t.target;if(!i)return{kind:"implicit",content:r};const o=await Ks(i,e,n,{scopeElements:async()=>gt(n.me)?[n.me]:[],selectorSource:!0,bareReference:!0});if(o)return function(t,e){switch(t.kind){case"selector":return{kind:"selector",selector:t.selector,content:e};case"attribute":return{kind:"attribute",elements:t.elements,name:t.name,content:e};case"property":return{kind:"property",property:t.target,content:e};case"variable":return{kind:"variable",name:t.name,scope:t.scope,content:e};default:throw Error(`unrequested write-target rung '${t.kind}'`)}}(o,r);const s=await e.evaluate(i,n),a=function(t){if(gt(t))return[t];if(Array.isArray(t)&&t.length>0&&t.every(t=>gt(t)))return t;if(t&&"object"==typeof t&&"number"==typeof t.length&&"function"==typeof t.item){const e=Array.from(t).filter(t=>gt(t));return e.length?e:null}return null}(s);return a?{kind:"elements",elements:a,content:r}:{kind:"value",target:s,content:r}}async execute(t,e){switch(t.kind){case"selector":return this.done(e,this.insertIntoSelector(t.selector,t.content));case"elements":return this.done(e,this.insertIntoEach(t.elements,t.content));case"attribute":{for(const e of t.elements)e.setAttribute(t.name,this.concat(e.getAttribute(t.name),t.content));const n=t.elements[0]?.getAttribute(t.name)??this.concat(null,t.content);return Object.assign(e,{it:n}),{target:"@"+t.name,value:n,targetType:"attribute"}}case"property":{const n=ws(t.property),r=this.combineValue(n,t.content);return gt(n)||Es(t.property,r),Object.assign(e,{it:r}),{target:t.property.element,value:r,targetType:"property"}}case"variable":return this.executeVariable(t,e);case"value":{const n=this.combineValue(t.target,t.content,!0);return Object.assign(e,{it:n}),{target:t.target,value:n,targetType:this.targetTypeOf(t.target)}}case"implicit":return this.execImplicit(e,t.content)}}insertIntoSelector(t,e){return this.insertIntoEach(St(t),e)}insertIntoEach(t,e){const n=ja(e);for(const e of t)Yo(e,n,this.position);return t}combineValue(t,e,n=!1){if(Array.isArray(t))return this.pushInto(t,e);if(t instanceof Set)return t.add(e),t;if(gt(t))return Yo(t,ja(e),this.position),t;if(n&&null!=t&&"string"!=typeof t&&"number"!=typeof t)throw Error(`Unable to ${this.name} a value!`);return this.concat(t,e)}targetTypeOf(t){return Array.isArray(t)?"array":t instanceof Set?"set":gt(t)?"element":"result"}executeVariable(t,e){if("me"===t.name||"you"===t.name){const n="me"===t.name?e.me:e.you;if(gt(n))return Yo(n,ja(t.content),this.position),Object.assign(e,{it:n}),{target:n,value:n,targetType:"element"}}if("it"===t.name||"result"===t.name)return this.execImplicit(e,t.content);const n=wt(t.name,e,t.scope),r=this.combineValue(n,t.content);return Array.isArray(n)||n instanceof Set||gt(n)||Et(t.name,r,e,t.scope),Object.assign(e,{it:r}),{target:t.name,value:r,targetType:this.targetTypeOf(n)}}execImplicit(t,e){const n=t.it??t.result,r=this.combineValue(n,e);return Object.assign(t,{it:r,result:r}),{target:"result",value:r,targetType:this.targetTypeOf(n)}}done(t,e){const n=1===e.length?e[0]:e;return Object.assign(t,{it:n}),{target:n,value:n,targetType:"element"}}}const Ra=vo((()=>{let t,e,n=[go({name:"append"})],r=[],i=Na;var o=e=class extends i{get metadata(){return o.metadata}constructor(){super("append")}};return yo(e,"AppendCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({description:"Add content to the end of a string, array, Set, 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','append " (edited)" to #title\'s textContent'],sideEffects:["data-mutation","dom-mutation"],category:"content",compatibility:"standard"}),po(e,r),o=e})()),La=vo((()=>{let t,e,n=[go({name:"prepend"})],r=[],i=Na;var o=e=class extends i{get metadata(){return o.metadata}constructor(){super("prepend")}};return yo(e,"PrependCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),o=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=bo({description:"Add content to the start of a string, array, Set, or HTML element",syntax:["prepend <content>","prepend <content> to <target>"],examples:['prepend "Hello"','prepend "World" to greeting',"prepend item to myArray",'prepend "<p>First</p>" to #content'],sideEffects:["data-mutation","dom-mutation"],category:"content",compatibility:"lokascript-extension"}),po(e,r),o=e})()),Ia=vo((()=>{let t,e,n=[go({name:"transition"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("transition requires property and value");let r,i;const o=await e.evaluate(t.args[0],n),s=(t=>Array.isArray(t)||bt(t)?t[0]:t)(o);if(gt(s)||"string"==typeof o&&/^[#.]|^(?:me|it|you)$/.test(o))i=s,r=await e.evaluate(t.args[1],n)+"";else{if(t.args.length>=2)throw Error("transition: target element not found");r=o+""}if(!r)throw Error("transition requires a CSS property");if(!t.modifiers?.to)throw Error('transition requires "to <value>"');let a=await e.evaluate(t.modifiers.to,n);void 0===a&&"identifier"===t.modifiers.to.type&&(a=t.modifiers.to.name);const c={property:r,value:a};return void 0!==i&&(c.target=i),t.modifiers?.over&&(c.duration=await e.evaluate(t.modifiers.over,n)),t.modifiers?.with&&(c.timingFunction=await e.evaluate(t.modifiers.with,n)+""),c}async execute(t,e){let{property:n}=t;const{target:r,value:i,duration:o,timingFunction:s}=t;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const a=Eo(r,e,"transition"),c=rs(o,300),l=getComputedStyle(a).getPropertyValue(n),u=a.style.transition,f=`${n} ${c}ms ${s||"ease"}`;a.style.transition=u?`${u}, ${f}`:f;let d=i+"",h=!1;if("initial"===d||"inherit"===d||"unset"===d||"revert"===d){const t=a.style.getPropertyValue(n);a.style.removeProperty(n),d=getComputedStyle(a).getPropertyValue(n),t&&a.style.setProperty(n,t),h=!0}a.style.setProperty(n,d);const m=await function(t,e,n){return new Promise(r=>{const i=n=>{n.target===t&&n.propertyName===e&&s({completed:!0,cancelled:!1})},o=n=>{n.target===t&&n.propertyName===e&&s({completed:!1,cancelled:!0})},s=Fs(()=>{t.removeEventListener("transitionend",i),t.removeEventListener("transitioncancel",o),clearTimeout(a)},r);t.addEventListener("transitionend",i),t.addEventListener("transitioncancel",o);const a=setTimeout(()=>{s({completed:!0,cancelled:!1})},n+50)})}(a,n,c);return a.style.transition=u,h&&a.style.removeProperty(n),{element:a,property:n,fromValue:l,toValue:d,duration:c,completed:m.completed}}};return yo(e,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Animate CSS properties using CSS transitions",syntax:"transition [<target>] <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition my *opacity to 0 over 200ms","transition #box's *opacity to 0 over 200ms","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"],category:"animation",compatibility:"standard"}),po(e,r),i=e})()),Ma=vo((()=>{let t,e,n=[go({name:"measure"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r,i,o;if(t.args?.length){const o=t.args[0];if("identifier"===o.type&&o.name){const s=o.name.toLowerCase();if("me"===s||"it"===s||"you"===s){const s=await e.evaluate(o,n);if(gt(s)&&(r=s,t.args.length>1)){const r=t.args[1];i="identifier"===r.type?r.name:await e.evaluate(r,n)+""}}else i=o.name}else{const s=await e.evaluate(o,n);if(gt(s)||"string"==typeof s&&/^[#.]/.test(s)){if(r=s,t.args.length>1){const r=t.args[1];i="identifier"===r.type?r.name:await e.evaluate(r,n)+""}}else"string"==typeof s&&(i=s)}}t.modifiers?.set&&(o=await e.evaluate(t.modifiers.set,n)+"");const s={};return void 0!==r&&(s.target=r),void 0!==i&&(s.property=i),void 0!==o&&(s.variable=o),s}async execute(t,e){const n=Eo(t.target,e,"measure"),r=t.property||"width",i=this.getMeasurement(n,r);return t.variable&&e.locals&&e.locals.set(t.variable,i.value),Object.assign(e,{it:i.value}),{result:i.value,wasAsync:!1,element:n,property:r,value:i.value,unit:i.unit,stored:!!t.variable}}getMeasurement(t,e){const n=getComputedStyle(t);if(e.startsWith("*")){const t=n.getPropertyValue(e.substring(1)),r=parseFloat(t);if(!isNaN(r)){const e=t.match(/([a-zA-Z%]+)$/);return{value:r,unit:e?e[1]:""}}return{value:t,unit:""}}const r=e.toLowerCase(),i=t.getBoundingClientRect(),o={width:()=>i.width,height:()=>i.height,top:()=>i.top,left:()=>i.left,right:()=>i.right,bottom:()=>i.bottom,x:()=>t.offsetLeft,y:()=>t.offsetTop,clientwidth:()=>t.clientWidth,"client-width":()=>t.clientWidth,clientheight:()=>t.clientHeight,"client-height":()=>t.clientHeight,offsetwidth:()=>t.offsetWidth,"offset-width":()=>t.offsetWidth,offsetheight:()=>t.offsetHeight,"offset-height":()=>t.offsetHeight,scrollwidth:()=>t.scrollWidth,"scroll-width":()=>t.scrollWidth,scrollheight:()=>t.scrollHeight,"scroll-height":()=>t.scrollHeight,scrolltop:()=>t.scrollTop,"scroll-top":()=>t.scrollTop,scrollleft:()=>t.scrollLeft,"scroll-left":()=>t.scrollLeft,offsettop:()=>t.offsetTop,"offset-top":()=>t.offsetTop,offsetleft:()=>t.offsetLeft,"offset-left":()=>t.offsetLeft};if(o[r])return{value:o[r](),unit:"px"};const s=n.getPropertyValue(e),a=parseFloat(s);if(!isNaN(a)){const t=s.match(/([a-zA-Z%]+)$/);return{value:a,unit:t?t[1]:"px"}}return{value:0,unit:"px"}}};return yo(e,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"animation",compatibility:"standard"}),po(e,r),i=e})()),Pa=vo((()=>{let t,e,n=[go({name:"settle"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r,i;if(t.args&&t.args.length>0){const i=await e.evaluate(t.args[0],n);(gt(i)||"string"==typeof i&&(i.startsWith("#")||i.startsWith(".")||"me"===i||"it"===i||"you"===i))&&(r=i)}t.modifiers?.for&&(i=await e.evaluate(t.modifiers.for,n));const o={};return void 0!==r&&(o.target=r),void 0!==i&&(o.timeout=i),o}async execute(t,e){const{target:n,timeout:r}=t,i=Eo(n,e,"settle"),o=rs(r,5e3),s=Date.now(),a=getComputedStyle(i),c=os(a.transitionDuration),l=os(a.transitionDelay),u=os(a.animationDuration),f=os(a.animationDelay),d=ss(c,l),h=ss(u,f),m=Math.max(d,h);var p,y,g;return{element:i,settled:(await(p=i,y=m,g=o,y>0?new Promise(t=>{const e=t=>{t.target===p&&r({completed:!0,type:"transition"})},n=t=>{t.target===p&&r({completed:!0,type:"animation"})},r=Fs(()=>{p.removeEventListener("transitionend",e),p.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(o)},t);p.addEventListener("transitionend",e),p.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},y+50),o=setTimeout(()=>{r({completed:!1,type:"timeout"})},g)}):Promise.resolve({completed:!0,type:"timeout"}))).completed,timeout:o,duration:Date.now()-s}}};return yo(e,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"],category:"animation",compatibility:"standard"}),po(e,r),i=e})());const qa=vo((()=>{let t,e,n=[go({name:"take"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error('take requires property, "from", and source');const{value:r}=await Wo(t.args[0],e,n),i=r+"";let o;if(2>t.args.length)t.modifiers?.from&&(o=await e.evaluate(t.modifiers.from,n));else{if(!(s=t.args[1])||("identifier"!==s.type||"from"!==s.name)&&"from"!==s.value)throw Error("take syntax: take <property> from <source>");t.args[2]&&(o=await e.evaluate(t.args[2],n))}var s;let a;if(8>t.args.length)t.args.length>3&&(a=await e.evaluate(t.args[3],n));else{const r=[3,4,5,6].map(e=>t.args[e]),i=t=>t?.name??t?.value;"and"===i(r[0])&&"put"===i(r[1])&&"it"===i(r[2])&&"on"===i(r[3])&&t.args[7]&&(a=await e.evaluate(t.args[7],n))}if(!a&&t.modifiers?.on&&(a=await e.evaluate(t.modifiers.on,n)),!a&&t.modifiers?.for&&(a=await e.evaluate(t.modifiers.for,n)),void 0===o&&!i.startsWith("."))throw Error('take requires property, "from", and source');return{property:i,source:o,target:a}}async execute(t,e){const n=t.property.trim();if(n.startsWith(".")){const r=n.substring(1);let i;if(null!=t.source)i=xo(t.source,e);else{const t=e.me?.ownerDocument??("undefined"!=typeof document?document:null);i=t?Array.from(t.querySelectorAll("."+r)):[]}for(const t of i)t.classList.remove(r);const o=xo(t.target,e);if(0===o.length)throw Error("take: no recipient element found");for(const t of o)t.classList.add(r);return{targetElement:o[0],property:t.property,value:r}}const r=Eo(this.firstOf(t.source),e,"take"),i=Eo(t.target?this.firstOf(t.target):void 0,e,"take"),o=this.takeProperty(r,t.property);return this.putProperty(i,t.property,o),{targetElement:i,property:t.property,value:o}}firstOf(t){const e=null!==t&&"object"==typeof t&&"number"==typeof t.length&&"function"==typeof t.item;if(Array.isArray(t)||e){const e=t[0];if(void 0===e)throw Error("take: no matching elements");return e}return t}takeProperty(t,e){const n=e.trim(),r=n.toLowerCase();if("class"===r||"classes"===r){const e=Array.from(t.classList);return t.className="",e}if(n.startsWith(".")){const e=n.substring(1);return t.classList.contains(e)?(t.classList.remove(e),e):null}if(n.startsWith("@")){const e=n.substring(1),r=t.getAttribute(e);return t.removeAttribute(e),r}if(n.startsWith("data-")){const e=t.getAttribute(n);return t.removeAttribute(n),e}if("id"===r){const e=t.id;return t.id="",e}if("title"===r){const e=t.title;return t.title="",e}if("value"===r&&"value"in t){const e=t.value;return t.value="",e}const i=n.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());if(n.includes("-")||i in t.style||n in t.style){let e;return i in t.style?(e=t.style[i],t.style[i]=""):n in t.style?(e=t.style[n],t.style[n]=""):(e=t.style.getPropertyValue(n),t.style.removeProperty(n)),e}const o=t.getAttribute(e);return null!==o?(t.removeAttribute(e),o):null}putProperty(t,e,n){if(null==n)return;const r=e.trim(),i=r.toLowerCase();if("class"===i||"classes"===i)return void(Array.isArray(n)?n.forEach(e=>e&&"string"==typeof e&&t.classList.add(e)):"string"==typeof n&&(t.className=n));if(r.startsWith("."))return void(n&&t.classList.add(r.substring(1)));if(r.startsWith("@"))return void t.setAttribute(r.substring(1),n+"");if(r.startsWith("data-"))return void t.setAttribute(r,n+"");if("id"===i)return void(t.id=n+"");if("title"===i)return void(t.title=n+"");if("value"===i&&"value"in t)return void(t.value=n+"");const o=r.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());r.includes("-")||o in t.style||r in t.style?o in t.style?t.style[o]=n+"":r in t.style?t.style[r]=n+"":t.style.setProperty(r,n+""):t.setAttribute(e,n+"")}};return yo(e,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Move classes, attributes, and properties from one element to another",syntax:["take <class> [from <source>] [for <recipient>]","take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take .active from .tab for me","take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"],category:"animation",compatibility:"standard"}),po(e,r),i=e})()),Ha=vo((()=>{let t,e,n=[go({name:"js"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){let r,i;if(0===t.args.length)throw Error("js command requires JavaScript code");const o=t.args[0],s=t.args[1];if(o&&"literal"===o.type&&"string"==typeof o.value)r=o.value;else{if(!o||void 0===o.value)throw Error("js command requires JavaScript code");r=o.value+""}s&&"arrayLiteral"===s.type&&Array.isArray(s.elements)&&(i=s.elements.map(t=>"string"==typeof t.value?t.value:t.value+"").filter(t=>t&&t.length>0));const a={code:r};return i&&i.length>0&&(a.parameters=i),a}async execute(t,e){const{code:n,parameters:r=[]}=t;if(!n.trim())return{result:void 0,executed:!1,codeLength:n.length,parameters:r,preserveArrayResult:!0};try{const t=this.createExecutionContext(e,r),i=Function(...Object.keys(t),n),o=await i(...Object.values(t));return void 0!==o&&Object.assign(e,{it:o}),{result:o,executed:!0,codeLength:n.length,parameters:r,preserveArrayResult:!0}}catch(t){throw Error("JavaScript execution failed: "+(t instanceof Error?t.message:"Unknown error"))}}createExecutionContext(t,e){return{me:t.me,it:t.it,you:t.you,locals:t.locals,globals:t.globals,variables:t.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...e.reduce((e,n)=>{let r=t.locals?.get(n);return void 0===r&&(r=t.variables?.get(n)),void 0===r&&(r=t[n]),e[n]=r,e},{})}}};return yo(e,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"advanced",compatibility:"standard"}),po(e,r),i=e})()),Ba=vo((()=>{let t,e,n=[go({name:"async"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("async command requires at least one command to execute");return{commands:t.args}}async execute(t,e){const{commands:n}=t,r=Date.now();try{const t=await this.executeCommandsAsync(e,n),i=Date.now()-r;return t.length>0&&Object.assign(e,{it:t[t.length-1]}),{commandCount:n.length,results:t,executed:!0,duration:i}}catch(t){throw Error("Async command execution failed: "+(t instanceof Error?t.message:"Unknown error"))}}async executeCommandsAsync(t,e){const n=[];for(let r=0;e.length>r;r++){const i=e[r];try{const e=await this.executeCommand(i,t);n.push(e),Object.assign(t,{it:e})}catch(t){const n=this.getCommandName(i);throw Error(`Command '${n}' (${r+1}/${e.length}) failed: ${t instanceof Error?t.message:"Unknown error"}`)}}return n}async executeCommand(t,e){if("function"==typeof t)return await t(e);if(t&&"object"==typeof t&&"execute"in t&&"function"==typeof t.execute)return await t.execute(e);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(t){return"function"==typeof t?t.name||"anonymous function":t&&"object"==typeof t?t.name||"unnamed command":"unknown"}};return yo(e,"AsyncCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"],category:"advanced",compatibility:"lokascript-extension"}),po(e,r),i=e})()),Da=vo((()=>{let t,e,n=[go({name:"log"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{values:[]}}async execute(t,e){const n="undefined"!=typeof window?window.console:console;0===t.values.length?n.log():n.log(...t.values)}validate(t){return"object"==typeof t&&null!==t&&Array.isArray(t.values)}};return yo(e,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"utility",compatibility:"standard"}),po(e,r),i=e})()),Va=vo((()=>{let t,e,n=[go({name:"tell"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(2>t.args.length)throw Error("tell command requires a target and at least one command");return{target:await e.evaluate(t.args[0],n),commands:t.args.slice(1)}}async execute(t,e){const{target:n,commands:r}=t,i=xo(n,e);if(0===i.length)throw Error("tell command found no target elements");const o=e.locals.get("_runtimeExecute"),s=[];for(const t of i){const n={...e,me:t,you:t};for(const t of r)try{const e=await this.executeCommand(t,n,o);s.push(e),Object.assign(n,{it:e})}catch(t){throw Error("Command execution failed in tell block: "+(t instanceof Error?t.message:"Unknown error"))}}return{targetElements:i,commandResults:s,executionCount:i.length*r.length}}async executeCommand(t,e,n){if(t&&"object"==typeof t&&"command"===t.type&&n)return await n(t,e);if("function"==typeof t)return await t(e);if(t&&"object"==typeof t&&"function"==typeof t.execute)return await t.execute(e);throw Error("Invalid command: must be a function or object with execute method")}};return yo(e,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"utility",compatibility:"standard"}),po(e,r),i=e})()),Fa=vo((()=>{let t,e,n=[go({name:"copy"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("copy command requires a source (text or element)");const r=await e.evaluate(t.args[0],n);let i="text";if(t.modifiers?.format){const r=await e.evaluate(t.modifiers.format,n);"html"!==r&&"text"!==r||(i=r)}return{source:r,format:i}}async execute(t,e){const{source:n,format:r="text"}=t,i=this.extractText(n,r,e);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(i),this.dispatchCopyEvent(e,"copy:success",{text:i,method:"clipboard-api"}),{success:!0,text:i,format:r,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(i))return this.dispatchCopyEvent(e,"copy:success",{text:i,method:"execCommand"}),{success:!0,text:i,format:r,method:"execCommand"}}catch{}return this.dispatchCopyEvent(e,"copy:error",{text:i,error:"All copy methods failed"}),{success:!1,text:i,format:r,method:"fallback"}}extractText(t,e,n){if("string"==typeof t)return t;if(gt(t))return"html"===e?t.outerHTML:t.textContent||"";if(t===n.me&&gt(n.me)){const t=n.me;return"html"===e?t.outerHTML:t.textContent||""}return t+""}copyUsingExecCommand(t){if("undefined"==typeof document)return!1;const e=document.createElement("textarea");e.value=t,e.style.cssText="position:fixed;top:0;left:-9999px",e.setAttribute("readonly",""),document.body.appendChild(e);try{e.select(),e.setSelectionRange(0,t.length);const n=document.execCommand("copy");return document.body.removeChild(e),n}catch{return e.parentNode?.removeChild(e),!1}}dispatchCopyEvent(t,e,n){if(gt(t.me)){const r=new CustomEvent(e,{detail:n,bubbles:!0,cancelable:!1});t.me.dispatchEvent(r)}}};return yo(e,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"utility",compatibility:"lokascript-extension"}),po(e,r),i=e})());const Ua=vo((()=>{let t,e,n=[go({name:"pick"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.modifiers?.variant,i=r?.value;if("first"===i||"last"===i){const r=await e.evaluate(t.args[0],n),o=await e.evaluate(t.modifiers.count,n);if(!Array.isArray(r))throw Error(`pick ${i}: source must be an array, got ${typeof r}`);if("number"!=typeof o||!Number.isFinite(o))throw Error(`pick ${i}: count must be a number, got ${typeof o}`);return{variant:i,array:r,count:o}}if("random"===i){const r=await e.evaluate(t.args[0],n);if(!Array.isArray(r))throw Error("pick random: source must be an array");let i;if(t.modifiers.count){const r=await e.evaluate(t.modifiers.count,n);if("number"!=typeof r||!Number.isFinite(r))throw Error("pick random: count must be a number, got "+typeof r);i=r}return{variant:"random",array:r,count:i}}if("range"===i){const r=await e.evaluate(t.args[0],n);if(!Array.isArray(r)&&"string"!=typeof r)throw Error("pick items: source must be an array or string");const i=t.modifiers.rangeStart,o="start"===i?.value?"start":await e.evaluate(t.modifiers.rangeStart,n),s="start"===o?"start":Number(o);let a;if(t.modifiers.rangeEnd)if("end"===t.modifiers.rangeEnd.value)a="end";else{const r=await e.evaluate(t.modifiers.rangeEnd,n);a=Number(r)}const c=t.modifiers.rangeMode;return{variant:"range",array:r,rangeStart:s,rangeEnd:a,rangeMode:c?.value??"default"}}if("match"===i||"matches"===i){const r=await e.evaluate(t.args[0],n);if("string"!=typeof r)throw Error(`pick ${i}: source must be a string, got ${typeof r}`);const o=await e.evaluate(t.modifiers.regex,n),s="string"==typeof o?o:o+"",a=t.modifiers.flags,c=a?.value;return{variant:i,source:r,regex:s,flags:c}}if(t.modifiers?.from){const r=await e.evaluate(t.modifiers.from,n);if(!Array.isArray(r))throw Error("pick from requires an array");if(0===r.length)throw Error("Cannot pick from empty array");return{variant:"random",array:r}}if(0===t.args.length)throw Error("pick command requires items to choose from");return{variant:"random",items:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}}async execute(t,e){const n=t.variant??"random";if("first"===n){const n=t.array??[],r=n.slice(0,t.count??0);return Object.assign(e,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"array",variant:"first"}}if("last"===n){const n=t.array??[],r=t.count??0,i=r>0?n.slice(-r):[];return Object.assign(e,{it:i}),{selectedItem:i,sourceLength:n.length,sourceType:"array",variant:"last"}}if("range"===n){const n=t.array??[];let r="start"===t.rangeStart?0:t.rangeStart??0,i=void 0===t.rangeEnd?r+1:"end"===t.rangeEnd?n.length:t.rangeEnd;"inclusive"===t.rangeMode?i++:"exclusive"===t.rangeMode&&r++;const o=n.slice(r,i);return Object.assign(e,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"array",variant:"range"}}if("match"===n){const n=t.source??"",r=RegExp(t.regex??"",t.flags).exec(n);return Object.assign(e,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"string",variant:"match"}}if("matches"===n){const n=t.source??"",r=t.flags??"g",i=RegExp(t.regex??"",r.includes("g")?r:"g"+r),o=Array.from(n.matchAll(i));return Object.assign(e,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"string",variant:"matches"}}const r=t.items??t.array??[];if(0===r.length)throw Error("Cannot pick from empty collection");if(void 0===t.count){const n=Math.floor(Math.random()*r.length),i=r[n];return Object.assign(e,{it:i}),{selectedItem:i,selectedIndex:n,sourceLength:r.length,sourceType:t.items?"items":"array",variant:"random"}}const i=r.slice(),o=[];for(let e=0;t.count>e&&i.length>0;e++){const t=Math.floor(Math.random()*i.length);o.push(i.splice(t,1)[0])}return Object.assign(e,{it:o}),{selectedItem:o,sourceLength:r.length,sourceType:t.items?"items":"array",variant:"random"}}};return yo(e,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"utility",compatibility:"standard"}),po(e,r),i=e})());const _a=vo((()=>{let t,e,n=[go({name:"beep"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return 0===t.args.length?{expressions:[]}:{expressions:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}}async execute(t,e){const n=t.expressions||[];if(0===n.length)return this.debugContext(e),{expressionCount:0,debugged:!0,outputs:[]};const r=[];console.group("\ud83d\udd14 beep! Debug Output");for(const t of n){const e=this.debugExpression(t);r.push(e),console.log("Value:",t),console.log("Type:",e.type),console.log("Representation:",e.representation),console.log("---")}return console.groupEnd(),{expressionCount:n.length,debugged:!0,outputs:r}}debugContext(t){console.group("\ud83d\udd14 beep! Context Debug"),console.log("me:",t.me),console.log("it:",t.it),console.log("you:",t.you),console.log("locals:",t.locals),console.log("globals:",t.globals),console.log("variables:",t.variables),console.groupEnd()}debugExpression(t){return{value:t,type:this.getType(t),representation:this.getRepresentation(t)}}getType(t){return null===t?"null":void 0===t?"undefined":Array.isArray(t)?"array":gt(t)?"HTMLElement":t instanceof Element?"Element":t instanceof Node?"Node":t instanceof Error?"Error":t instanceof Date?"Date":t instanceof RegExp?"RegExp":typeof t}getRepresentation(t){if(null===t)return"null";if(void 0===t)return"undefined";if(Array.isArray(t))return`Array(${t.length}) [${t.slice(0,3).map(t=>this.getRepresentation(t)).join(", ")}${t.length>3?"...":""}]`;if(gt(t)){const e=t;return`<${e.tagName.toLowerCase()}${e.id?"#"+e.id:""}${e.className?"."+e.className.split(" ").join("."):""}/>`}if(t instanceof Error)return"Error: "+t.message;if("string"==typeof t)return t.length>50?`"${t.substring(0,47)}..."`:`"${t}"`;if("object"==typeof t)try{const e=Object.keys(t);return`Object {${e.slice(0,3).join(", ")}${e.length>3?"...":""}}`}catch{return"[Object]"}return t+""}};return yo(e,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({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"],category:"utility",compatibility:"lokascript-extension"}),po(e,r),i=e})()),za=vo((()=>{let t,e,n=[go({name:"breakpoint"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{}}async execute(t,e){}validate(t){return"object"==typeof t&&null!==t}};return yo(e,"BreakpointCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;mo(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),i=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=bo({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),po(e,r),i=e})());class Wa{constructor(){this.name="install"}get metadata(){return Wa.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("install command requires a behavior name");const r=t.args[0];let i,o,s;if(i="identifier"===r?.type&&"string"==typeof r.name?r.name:await e.evaluate(r,n)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(i))throw Error(`Behavior name must be PascalCase (start with uppercase): "${i}"`);if(t.args.length>=2){const r=await e.evaluate(t.args[1],n);if(r&&"object"==typeof r&&!Array.isArray(r)){o=r;for(const t of Object.keys(o))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(t))throw Error(`Invalid parameter name: "${t}"`)}}return t.modifiers?.on&&(s=await e.evaluate(t.modifiers.on,n)),{behaviorName:i,parameters:o,target:s}}async execute(t,e){const{behaviorName:n,parameters:r={},target:i}=t;try{const t=this.resolveTarget(i,e);if(0===t.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(n,e))throw Error(`Behavior "${n}" is not defined. Define it using the 'behavior' keyword before installing.`);const o=[];for(const i of t){const t=await this.installBehavior(n,i,r,e);o.push(t)}return{success:!0,behaviorName:n,installedCount:o.length,instances:o}}catch(t){throw Error(`Failed to install behavior "${n}": ${t instanceof Error?t.message:t+""}`)}}resolveTarget(t,e){if(null==t){const t=e.me||e.locals.get("me");if(gt(t))return[t];throw Error('No target specified and "me" is not available in context')}if(gt(t))return[t];if(Array.isArray(t)){const e=t.filter(t=>gt(t));if(0===e.length)throw Error("Target array contains no valid HTMLElements");return e}if("string"==typeof t){if("me"===t){const t=e.me||e.locals.get("me");if(gt(t))return[t];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const e=document.querySelectorAll(t),n=Array.from(e).filter(t=>gt(t));if(0===n.length)throw Error(`No elements found matching selector: "${t}"`);return n}throw Error("document is not available (not in browser environment)")}if(t&&"object"==typeof t&&"length"in t){const e=Array.from(t).filter(t=>gt(t));if(0===e.length)throw Error("Target collection contains no valid HTMLElements");return e}if("object"==typeof t&&"element"in t){const e=t.element;if(gt(e))return[e]}throw Error("Cannot resolve target to HTMLElement(s): "+t)}behaviorExists(t,e){const n=e.locals.get("_behaviors");if(n&&"object"==typeof n){const e=n;if(e.has(t))return!0;if(e.resolve&&e.resolve(t))return!0}if("undefined"!=typeof globalThis){const e=globalThis._hyperscript;if(e?.behaviors){if(e.behaviors.has(t))return!0;if(e.behaviors.resolve&&e.behaviors.resolve(t))return!0}}return!1}async installBehavior(t,e,n,r){const i=r.locals.get("_behaviors");if(i&&"object"==typeof i){const r=i;if(r.install&&"function"==typeof r.install)return await r.install(t,e,n)}if("undefined"!=typeof globalThis){const r=globalThis._hyperscript;if(r?.behaviors?.install)return await r.behaviors.install(t,e,n)}throw Error("Behavior system not available in context")}}Wa.metadata=bo({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",compatibility:"standard",sideEffects:["behavior-installation","element-modification"]});class Za{constructor(){this.name="render"}get metadata(){return Za.metadata}async parseInput(t,e,n){if(1>t.args.length)throw Error("render command requires a template");const r=await e.evaluate(t.args[0],n);let i;if(t.args.length>=3&&"with"===await e.evaluate(t.args[1],n)){const r=await e.evaluate(t.args[2],n);r&&"object"==typeof r&&(i=r)}if(!i&&t.modifiers?.with){const r=await e.evaluate(t.modifiers.with,n);r&&"object"==typeof r&&(i=r)}return{template:r,variables:i}}async execute(t,e){const{template:n,variables:r={}}=t,i=this.extractTemplateContent(n,e),o=this.createTemplateContext(e,r),s=[],a=await this.processTemplate(i,o,s),c=this.createDOMElement(a);return Object.assign(e,{it:c}),{element:c,rendered:a,directivesProcessed:s}}extractTemplateContent(t,e){if(t instanceof HTMLTemplateElement)return t.innerHTML;if("string"==typeof t){let n=t;if(!n.includes("<")&&!n.includes("$")){const t=this.resolveVariable(n,e);if(t instanceof HTMLTemplateElement)return t.innerHTML;"string"==typeof t&&(n=t)}const r=n.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return r?r[1]:n}if(t&&"object"==typeof t&&"innerHTML"in t)return t.innerHTML;throw Error("Invalid template format")}createTemplateContext(t,e){return{...t,locals:new Map([...Array.from(t.locals.entries()),...Object.entries(e)])}}async processTemplate(t,e,n){const r=t.split("\n"),i=[];let o=0;for(;r.length>o;){const t=r[o].trim();if(t.startsWith("@repeat ")){const{nextIndex:t,rendered:s}=await this.processRepeatDirective(r,o,e);i.push(s),o=t,n.push("@repeat")}else if(t.startsWith("@if ")){const{nextIndex:t,rendered:s}=await this.processIfDirective(r,o,e,n);i.push(s),o=t,n.push("@if")}else if("@else"===t||"@end"===t)o++;else{const n=this.processVariableInterpolation(t,e);i.push(n),o++}}return i.join("\n")}async processRepeatDirective(t,e,n){const r=t[e].trim(),i=r.match(/^@repeat\s+in\s+(.+)$/);if(!i)throw Error("Invalid @repeat syntax: "+r);const o=this.evaluateExpression(i[1],n),{endIndex:s,blockContent:a}=this.extractDirectiveBlock(t,e+1),c=[];if(Array.isArray(o))for(const t of o){const e={...n,locals:new Map([...n.locals.entries(),["it",t]])},r=await this.processTemplate(a.join("\n"),e,[]);c.push(r)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(t,e,n,r){const i=t[e].trim(),o=i.match(/^@if\s+(.+)$/);if(!o)throw Error("Invalid @if syntax: "+i);const s=!!this.evaluateExpression(o[1],n),{endIndex:a,blockContent:c,elseContent:l}=this.extractIfElseBlock(t,e+1);let u="";return s?u=await this.processTemplate(c.join("\n"),n,[]):l.length>0&&(u=await this.processTemplate(l.join("\n"),n,[]),r.push("@else")),{nextIndex:a+1,rendered:u}}extractDirectiveBlock(t,e){const n=[];let r=1,i=e;for(;t.length>i&&r>0;){const e=t[i].trim();e.startsWith("@repeat ")||e.startsWith("@if ")?(r++,n.push(t[i])):"@end"===e?(r--,r>0&&n.push(t[i])):n.push(t[i]),i++}return{endIndex:i-1,blockContent:n}}extractIfElseBlock(t,e){const n=[],r=[];let i=1,o=e,s=!1;for(;t.length>o&&i>0;){const e=t[o].trim();if(e.startsWith("@if "))i++;else{if("@else"===e&&1===i){s=!0,o++;continue}if("@end"===e&&(i--,0===i))break}s?r.push(t[o]):n.push(t[o]),o++}return{endIndex:o,blockContent:n,elseContent:r}}processVariableInterpolation(t,e){return t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=n.trim();if(t.startsWith("unescaped ")){const n=t.substring(10).trim();return(this.evaluateExpression(n,e)||"")+""}const r=this.evaluateExpression(t,e);return this.escapeHtml((r||"")+"")}catch(e){return Re(`render: template interpolation error for ${n}:`,e),t}})}evaluateExpression(t,e){if("true"===t)return!0;if("false"===t)return!1;if("null"===t)return null;if("undefined"===t)return;const n=Number(t);if(!isNaN(n)&&""!==t.trim())return n;if(t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++){if("object"!=typeof r||null===r)return;r=r[n[t]]}return r}return this.resolveVariable(t,e)}resolveVariable(t,e){return e.locals?.has(t)?e.locals.get(t):"me"===t?e.me:"it"===t?e.it??e.result:"you"===t?e.you:"result"===t?e.result??e.it:e.globals?.has(t)?e.globals.get(t):void 0}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(t){if("undefined"==typeof document)return null;const e=document.createElement("div");return e.innerHTML=t,1===e.children.length?e.firstElementChild:e}}function Ja(){if("undefined"!=typeof window&&window.LokaScriptSemantic)return window.LokaScriptSemantic;throw Error('LokaScriptSemantic not found. Load the semantic bundle before the multilingual bundle:\n<script src="lokascript-semantic.browser.global.js"><\/script>\n<script src="hyperfixi-multilingual.js"><\/script>')}Za.metadata=bo({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",compatibility:"standard",sideEffects:["dom-creation","template-execution"]});const Ka=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],Xa=function(t,e){const n=new qr(null);for(const e of t)n.register(e);return new Wr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Oo(),No(),Ko(),es(),Ss(),Ts(),Os(),js(),Ls(),Ms(),qs(),Bs(),Us(),Zs(),Xs(),Gs(),ta(),ea(),na(),ia(),aa(),ca(),la(),da(),pa(),ba(),wa(),Ea(),xa(),Sa(),ha(),Ta(),Aa(),new Ca,$a(),Oa(),Ra(),La(),Ia(),Ma(),Pa(),qa(),Ha(),Ba(),Da(),Va(),Fa(),Ua(),_a(),za(),new Wa,new Za],{expressionRegistry:fo()}),Ga={async execute(t,e,n){const r=Ja(),i=r.parseSemantic(t,e);if(.5>i.confidence||!i.node)throw Error(`Failed to parse "${t}" in language "${e}" (confidence: ${i.confidence.toFixed(2)})`);const o=r.buildAST(i.node),s=yt(n);return Xa.execute(o.ast,s)},parse(t,e){const n=Ja(),r=n.parseSemantic(t,e);return.5>r.confidence||!r.node?null:n.buildAST(r.node).ast},translate:(t,e,n)=>Ja().translate(t,e,n),getAllTranslations:(t,e)=>Ja().getAllTranslations(t,e),createContext:pt,runtime:Xa,version:"1.0.0-multilingual",commands:["hide","show","add","remove","toggle","put","make","wait","fetch","set","get","increment","decrement","default","trigger","send","go","if","repeat","break","continue","halt","return","exit","unless","throw","call","pseudo-command","append","prepend","transition","measure","settle","take","js","async","log","tell","copy","pick","beep","install","render"],supportedLanguages:Ka,bundleType:"multilingual",processNode:async t=>{t===document||t===document.documentElement?await ec():t instanceof HTMLElement&&await tc(t)},process:async t=>Ga.processNode(t)},Ya=new WeakSet;let Qa=null;async function tc(t){if(Ya.has(t))return;const e=t.getAttribute("_");if(e)try{const n=function(t){const e=t.getAttribute("data-lang");if(e&&Ka.includes(e))return e;let n=t;for(;n;){const t=n.getAttribute("lang");if(t){const e=t.split("-")[0].toLowerCase();if(Ka.includes(e))return e}n=n.parentElement}return"en"}(t);Ie(`ATTR-ML: Processing element with lang="${n}":`,e.substring(0,60));const r=Ja(),i=r.parseSemantic(e,n);if(.5>i.confidence||!i.node)return void Ie(`ATTR-ML: Low confidence (${i.confidence.toFixed(2)}) for: ${e}`);const o=r.buildAST(i.node),s=yt(t);await Xa.execute(o.ast,s),Ya.add(t),Ie("ATTR-ML: Successfully processed element")}catch(t){Ie("ATTR-ML: Error processing element:",t.message)}}async function ec(){const t=document.querySelectorAll("[_]");Ie(`ATTR-ML: Found ${t.length} elements with _ attributes`);const e=[];t.forEach(t=>{t instanceof HTMLElement&&e.push(tc(t))}),await Promise.all(e),Ie("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:t.length}}))}function nc(){"undefined"!=typeof MutationObserver&&(Qa=new MutationObserver(t=>{for(const e of t)e.addedNodes.forEach(t=>{if(t.nodeType!==Node.ELEMENT_NODE)return;const e=t;e.getAttribute?.("_")&&tc(e).catch(t=>{Ie("ATTR-ML: Error processing dynamic element:",t)});const n=e.querySelectorAll?.("[_]");n?.forEach(t=>{t instanceof HTMLElement&&tc(t).catch(t=>{Ie("ATTR-ML: Error processing dynamic descendant:",t)})})})}),Qa.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=Ga,void 0===window.lokascript&&Object.defineProperty(window,"lokascript",{get:()=>(console.warn("[DEPRECATED] window.lokascript is deprecated and will be removed in v3.0.0. Please use window.hyperfixi instead."),window.hyperfixi),enumerable:!0,configurable:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ec().then(()=>nc())}):ec().then(()=>nc())),t.default=Ga,t.hyperfixi=Ga,Object.defineProperty(t,"l",{value:!0}),t}({});
2
2
  //# sourceMappingURL=hyperfixi-multilingual.js.map