@hyperfixi/core 3.0.0 → 3.1.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 (60) hide show
  1. package/dist/api/hyperscript-api.d.ts +2 -0
  2. package/dist/ast-utils/{index.js → index.cjs} +1 -1
  3. package/dist/behaviors/{index.js → index.cjs} +1 -1
  4. package/dist/bundle-generator/{index.js → index.cjs} +1 -1
  5. package/dist/chunks/bridge-DylVo1oZ.js +2 -0
  6. package/dist/chunks/browser-modular-sLPMdxR7.js +2 -0
  7. package/dist/chunks/index-C7lqD4mo.js +2 -0
  8. package/dist/commands/{index.js → index.cjs} +39 -1
  9. package/dist/commands/index.mjs +38 -0
  10. package/dist/dom/attribute-processor.d.ts +35 -1
  11. package/dist/dom/detect-language.d.ts +3 -0
  12. package/dist/expressions/{index.js → index.cjs} +1 -1
  13. package/dist/hyperfixi-browser-classic-i18n.js +1 -1
  14. package/dist/hyperfixi-browser.js +1 -1
  15. package/dist/hyperfixi-classic-i18n.js +1 -1
  16. package/dist/hyperfixi-hx-v4.js +1 -1
  17. package/dist/hyperfixi-multilingual.js +1 -1
  18. package/dist/hyperfixi.js +1 -1
  19. package/dist/hyperfixi.mjs +1 -1
  20. package/dist/index.cjs +28495 -0
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.min.js +1 -1
  23. package/dist/index.mjs +630 -57829
  24. package/dist/lokascript-browser-classic-i18n.js +1 -1
  25. package/dist/lokascript-browser.js +1 -1
  26. package/dist/lokascript-multilingual.js +1 -1
  27. package/dist/lse/{index.js → index.cjs} +1 -1
  28. package/dist/{lsp-metadata.js → lsp-metadata.cjs} +1 -1
  29. package/dist/{metadata.js → metadata.cjs} +2 -2
  30. package/dist/metadata.d.ts +1 -1
  31. package/dist/metadata.mjs +1 -1
  32. package/dist/multilingual/bridge.d.ts +2 -0
  33. package/dist/multilingual/{index.js → index.cjs} +3 -105
  34. package/dist/multilingual/index.mjs +1 -103
  35. package/dist/parser/{full-parser.js → full-parser.cjs} +39 -1
  36. package/dist/parser/full-parser.mjs +38 -0
  37. package/dist/parser/hybrid/{aliases.js → aliases.cjs} +1 -1
  38. package/dist/parser/hybrid/ast-types.cjs +3 -0
  39. package/dist/parser/hybrid/{index.js → index.cjs} +1 -1
  40. package/dist/parser/hybrid/{parser-core.js → parser-core.cjs} +1 -1
  41. package/dist/parser/hybrid/{tokenizer.js → tokenizer.cjs} +1 -1
  42. package/dist/parser/{hybrid-parser.js → hybrid-parser.cjs} +1 -1
  43. package/dist/parser/{regex-parser.js → regex-parser.cjs} +1 -1
  44. package/dist/parser/semantic-integration.d.ts +15 -0
  45. package/dist/reference/{index.js → index.cjs} +1 -1
  46. package/dist/registry/{browser-types.js → browser-types.cjs} +1 -1
  47. package/dist/registry/{environment.js → environment.cjs} +1 -1
  48. package/dist/registry/{index.js → index.cjs} +39 -1
  49. package/dist/registry/index.mjs +38 -0
  50. package/dist/registry/{universal-types.js → universal-types.cjs} +1 -1
  51. package/dist/runtime/runtime-base.d.ts +1 -0
  52. package/dist/runtime/runtime.d.ts +1 -0
  53. package/dist/version.d.ts +1 -1
  54. package/package.json +28 -28
  55. package/dist/api/dom-processor.d.ts +0 -21
  56. package/dist/chunks/bridge-8SRzBI2K.js +0 -2
  57. package/dist/chunks/browser-modular-L1qgqF_N.js +0 -2
  58. package/dist/chunks/index-SorDzXmq.js +0 -2
  59. package/dist/index.js +0 -85694
  60. package/dist/parser/hybrid/ast-types.js +0 -3
@@ -1,2 +1,2 @@
1
- var _hyperfixiMultilingualInternal=function(e){"use strict";function t(e){return e}function n(e){return e}class r{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const n of this.afterExecuteHooks)await n(e,t)}async runOnError(e,t){let n=t;for(const t of this.onErrorHooks){const r=await t(e,n);r instanceof Error&&(n=r)}return n}shouldIntercept(e,t){for(const n of this.interceptCommandHooks)if(n(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function i(e){return{ok:!0,value:e}}function o(e){return{ok:!1,error:e}}function s(e){return!0===e.ok}const a="then",c="else",l="end",u="and",f="for",d="while",h="until",m="forever",p="times",y="index",b="in",g="to",v="from",w="with",E="of",x="on",k="event",S="behavior",T="global",A="the",C="start",$=new Set(["add","append","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"]),j=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),O="at end of",N=["into","before","after","at",j,O,"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=e=>$.has(e.toLowerCase()),M=e=>R.has(e.toLowerCase()),I=e=>q.has(e.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"]),P=new Set(["and","or","not","no"]),B=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","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]),D=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),U=new Set([")","]","}",","]);function _(e,t){return{infix:{bp:[e,e+1],handler:t??((t,n,r)=>{const i=r.parseExpr(e+1);return{type:"binaryExpression",operator:n.value,left:t,right:i,start:t.start,end:i.end??n.end,line:t.line??n.line,column:t.column??n.column}})}}}function z(e,t){return{infix:{bp:[e+1,e],handler:(t,n,r)=>{const i=r.parseExpr(e);return{type:"binaryExpression",operator:n.value,left:t,right:i,start:t.start,end:i.end??n.end,line:t.line??n.line,column:t.column??n.column}}}}}function W(e,t){return{prefix:{bp:e,handler:t??((t,n)=>{const r=n.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:r,argument:r,prefix:!0,start:t.start,end:r.end??t.end,line:t.line,column:t.column}})}}}function Z(e){return(t,n,r)=>{const i=r.advance();if(!i||!i.value)throw Error(`Type check requires a type name after 'is ${e?"not ":""}a/an', got: <end>`);let o=!0;const s=r.peek();return s&&"!"===s.value&&(r.advance(),o=!1),{type:"typeCheckExpression",value:t,typeName:i.value,nullOk:o,negated:e,start:t.start,end:i.end}}}const J=function(...e){const t=new Map;for(const n of e)for(const[e,r]of n){const n=t.get(e);t.set(e,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return t}(new Map([["or",_(10)],["||",_(10)],["and",_(20)],["&&",_(20)],["==",_(30)],["!=",_(30)],["<",_(30)],[">",_(30)],["<=",_(30)],[">=",_(30)],["is",_(30)],["matches",_(30)],["contains",_(30)],["starts with",_(30)],["ends with",_(30)],["does not start with",_(30)],["does not end with",_(30)],["is between",_(30,(e,t,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:e,min:r,max:o,negated:!1,start:e.start,end:o.end}})],["is not between",_(30,(e,t,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:e,min:r,max:o,negated:!0,start:e.start,end:o.end}})],["am between",_(30,(e,t,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:e,min:r,max:o,negated:!1,start:e.start,end:o.end}})],["am not between",_(30,(e,t,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:e,min:r,max:o,negated:!0,start:e.start,end:o.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:r,start:e.start,end:r.end}})],["sorted by",_(28,(e,t,n)=>{const r=n.parseExpr(29);let i="asc";const o=n.peek();if(o&&"string"==typeof o.value){const e=o.value.toLowerCase();"asc"===e||"ascending"===e?(n.advance(),i="asc"):"desc"!==e&&"descending"!==e||(n.advance(),i="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:r,order:i,start:e.start,end:r.end}})],["mapped to",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:r,start:e.start,end:r.end}})],["split by",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:r,start:e.start,end:r.end}})],["joined by",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:r,start:e.start,end:r.end}})],["+",{..._(40),...W(80)}],["-",{..._(40),...W(80)}],["*",_(50)],["/",_(50)],["%",_(50)],["mod",_(50)],["^",z(60)],["**",z(60)],["as",_(70,(e,t,n)=>{const r=()=>{const e=n.peek();!e||"a"!==e.value&&"an"!==e.value||n.advance();const t=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&t&&"identifier"===t.type){n.advance();const e=n.advance();if(e&&void 0!==e.value)return{...t,name:`${t.name+""}:${e.value}`,end:e.end}}return t};let i=r(),o={type:"asExpression",expression:e,targetType:i,start:e.start,end:i.end??t.end,line:e.line??t.line,column:e.column??t.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const e=r();o={type:"asExpression",expression:o,targetType:e,start:o.start,end:e.end??o.end,line:o.line,column:o.column}}return o})],["not",W(80)],["!",W(80)],["no",W(27)]]),new Map([["===",_(30)],["!==",_(30)],["is not",_(30)],["am",_(30)],["is in",_(30)],["is not in",_(30)],["precedes",_(30)],["does not precede",_(30)],["follows",_(30)],["does not follow",_(30)],["is a",_(30,Z(!1))],["is an",_(30,Z(!1))],["is not a",_(30,Z(!0))],["is not an",_(30,Z(!0))],["has",_(30)],["have",_(30)],["match",_(30)],["include",_(30)],["includes",_(30)],["equals",_(30)],["does not contain",_(30)],["does not include",_(30)],["am in",_(30)],["am not in",_(30)],["is really",_(30)],["is not really",_(30)],["is equal",_(30)],["is not equal",_(30)],["contain",_(30)],["do not contain",_(30)],["does not contains",_(30)],["do not match",_(30)],["does not match",_(30)],["is equal to",_(30)],["is not equal to",_(30)],["is really equal to",_(30)],["is not really equal to",_(30)],["really equals",_(30)],["is greater than",_(30)],["is less than",_(30)],["is greater than or equal to",_(30)],["is less than or equal to",_(30)],["in",_(30)],["of",z(30)],["really",_(30)],["exists",{prefix:{bp:80,handler:(e,t)=>({type:"unaryExpression",operator:e.value,operand:t.parseExpr(80),start:e.start})},infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["does not exist",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is not empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["some",W(80)]]),new Map([["=",z(5)]])),K=new Set,G=new Set,X=new Set,Y=new Set;function Q(e,t){void 0!==console&&console.error(`[hyperfixi] ${e} threw:`,t)}function ee(e,t){if(0!==G.size)for(const n of G)try{n(e,t)}catch(e){Q("globalReadHook",e)}}function te(e,t,n){if(0!==X.size)for(const r of X)try{r(e,t,n)}catch(e){Q("localWriteHook",e)}}function ne(e,t){if(0!==Y.size)for(const n of Y)try{n(e,t)}catch(e){Q("localReadHook",e)}}function re(e,t,n){if(e.globals.set(t,n),0!==K.size)for(const r of K)try{r(t,n,e)}catch(e){Q("globalWriteHook",e)}}const ie=new Map,oe=new Map,se=new Map;function ae(e){return ie.get(e.toLowerCase())}function ce(e){return se.get(e)}const le=new Map,ue=new WeakMap;function fe(e){let t=ue.get(e);return t||(t=new Map,ue.set(e,t)),t}function de(e){return e.owner||(e.me instanceof Element?e.me:null)}function he(e,t){const n=de(e);if(n)return ne(t,e),fe(n).get(t)}function me(e,t,n){const r=de(e);r&&(fe(r).set(t,n),te(t,n,e))}function pe(e,t){return{me:e??null,owner:e??null,it:null,you:null,result:null,locals:new Map,globals:t||le}}function ye(e){if(!e)return pe();if(e.locals instanceof Map&&e.globals instanceof Map)return e;const t=pe(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}function be(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function ge(e){if(null===e||"object"!=typeof e)return!1;const t=e.nodeType;return 1===t||3===t||11===t}function ve(e){return null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(Symbol.iterator in e||"function"==typeof e.item)}function we(e){if(null==e)return 0;if("number"==typeof e)return isFinite(e)?e:0;if("string"==typeof e)return parseFloat(e);if("boolean"==typeof e)return e?1:0;if(Array.isArray(e))return e.length;if("object"==typeof e){if("length"in e&&"number"==typeof e.length)return e.length;if("function"==typeof e.valueOf){const t=e.valueOf();if("number"==typeof t)return t}return NaN}return 0}function Ee(e,t,n){return"element"===n?he(t,e):"global"===n&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==n&&t.locals&&t.locals.has(e)?(ne(e,t),t.locals.get(e)):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===n&&t.locals&&t.locals.has(e)?(ne(e,t),t.locals.get(e)):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function xe(e,t,n,r){if("element"!==r){if("global"===r)return re(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))return void re(n,e.slice(1),t);if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void te(e,t,n);if(n.globals&&n.globals.has(e))return re(n,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(n.variables&&n.variables.has(e))n.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void re(n,e,t);n.locals.set(e,t),te(e,t,n)}}else me(n,e,t)}function ke(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Ee(e,t)}function Se(e,t,n){return n||"string"!=typeof t||!t.startsWith("#")?e:Array.isArray(e)?e[0]??null:e}function Te(e){if("undefined"==typeof document)throw Error("DOM not available");const t=Array.from(document.querySelectorAll(e)).filter(e=>be(e));if(!t.length)throw Error(`No elements: "${e}"`);return t}function Ae(e){if(be(e))return[e];if(Array.isArray(e)){const t=e.filter(be);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(be);return t.length>0?t:null}return null}const Ce=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,n]of this.types)if(n.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),n=this.types.get(t);return n?.hyperscriptType??"unknown"}coerce(e,t,n){const r=this.types.get(t);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(r.isType(e))return e;if(this.config.cacheCoercions){const n=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(e),o=r.coerceFrom?.[i];if(o){const r=o(e,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(e,t){const n=this.types.get(t);if(!n)return!1;if(n.isType(e))return!0;const r=this.inferType(e);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(e,t){const n=this.types.get(t);return n&&(e===t||n.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const n=e;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,n)=>{t[n+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function $e(e){const t=Ce.get("String");return t?t.isType(e):"string"==typeof e}function je(e){const t=Ce.get("Number");return t?t.isType(e):"number"==typeof e}function Oe(e){const t=Ce.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Ne(e){const t=Ce.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Re(e){const t=Ce.get("Function");return t?t.isType(e):"function"==typeof e}function Le(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function Me(e){return e instanceof Element}function Ie(e){return e instanceof HTMLElement}const qe=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function He(e,t){return qe.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const Pe={id:e=>e.id,classname:e=>e.className,class:e=>e.className,tagname:e=>e.tagName.toLowerCase(),innertext:e=>e.textContent?.trim(),innerHTML:e=>e.innerHTML,outerhtml:e=>e.outerHTML,value:e=>function(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}(e)?e.value:void 0,checked:e=>function(e){return null!==e&&"object"==typeof e&&"tagName"in e&&"INPUT"===e.tagName}(e)?e.checked:void 0,disabled:e=>"disabled"in e?e.disabled:void 0,selected:e=>function(e){return null!=e&&"object"==typeof e&&"tagName"in e&&"OPTION"===e.tagName}(e)?e.selected:void 0,tabindex:e=>Le(e)?e.tabIndex:void 0,hidden:e=>Le(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling,next:e=>e.nextElementSibling,previous:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e.getAttribute("name");n&&"value"in e&&t.append(n,e.value)}),t}(e)};function Be(e,t){if(t.startsWith("*"))return function(e,t){if(!Ie(e))return;if(t.startsWith("computed-"))return getComputedStyle(e).getPropertyValue(t.slice(9))||"";const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}(e,t.slice(1));if(t.startsWith("computed-")){const n=t.slice(9);return Ie(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return He(e,t.slice(1));const n=Pe[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return He(e,t);const r=e[t];return Re(r)?r.bind(e):r}const Ve={1:"one",2:"two",3:"three",4:"four",5:"five"};function Fe(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${i=t,Ve[i]??i+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var i;return null}function De(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function Ue(e,t,n){return Fe(e,1,t,n)??De(e,0,t,n)}function _e(e,t){return Fe(e,2,t,"left, right")}function ze(){return null}function We(e,t,n,r){return e.length>t?`${n} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${r?` (${r})`:""}`:null}function Ze(e,t,n,r,i){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${i?` (${i})`:""}`:null}const Je={conversions:{dynamicResolvers:[]}},Ke={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":$e(e)?e:Ne(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Oe(e))return e;if(null==e)return!1;if($e(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return je(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(je(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(je(e))return e;if(null==e)return 0;const t=(e+"").trim();if(!t)return 0;try{return function(e){if(e=e.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(e))throw Error("Invalid characters in math expression");try{const t=Function(`"use strict"; return (${e})`)();if(!je(t)||!isFinite(t))throw Error("Expression did not evaluate to a finite number");return t}catch(e){throw Error("Math expression evaluation failed: "+(e instanceof Error?e.message:e+""))}}(t)}catch(e){return console.warn("Math conversion failed:",e),0}},Int:e=>{const t=Ke.Number(e);return Math.trunc(t)},Float:e=>{const t=Ke.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if($e(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r)}return new Date(e)},JSON:e=>{if(!$e(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(Ne(e))return e;if($e(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{const t=document.createDocumentFragment(),n=Array.isArray(e)||e instanceof NodeList?Array.from(e):[e];for(const e of n)if(e instanceof Node)t.append(e);else{const n=document.createElement("template");n.innerHTML=null==e?"":e+"",t.append(n.content)}return t},HTML:e=>$e(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:Ke.String(e)).join(""):e instanceof Element?e.outerHTML:Ke.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=Ge(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=Ge(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?Ke.Values(e,t):e;if(!Ne(n))return"";const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return""+r},Set:e=>new Set(e),Map:e=>new Map(Object.entries(e??{})),Keys:e=>e instanceof Map?Array.from(e.keys()):Object.keys(e??{}),Entries:e=>e instanceof Map?Array.from(e.entries()):Object.entries(e??{}),Reversed:e=>Array.from(e).reverse(),Unique:e=>[...new Set(e)],Flat:e=>Array.from(e).flat(),"Values:Form":(e,t)=>{const n=Ke.Values(e,t);return Ke.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=Ke.Values(e,t);return JSON.stringify(n)}};function Ge(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}const Xe={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 Ye(e,t,n){if("string"!=typeof t)throw Error("Conversion type must be a string");if(t.startsWith("Fixed")){const{precision:n}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):0}:{}}(t);return Ke.Number(e).toFixed(n??0)}if(null==e)return e;let r=Ke[t];if(r)return r(e,n);const i=Xe[t.toLowerCase()];if(i&&(r=Ke[i],r))return r(e,n);const o=Je.conversions[t];if("function"==typeof o)return o(e,n);for(const n of Je.conversions.dynamicResolvers){const r=n(t,e);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+t),e}const Qe={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;return Ye(n,r,e)},validate:e=>Fe(e,2,"as","value, type")??De(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[n,r]=t;if(!$e(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 $e(n);case"number":return je(n)&&!isNaN(n);case"boolean":return Oe(n);case"object":return Ne(n);case"array":return Array.isArray(n);case"function":return Re(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||Ne(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>Fe(e,2,"is","value, type")??De(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Fe(e,1,"async","expression")}};function et(e,t){if(t.startsWith("computed-")){const n=t.substring(9);return getComputedStyle(e).getPropertyValue(n)||""}const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}const tt={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:ze},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:ze},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it??e.result,validate:ze},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it??e.result,validate:ze},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result??e.it,validate:ze},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:e=>Ue(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>Ue(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:e=>Ue(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:e=>Ue(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let n=t[0];if(n&&"object"==typeof n&&"type"in n){const e=n;"identifier"===e.type&&e.name?n=e.name:"literal"===e.type&&"string"==typeof e.value&&(n=e.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return e.me?e.me.closest(n):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:ze},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:ze},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:ze},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const i=r.querySelectorAll(n);return Array.from(i)},validate:e=>Ue(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const i=r||e.me;if(i&&i instanceof HTMLElement)return et(i,n)},validate:e=>Ze(e,1,2,"styleRef","property, optional element")??De(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&e.me?i=e.me instanceof HTMLElement?e.me:null:"its"===n&&e.it&&(i=e.it instanceof HTMLElement?e.it:null),i)return et(i,r)},validate:e=>Fe(e,2,"possessiveStyleRef","possessor, property")??De(e,0,"possessiveStyleRef","possessor")??De(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&e.me?i=e.me instanceof HTMLElement?e.me:null:"it"===r&&e.it&&(i=e.it instanceof HTMLElement?e.it:null),i)return et(i,n)},validate:e=>Fe(e,2,"ofStyleRef","property, reference")??De(e,0,"ofStyleRef","property")??De(e,1,"ofStyleRef","reference")}};function nt(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const rt="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 it;function ot(){return it({validate:e=>({success:!0,data:e})})}function st(e,t){if(rt)return ot();const n=it({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:nt("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(t?.strict){const t=Object.keys(e),n=Object.keys(r).filter(e=>!t.includes(e));if(n.length>0)return{success:!1,error:nt("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[t,n]of Object.entries(e)){const e=r[t];if(!(t in r)&&!n.t)return{success:!1,error:nt("missing-argument",`Required field "${t}" is missing`,t)};const o=n.validate(e);if(!o.success)return{success:!1,error:nt("validation-error",o.error.message||`Field "${t}" validation failed`,o.error.path?`${t}.${o.error.path}`:t)};void 0!==o.data&&(i[t]=o.data)}return{success:!0,data:i}}});return n.strict=()=>st(e,{strict:!0}),n}it=function(e){return e.describe||(e.describe=function(e){return this.description=e,this}),e.safeParse||(e.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),e.parse||(e.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),e.optional||(e.optional=function(){const e=this.validate.bind(this),t={...this,t:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return it(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&e>r.data.length?{success:!1,error:nt("runtime-error",`String must be at least ${e} characters long`)}:r}};return it(n)}),e.max||(e.max=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length>e?{success:!1,error:nt("runtime-error",`String must be at most ${e} characters long`)}:r}};return it(n)}),e.default||(e.default=function(e){const t=this.validate.bind(this),n={...this,i:e,o:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return it(n)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?e(i.data)?i:{success:!1,error:nt("runtime-error",t||"Refinement validation failed")}:i}};return it(r)}),new Proxy(e,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const at=e=>function(e={}){return rt?ot():it({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:nt("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:nt("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:nt("runtime-error",`String must be at most ${e.maxLength} characters long`)}:e.pattern&&!e.pattern.test(t)?e.pattern.source.startsWith("^")&&e.pattern.source.endsWith("$")?{success:!1,error:nt("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:nt("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),ct=e=>st(e),lt=e=>function(e){return rt?ot():it({validate:t=>{if(!Array.isArray(t))return{success:!1,error:nt("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:nt("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const n=[];for(let r=0;e.length>r;r++){const i=e[r].validate(t[r]);if(!i.success)return{success:!1,error:nt("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(e),ut=()=>ot();class ft{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(this.ttl>=Date.now()-t.timestamp)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU(),this.cache.set(e,{result:t,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[n,r]of this.accessOrder)t>r&&(t=r,e=n);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,n)=>e+(t-n.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const dt=new class{constructor(){this.domQueryCache=new ft(200,3e3),this.exprResultCache=new ft(500,2e3),this.cssMatchCache=new ft(100,5e3),this.formValueCache=new ft(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(e);return this.domQueryCache.set(t,r),r}querySelectorAll(e){const t="querySelectorAll:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,r),r}getElementById(e){const t="getElementById:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(e);return this.domQueryCache.set(t,r),r}getElementsByClassName(e){const t="getElementsByClassName:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,r),r}matches(e,t){const n=`matches:${this.getElementCacheKey(e)}:${t}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=e.matches(t);return this.cssMatchCache.set(n,i),i}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),n=this.formValueCache.get("formValue:"+t);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(e,t){const n=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+n,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(e.cache.keys()))"string"==typeof n&&n.includes(t)&&e.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),n=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${n}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([n,r])=>{e-r.timestamp>t.ttl&&t.delete(n)})})}};var ht;"undefined"!=typeof window&&setInterval(()=>{dt.cleanup()},1e4),function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(ht||(ht={}));const mt=new Set(["+","-","*","/","mod"]),pt=new Set(["ms","s","seconds","minutes","hours","days"]);function yt(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function bt(e){const t=e.input[e.position];return e.position++,"\n"===t?(e.line++,e.column=1):"\r"===t?("\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1):e.column++,t}function gt(e){const t=e.input,n=t.length;for(;n>e.position;){const n=t[e.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;bt(e)}}function vt(e,t,n,r,i){const o=r??e.position-n.length,s=e.position;let a=e.column-n.length;void 0!==r&&(a=wt(e.input,r).column);const c={kind:t,value:n,start:o,end:s,line:Et(e,o),column:a};e.tokens.push(c)}function wt(e,t){let n=1,r=-1;const i=Math.min(t,e.length);for(let t=0;i>t;t++){const i=e[t];"\n"===i?(n++,r=t):"\r"===i&&(n++,e.length>t+1&&"\n"===e[t+1]&&t++,r=t)}return{line:n,column:t-r}}function Et(e,t){return wt(e.input,t).line}function xt(e){const t=e.position;let n="";for(bt(e),bt(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=bt(e);vt(e,ht.COMMENT,"--"+n,t)}function kt(e){const t=e.position,n=bt(e);let r=n;for(;e.input.length>e.position;){const t=bt(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=bt(e))}vt(e,ht.STRING,r,t)}function St(e){const t=e.position;bt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){bt(e);break}if("\\"===t){if(bt(e),e.input.length>e.position){const t=bt(e);switch(t){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=t}}}else n+=bt(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);vt(e,ht.TEMPLATE,n,t)}function Tt(e){const t=e.position;let n=bt(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=bt(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=bt(e),"}"===t)break}vt(e,ht.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)bt(e),e.input.length>e.position&&(n+=bt(e));else{if(!Lt(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=bt(e)}}vt(e,ht.SELECTOR,n,t)}}function At(e){const t=e.position;if(Mt(e))return void function(e,t){const n=e.input;let r="",i=0,o="";for(;n.length>e.position;){const t=n[e.position];if(o)r+=bt(e),t===o&&(o="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===n[e.position+1]){for(;n.length>e.position&&">"!==n[e.position];)r+=bt(e);if(n.length>e.position&&(r+=bt(e)),i--,0>=i)break;continue}let t=!1,o="";for(;n.length>e.position;){const i=n[e.position];if(o)r+=bt(e),i===o&&(o="");else if('"'!==i&&"'"!==i){if(">"===i){t="/"===n[e.position-1],r+=bt(e);break}r+=bt(e)}else o=i,r+=bt(e)}if(t||i++,0>=i)break;continue}r+=bt(e)}else o=t,r+=bt(e)}vt(e,ht.SELECTOR,r,t)}(e,t);let n="";for(n+=bt(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=bt(e),"/"===t&&">"===r){n+=bt(e);break}}vt(e,ht.SELECTOR,n,t)}function Ct(e){const t=e.position;let n=bt(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!Lt(t)&&"_"!==t&&"-"!==t)break;n+=bt(e)}vt(e,ht.SYMBOL,n,t)}function $t(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===yt(e,1))return n="'s",bt(e),bt(e),void vt(e,ht.OPERATOR,n,t);const i=e.input.substring(e.position,e.position+2),o=e.input.substring(e.position,e.position+3);["===","!=="].includes(o)?(n=o,bt(e),bt(e),bt(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,bt(e),bt(e)):n=bt(e),vt(e,ht.OPERATOR,n,t)}function jt(e){const t=e.position,n=e.input,r=n.length;let i="";for(;r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=bt(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(i+=bt(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=bt(e)}if(r>e.position){const t=n[e.position];if("e"===t||"E"===t){const t=r>e.position+1?n[e.position+1]:"",o=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">o||o>"9"))for(i+=bt(e),"+"!==n[e.position]&&"-"!==n[e.position]||(i+=bt(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=bt(e)}}}const o=e.position;let s="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;s+=bt(e)}pt.has(s)?vt(e,ht.TIME,i+s,t):(e.position=o,vt(e,ht.NUMBER,i,t))}function Ot(e){const t=e.position,n=e.input,r=n.length;let i="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;i+=bt(e)}const o=function(e,t,n){const r=t.toLowerCase(),i=e.position;if("'s"===t||"'s"===t)return!1;const o=e.tokens[e.tokens.length-1];if(o&&(o.kind===ht.IDENTIFIER||o.kind===ht.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}gt(e);let s="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=bt(e)}if(s){const t=s.toLowerCase(),i=`${r} ${t}`,o=function(e,t,n,r){const i=t.toLowerCase(),o=n.toLowerCase();if("at"===i){const t=e.position;if("the"===o){gt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;n+=bt(e)}const i=n.toLowerCase();if("start"===i||"end"===i){gt(e);let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;t+=bt(e)}if("of"===t.toLowerCase())return vt(e,ht.IDENTIFIER,`at the ${i} of`,r),!0}return e.position=t,!1}if("start"===o||"end"===o){gt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;n+=bt(e)}return"of"===n.toLowerCase()?(vt(e,ht.IDENTIFIER,`at ${o} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(o)return!0;const a=function(e,t,n){const r=e.position;let i=`${t} ${n}`,o=e.position;const s=[t,n];for(;8>s.length&&(gt(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;t+=bt(e)}if(!t)break;s.push(t.toLowerCase());const n=s.join(" ");B.has(n)&&(i=n,o=e.position)}return B.has(i)&&i!==`${t} ${n}`?(e.position=o,i):(e.position=r,null)}(e,r,t);if(a)return vt(e,ht.OPERATOR,a,n),!0;if(B.has(i))return vt(e,ht.OPERATOR,i,n),!0}return B.has(r)?(e.position=i,vt(e,ht.OPERATOR,t,n),!0):(e.position=i,!1)}(e,i,t);if(o)return;const s=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||P.has(t)||mt.has(e)||mt.has(t)||B.has(t)?ht.OPERATOR:ht.IDENTIFIER}(i);vt(e,s,i,t)}function Nt(e){const t=e.position,n=e.input,r=n.length;bt(e);let i="$";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;i+=bt(e)}vt(e,ht.IDENTIFIER,i,t)}function Rt(e){return/[a-zA-Z]/.test(e)}function Lt(e){return/[a-zA-Z0-9]/.test(e)}function Mt(e){const t=e.input,n=t[e.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=e.position+1,i="";for(;t.length>r&&/[a-zA-Z0-9-]/.test(t[r]);)i+=t[r],r++;return i.length>0&&-1!==t.indexOf("</"+i+">",r)}function It(e){if(Mt(e))return!0;let t=e.position+1,n=!1;for(;e.input.length>t;){const r=e.input[t];if("/"===r&&e.input.length>t+1&&">"===e.input[t+1])return n;if(Lt(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,t++;else{if(" "!==r&&"\t"!==r)return!1;t++}if(t-e.position>50)return!1}return!1}function qt(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const Ht=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const n=performance.now()-t;return this.startTimes.delete(e),n}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=dt.getPerformanceStats();this.metrics.cacheHitRate=e.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Pt(){dt.cleanup(),Ht.getMetrics().memoryUsage>52428800&&Ht.reset()}let Bt=null;function Vt(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const n=e.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${t} cannot be converted to number: "${e}"`);return r}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const n=e[0];if(Array.isArray(n))throw Error(t+" is a nested array, cannot convert to number");return Vt(n,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const n=parseFloat(e);if(!isNaN(n))return n}}const n=e.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Ft(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const n=parseFloat(t);return isNaN(n)?null:n}return"boolean"==typeof e?e?1:0:null==e?0:null}function Dt(e,t){if(!Number.isFinite(e)){if(Number.isNaN(e))throw Error(t+" resulted in non-finite value: NaN");throw Error(`${t} resulted in non-finite value: ${e>0?"Infinity":"-Infinity"}`)}return e}function Ut(e){try{return Vt(e,"_"),!0}catch{return!1}}function _t(e,t,n){if("==="===n)return e===t;if("!=="===n)return e!==t;if(null==e||null==t)return function(e,t,n){if(null==e&&null==t)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,n);const[r,i]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const n=parseFloat(e),r=parseFloat(t);return isNaN(n)||isNaN(r)?[e,t]:[n,r]}const n=Ft(e),r=Ft(t);return null!==n&&null!==r?[n,r]:[e+"",t+""]}(e,t);switch(n){case">":return r>i;case"<":return i>r;case">=":return r>=i;case"<=":return i>=r;case"==":return zt(e,t);case"!=":return!zt(e,t);default:return!1}}function zt(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const n=parseFloat(t);return!isNaN(n)&&e===n}if("string"==typeof e&&"number"==typeof t){const n=parseFloat(e);return!isNaN(n)&&n===t}return"boolean"==typeof e?zt(e?1:0,t):"boolean"==typeof t?zt(e,t?1:0):e+""==t+""}function Wt(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function Zt(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function Jt(e,t,n,r,i,o=!0,s){return r}function Kt(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}"undefined"!=typeof window&&function(e=3e4){Bt&&clearInterval(Bt),Bt=setInterval(Pt,e)}();const Gt=lt([ut(),ut()]),Xt=lt([ut(),at()]),Yt={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){try{return Jt(0,0,0,t==n)}catch(e){throw e}},validate:e=>_e(e,"equals"),inputSchema:Gt,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)"}}},Qt={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,n)=>t===n,validate:e=>_e(e,"strictEquals")},en={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],evaluate:async(e,t,n)=>t!=n,validate:e=>_e(e,"notEquals")},tn={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,n)=>t!==n,validate:e=>_e(e,"strictNotEquals")},nn={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,n)=>_t(t,n,"<"),validate:e=>_e(e,"lessThan")},rn={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],evaluate:async(e,t,n)=>_t(t,n,"<="),validate:e=>_e(e,"lessThanOrEqual")},on={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,n)=>_t(t,n,">"),validate:e=>_e(e,"greaterThan")},sn={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],evaluate:async(e,t,n)=>_t(t,n,">="),validate:e=>_e(e,"greaterThanOrEqual")},an={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){try{return Jt(0,0,0,t&&n)}catch(e){throw e}},validate:e=>_e(e,"and"),inputSchema:Gt,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)"}}},cn={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,n)=>t||n,validate:e=>_e(e,"or")},ln={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>Fe(e,1,"not","operand")},un={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){let n;return n=null==t||($e(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Ne(t)||0!==Object.keys(t).length)),n},validate:e=>Fe(e,1,"isEmpty","value")},fn={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){let n;return n=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:($e(t),!1)),n},validate:e=>Fe(e,1,"no","value")},dn={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await un.evaluate(e,t),validate:e=>Fe(e,1,"isNotEmpty","value")},hn={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>mn(t),validate:e=>Fe(e,1,"exists","value")};function mn(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const pn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>!mn(t),validate:e=>Fe(e,1,"doesNotExist","value")},yn={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){let r;if(t&&n){if(Kt(t)&&Kt(n))return r=t.contains(n),r;if($e(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&Kt(n))return r=e.contains(n),r;if(e&&$e(n)&&n.match(/^[.#][\w-]+$/)){const t=document.querySelector(n);return r=!!t&&e.contains(t),r}}if($e(n)&&n.match(/^[.#][\w-]+$/)&&Kt(t)){const e=document.querySelector(n);return r=!!e&&t.contains(e),r}}if($e(t)&&$e(n))r=t.includes(n);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);r=e.includes(n)||n instanceof Node&&e.some(e=>e instanceof Node&&e.contains(n))}else r=!(!Ne(t)||!$e(n))&&n in t;return r},validate:e=>Fe(e,2,"contains","container, value")},bn={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,n)=>!await yn.evaluate(e,t,n),validate:e=>Fe(e,2,"doesNotContain","container, value")},gn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,n)=>null!=t&&null!=n&&(t+"").startsWith(n+""),validate:e=>Fe(e,2,"startsWith","str, prefix")},vn={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,n)=>null!=t&&null!=n&&(t+"").endsWith(n+""),validate:e=>Fe(e,2,"endsWith","str, suffix")},wn={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){let i=n,o=r;if(null!=i&&null!=o&&i>o){const e=i;i=o,o=e}return null!=i&&null!=o&&t>=i&&o>=t},validate:e=>Fe(e,3,"between","value, min, max")},En={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){try{let e;if(t instanceof Element&&$e(n)){const r=n;if(r.startsWith(".")||r.startsWith("#")||r.startsWith(":")||r.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(r))try{e=function(e,t){return dt.matches(e,t)}(t,r)}catch(t){e=!1}else e=!1}else if($e(t)&&$e(n)){const r=t,i=n;try{e=(i.startsWith("/")&&i.endsWith("/")?RegExp(i.slice(1,-1)):RegExp(i)).test(r)}catch(t){e=r.includes(i)}}else e=!1;return Jt(0,0,0,e)}catch(e){throw e}},validate:e=>Fe(e,2,"matches","element, selector"),inputSchema:Xt,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)"}}},xn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){let r=!1;if(t instanceof Element&&$e(n)){const e=n;e.startsWith(".")?r=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(r=t.hasAttribute(e.slice(1,-1)))}return r},validate:e=>Fe(e,2,"has","element, selector")},kn={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],evaluate:async(e,t,n)=>!await xn.evaluate(e,t,n),validate:e=>Fe(e,2,"doesNotHave","element, selector")},Sn={equals:Yt,strictEquals:Qt,notEquals:en,strictNotEquals:tn,lessThan:nn,lessThanOrEqual:rn,greaterThan:on,greaterThanOrEqual:sn,and:an,or:cn,not:ln,no:fn,isEmpty:un,isNotEmpty:dn,exists:hn,doesNotExist:pn,contains:yn,doesNotContain:bn,startsWith:gn,endsWith:vn,between:wn,matches:En,has:xn,doesNotHave:kn},Tn=new Set(["__proto__","constructor","prototype"]);function An(e,t){if(e instanceof Element)return Be(e,t);if(Ne(e)){if(Tn.has(t))return;return e[t]}return e[t]}function Cn(e){let t;if(Array.isArray(e))t=e;else{if(!("undefined"!=typeof NodeList&&e instanceof NodeList||"undefined"!=typeof HTMLCollection&&e instanceof HTMLCollection))return!1;t=Array.from(e)}return 0!==t.length&&t.every(e=>e instanceof Element||null!=e&&"object"==typeof e&&e.constructor!==Object&&!Array.isArray(e))}const $n={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[n,r]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return Cn(n)&&!(r in n)?Array.from(n,e=>An(e,r)):An(n,r)}},validate:e=>Fe(e,2,"possessive","element, property")??De(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[n]=t;if(e.me){if("string"!=typeof n)throw Error("Property name must be a string");if(e.me instanceof Element)return Be(e.me,n);if(Ne(e.me)){if(Tn.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>Ue(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[n]=t;if(null==e.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=e.it;if(r instanceof Element)return Be(r,n);if(Ne(r)){if(Tn.has(n))return;return r[n]}return r[n]},validate:e=>Ue(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[n]=t;if(e.you){if("string"!=typeof n)throw Error("Property name must be a string");if(e.you instanceof Element)return Be(e.you,n);if(Ne(e.you)){if(Tn.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>Ue(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[n,r]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Be(r,n);if(Ne(r)){if(Tn.has(n))return;return r[n]}return r[n]}},validate:e=>Fe(e,2,"of","property, object")??De(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");const i=r||e.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:e=>Ze(e,1,2,"attribute","attributeName, optional element")??De(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[n,r,i]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const o=i||e.me;return!!(o&&o instanceof Element)&&o.getAttribute(n)===r},validate:e=>Ze(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??De(e,0,"attributeWithValue","attribute name")??De(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:e=>Ue(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:e=>Ue(e,"idReference","idValue")}};function jn(e){return Array.isArray(e)?e:null==e?[]:"string"==typeof e?[e]:e instanceof NodeList||e instanceof HTMLCollection||"number"==typeof e.length?Array.from(e):[e]}const On=function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),Nn=On,Rn=On,Ln=On,Mn=On,In=(...e)=>{Nn&&console.log("\ud83d\udd27",...e)},qn=(...e)=>{Rn&&console.log("\ud83c\udfaf",...e)},Hn=(...e)=>{Ln&&console.log("\ud83d\udcdd",...e)},Pn=(...e)=>{Mn&&console.log("\ud83d\ude80",...e)};function Bn(e){return e.kind===ht.IDENTIFIER&&$.has(e.value.toLowerCase())}function Vn(e){return e.kind===ht.IDENTIFIER&&F.has(e.value.toLowerCase())}function Fn(e){return e.kind===ht.IDENTIFIER&&V.has(e.value.toLowerCase())}function Dn(e){return e.kind===ht.IDENTIFIER&&H.has(e.value.toLowerCase())}function Un(e){return B.has(e.value.toLowerCase())}function _n(e){return e.kind===ht.IDENTIFIER}function zn(e){return e.kind===ht.SELECTOR}function Wn(e){return e.kind===ht.SELECTOR&&!e.value.startsWith("<")}function Zn(e){return e.kind===ht.STRING||e.kind===ht.NUMBER||e.kind===ht.TEMPLATE}function Jn(e){return e.kind===ht.IDENTIFIER}function Kn(e){return e.kind===ht.TIME}function Gn(e){return e.kind===ht.SYMBOL}function Xn(e){return e.kind===ht.COMMENT}function Yn(e){if(e.kind!==ht.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!($.has(t)||F.has(t)||V.has(t)||H.has(t))}function Qn(e){return e.kind===ht.STRING}function er(e){return e.kind===ht.NUMBER}function tr(e){if(e.kind===ht.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function nr(e){return e.kind===ht.TEMPLATE}function rr(e){return e.kind===ht.SELECTOR&&e.value.startsWith("<")}function ir(e){return e.kind===ht.SELECTOR&&e.value.startsWith("#")}function or(e){return e.kind===ht.SELECTOR&&e.value.startsWith(".")}function sr(e){return e.kind===ht.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function ar(e){if(e.kind!==ht.OPERATOR)return!1;const t=e.value.toLowerCase();return!P.has(t)&&!B.has(t)}function cr(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function lr(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function ur(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function fr(e,t,n,r){return{type:"binaryExpression",operator:e,left:t,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function dr(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function hr(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function mr(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function pr(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function yr(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function br(e,t,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...n&&{source:n}}],start:e.start,end:e.end,line:e.line,column:e.column}}function gr(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const vr=[a,u,c,l];function wr(e,t=[]){if(e.isAtEnd())return!0;for(const t of vr)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function Er(e,t=[]){if(!wr(e,t))return e.parseExpression()}function xr(e,t){return!!e.check(t)&&(e.advance(),!0)}function kr(e){const t=e.savePosition();let n;if(e.checkIdentifierLike()){const r=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=r):e.restorePosition(t)}const r=e.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class Sr{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Sr(e.value);return t.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},t}static fromIdentifier(e){const t=new Sr(e.name);return void 0!==e.start&&(t.startPos={start:e.start,end:e.end??0,line:e.line??1,column:e.column??1}),t}static named(e){return new Sr(e)}withArgs(...e){return this.args.push(...e),this}withBody(e){return this.body=e,this}withImplicitTarget(e){return this.implicitTarget=e,this}withModifier(e,t){return this.modifiers||(this.modifiers={}),this.modifiers[e]=t,this}withModifiers(e){return this.modifiers={...this.modifiers,...e},this}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=e,this}blocking(e=!0){return this.isBlocking=e,this}startingAt(e){return this.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},this}endingAt(e){return this.endPos={start:e.start??this.startPos?.start??0,end:e.end,line:e.line??this.startPos?.line??1,column:e.column??this.startPos?.column??1},this}build(){const e={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(e.body=this.body),this.implicitTarget&&(e.implicitTarget=this.implicitTarget),this.modifiers&&(e.modifiers=this.modifiers),this.originalCmd&&(e.originalCommand=this.originalCmd),e}clone(){const e=new Sr(this.name);return e.args=[...this.args],e.body=this.body?[...this.body]:void 0,e.implicitTarget=this.implicitTarget,e.isBlocking=this.isBlocking,e.modifiers=this.modifiers?{...this.modifiers}:void 0,e.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function Tr(e,n){const r=[];let i="";const o=e.peek().start||0,s=e.peek().line||1,a=e.peek().column||1;if(e.checkIdentifierLike()){for(i=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),i+=":",e.checkIdentifierLike()&&(i+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=kr(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),r.push({type:"functionCall",name:i,args:t,start:o,end:e.getPosition().end,line:s,column:a})}else r.push({type:"string",value:i,start:o,end:e.getPosition().end,line:s,column:a})}const c=[...r],l={};for(;!wr(e);){if(e.check(x)||e.check(g)){e.advance();const t=Er(e,[w]);t&&(l.on=t);continue}if(e.check(w)){e.advance();const n=[];for(;!wr(e,[x,g]);){const t=e.savePosition(),r=e.parsePrimary();r&&n.push(r),e.savePosition()===t&&e.advance()}const r=n[0],i=n[n.length-1];l.with=t({type:"arrayLiteral",elements:n,...void 0!==r?.start?{start:r.start}:{},...void 0!==i?.end?{end:i.end}:{},...void 0!==r?.line?{line:r.line}:{},...void 0!==r?.column?{column:r.column}:{}});continue}const n=e.savePosition(),r=e.parsePrimary();r&&c.push(r),e.savePosition()===n&&e.advance()}const u=Sr.fromIdentifier(n).withArgs(...c);return Object.keys(l).length>0&&u.withModifiers(l),u.endingAt(e.getPosition()).build()}function Ar(e,t){const n=Sr.fromIdentifier(t);if(e.check(A)){const t=e.advance(),r=e.check(k)?e.advance():t;n.withModifier("the",{type:"literal",value:"event",start:t.start,end:r.end,line:t.line,column:t.column})}return n.endingAt(e.getPosition()).build()}function Cr(e,t){const n=[],r=()=>e.check(l)||t&&e.check(c);for(;!e.isAtEnd()&&!r();){if(Xn(e.peek())){e.advance();continue}if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))break;e.advance();const t=e.parseCommand();t&&n.push(t),(e.check(a)||e.check(u)||e.check(","))&&e.advance()}return n}const $r=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function jr(e,t,n){return null!==t&&!$r.has(t.value?.toLowerCase?.()??"")&&(e.checkIsCommand()||e.isCommand(n.value?.toLowerCase()))}function Or(e,t){const n=[];let r=!1;const i=e.savePosition();let o=null;for(let n=0;500>n&&!e.isAtEnd();n++){const n=e.peek();if(n.value===a){r=!0;break}if(n.value===l||n.value===S||"def"===n.value||n.value===x)break;if(void 0!==n.line&&n.line!==t.line&&jr(e,o,n))break;Xn(n)||(o=n),e.advance()}e.restorePosition(i);let s=!1;if(!r){const n=e.savePosition(),r=t.line,i=100;let o=!1,a=null;for(;!e.isAtEnd()&&i>e.current-n;){const t=e.peek(),n=t.value?.toLowerCase();if(o&&void 0!==t.line&&t.line!==r)break;if(n===S||"def"===n||n===x)break;if(n===c||n===l){t.line===r&&(s=!0);break}if(jr(e,a,t)){if(void 0!==t.line&&t.line!==r){s=!0;break}o=!0}Xn(t)||(a=t),e.advance()}e.restorePosition(n)}const u=r||s;let f;if(u)f=e.parseExpression();else{const n=[],r=20;let i=0,o=!0;for(;!e.isAtEnd()&&!e.check(a)&&(o||!e.checkIsCommand()&&!e.isCommand(e.peek().value))&&r>i;){o=!1;const t=e.savePosition();n.push(e.parseLogicalAnd()),e.savePosition()===t&&e.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:t.line,column:t.column}}if(n.push(f),u){xr(e,a);const r=Cr(e,!0);if(0===r.length&&e.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");n.push(dr(r,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}));let i=!1;if(e.check(c))if(e.advance(),e.check("if")){const t=e.peek();e.advance();const r=Or(e,t);n.push(dr([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column})),i=!0}else{const r=Cr(e,!1);n.push(dr(r,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}i||e.isAtEnd()||e.consume(l,"Expected 'end' after if block")}else{if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))throw Error("Expected command after if condition in single-line form");{e.advance();const r=e.parseCommand();n.push(dr([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}}return Sr.from(t).withArgs(...n).endingAt(e.getPosition()).build()}function Nr(e,t){const n=[],r={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(n.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();n.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();r.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const i=Sr.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const Rr=new Set(["my","its","your"]);function Lr(e){return{type:"literal",value:e,raw:e}}function Mr(e){const t={};if(xr(e,f)){const n=e.parseExpression();return n&&(t.for=n),t}if(!e.check(h))return t;e.advance();const n=e.peek();if(!n||!_n(n))return t;e.advance();let r=n.value;if(e.check(":")){e.advance();const t=e.peek();t&&_n(t)&&(e.advance(),r=`${r}:${t.value}`)}if(t.until=Lr(r),xr(e,v)){const n=Er(e);n&&(t.from=n)}return t}function Ir(e,t){const n=[],r=Er(e,[v]);r&&n.push(r);const i={};if(xr(e,v)){const t=Er(e);t&&(i.from=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(i).endingAt(e.getPosition()).build()}function qr(e,t){const n=[],r={};if(e.check("between")){e.advance();const t=[],n=Er(e,[u]);if(n&&"binaryExpression"===n.type&&"and"===n.operator)n.left&&t.push(n.left),n.right&&t.push(n.right);else{n&&t.push(n),xr(e,u);const r=Er(e,[v,x,f]);r&&t.push(r)}const i=t[0],o=t[t.length-1];r.between={type:"arrayLiteral",elements:t,...void 0!==i?.start?{start:i.start}:{},...void 0!==o?.end?{end:o.end}:{},...void 0!==i?.line?{line:i.line}:{},...void 0!==i?.column?{column:i.column}:{}}}else{const t=Er(e,[v,x]),i="asExpression"===t?.type?function(e){const t="string"==typeof e?e:e?.name;return"modal"===t||"non-modal"===t?t:void 0}(t.targetType):void 0;t&&void 0!==i&&t.expression?(n.push(t.expression),r.as=Lr(i)):t&&n.push(t),void 0===i&&e.check("modal")&&(e.advance(),r.as=Lr("modal"))}if(xr(e,v)||xr(e,x)){const t=Er(e);t&&(r.on=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers({...r,...Mr(e)}).endingAt(e.getPosition()).build()}function Hr(e){if(!e.check("using"))return{};if(e.advance(),!e.match("view"))throw Error("expected 'view transition' after 'using'");if(!e.match("transition"))throw Error("expected 'transition' after 'using view'");return{viewTransition:Lr("transition")}}function Pr(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=Er(e,[g]);t&&n.push(t)}const r={};if(xr(e,g)){const t=Er(e);t&&(r.to=t)}return Sr.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}function Br(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const r=e.peek();if(!r||!N.includes(r.value))return e.addError(`Expected operation keyword (${N.join(", ")}) after put expression, got: ${r?.value}`),null;let i=e.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=j:"at end of"===o||"at the end of"===o?i=O:"at"===i&&(e.check(C)||e.check(A)?(xr(e,A),e.check(C)&&(e.advance(),e.check(E)&&(e.advance(),i=j))):e.check(l)&&(e.advance(),e.check(E)&&(e.advance(),i=O)));const s=e.parseExpression();return s?Sr.fromIdentifier(t).withArgs(n).withModifier(i,s).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Vr=["afterbegin","afterend","beforebegin","beforeend","delete","innerhtml","innermorph","into","morph","none","outerhtml","outermorph","over"];function Fr(e,t){const n=[],r={};if(!e.isAtEnd()){const t=e.peek(),n=t?.value?.toLowerCase();n&&Vr.includes(n)&&(e.advance(),r.strategy=Lr(n))}const i="delete"===r.strategy?.value;xr(e,E);const o=i?e.parseExpression():Er(e,[w]);if(o&&n.push(o),!i&&xr(e,w)){const t=Er(e,["using"]);t&&(r.with=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers({...r,...Hr(e)}).endingAt(e.getPosition()).build()}function Dr(e,t){const n=[],r={};if(!(wr(e,["catch","finally"])||e.check("when")||e.check("where")||e.check(w))){const t=e.parseExpression();t&&n.push(t)}if(xr(e,w)){const t=function(e){if(!e)return null;const t="string"==typeof e.name?e.name:"string"==typeof e.value?e.value:null;return null===t?null:t.replace(/^\*/,"")}(e.parseExpression());null!==t&&(r.with=Lr(t))}const i=Sr.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}function Ur(e,t){const n=e.savePosition();let r=null,i=[];try{r=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end}}(e)??function(e){if(!e.check(T)&&!e.check("local"))return null;const t=e.advance(),n=e.advance();return{type:"identifier",name:n.value,scope:t.value,start:t.start,end:n.end}}(e)??function(e){if(!e.check(A))return null;const t=e.savePosition();e.advance();const n=e.parseExpression();if(!n)return e.restorePosition(t),null;if("binaryExpression"===n.type&&n.operator===E){const e=n.left,t=n.right;return yr(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(g)?n:(e.restorePosition(t),null)}(e),r||(r=e.parseExpression())}catch{e.restorePosition(n),r=null}if(!r){const t=function(e){if(e.match(":")){const t=e.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const t=[];for(;!(e.isAtEnd()||e.check(g)||e.check(a)||e.check(u)||e.check(c)||e.check(l));)t.push(e.parsePrimary());if(0===t.length)return{expression:null,tokens:[]};if(t.length>=4){const e=(e,t)=>e[t];if(e(t[0],"value")===A&&e(t[2],"value")===E){const n=t[1],r=t[3];return{expression:yr(ur(e(n,"value")||e(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:e(r,"value")||e(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:t[0].start??0,end:r.end??0,line:t[0].line??1,column:t[0].column??1}),tokens:[]}}}return 1===t.length?{expression:t[0],tokens:[]}:{expression:null,tokens:t}}(e);r=t.expression,i=t.tokens}if(!e.check(g)){const t=e.isAtEnd()?"end of input":e.peek().value;throw Error("Expected 'to' in set command, found: "+t)}e.advance();const o=e.parseExpression()??e.parsePrimary();let s;var f;e.check(x)&&(f=e.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||_r.has(f.value))&&(e.advance(),s=Er(e));const d=[];r?d.push(r):i.length>0&&d.push(...i);const h=Sr.fromIdentifier(t).withArgs(...d);return o&&h.withModifier("to",o),s&&h.withModifier("on",s),h.endingAt(e.getPosition()).build()}const _r=new Set(["me","my","it","its","you","your","yourself"]),zr=new Set(["top","middle","bottom","left","center","right","nearest"]);function Wr(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Zr(e){if(e.isAtEnd())return;const t=e.current,n=e.parsePrimary();return e.current===t?void 0:n}const Jr=new Set(["then","and","else","end","when","where","catch","finally"]);const Kr=new Set(["top","middle","bottom","left","center","right","nearest"]),Gr=new Set(["up","down","left","right"]),Xr=["of","smoothly","instantly","by","up","down","left","right"];function Yr(e,t){const n=e.peek(),r=e.resolveKeyword(n.value).toLowerCase();return("smoothly"===r||"instantly"===r)&&(e.advance(),t.behavior=Wr("smoothly"===r?"smooth":"instant",n),!0)}function Qr(e,t){const n=[],r={};if(xr(e,"url"),!e.isAtEnd()&&ai(e)){const t=li(e);t&&n.push(t)}else{const t=Er(e,["with"]);t&&n.push(t)}if(xr(e,"with")){xr(e,"title");const t=Er(e);t&&(r.title=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}function ei(e,t){if(e.isAtEnd())return!0;const n=e.peek();return(!e.checkIsCommand()||"("!==e.peekAt(1)?.value)&&(!!wr(e,["catch","finally","on"])||gr(n,[...t.markers]))}function ti(e,t,n,r){const i=[],o={};if("none"!==r.positional){const t=r.continuation??[];for(;!ei(e,r);){const n="expression"===r.positional?e.parseExpression():e.parsePrimary();if(!n)break;if(i.push(n),e.match(","))continue;if("primary"===r.positional)continue;const o=n.name;if("identifier"===n.type&&o&&t.includes(o.toLowerCase()))continue;const s=e.peek();if(!s||!t.includes(s.value.toLowerCase()))break;e.advance(),i.push(e.createIdentifier(s.value))}}const s=new Set(r.commaList??[]);for(;!e.isAtEnd()&&gr(e.peek(),[...r.markers]);){const t=e.advance().value,n=e.resolveKeyword(t).toLowerCase();let r=e.parseExpression();if(r&&s.has(n)&&e.check(",")){const t=[r];for(;e.match(",");){const n=e.parseExpression();if(!n)break;t.push(n)}const n=t[0];r={type:"arrayLiteral",elements:t,start:n.start,end:t[t.length-1].end,line:n.line,column:n.column}}r&&(o[n]=r)}const a=Sr.from(t).withName(n).withArgs(...i);return Object.keys(o).length>0&&a.withModifiers(o),a.endingAt(e.getPosition()).build()}const ni=new Map([["put",Br],["trigger",Tr],["send",Tr],["remove",Ir],["take",function(e,t){const n=[],r={},i=Er(e,[v,f]);if(i&&n.push(i),xr(e,v)){const t=Er(e,[f]);t&&(r.from=t)}if(xr(e,f)){const t=Er(e);t&&(r.for=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}],["toggle",qr],["set",Ur],["add",(e,t)=>Pr(e,ii(t))],["halt",Ar],["measure",Nr],["js",function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const r=e.peek().start,i=function(e,t){const n=e.getInputSlice(t);if(!n)return t;let r=0;for(;n.length>r;){const e=n[r];if("'"!==e&&"\u2019"!==e&&"\u2018"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===e&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==e&&"E"!==e||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return t+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==e;)"\\"===n[r]&&r++,r++;r++}}return t+n.length}(e,r);for(;!e.isAtEnd()&&!e.check(l)&&e.peek().start<i;)e.advance();e.consume(l,"Expected end after js code body");const o={type:"literal",value:e.getInputSlice(r,i).trim(),start:t.start,end:e.getPosition().end},s={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Sr.fromIdentifier(t).withArgs(o,s).endingAt(e.getPosition()).build()}],["go",function(e,n){const r=[],i={};for(;!wr(e,["when","where","catch","finally"]);){const n=e.peek(),o=e.resolveKeyword(n.value).toLowerCase();if("to"!==o&&"the"!==o)if("back"!==o&&"forward"!==o||0!==r.length||i.url){if("url"===o){e.advance();const t=ai(e)?li(e):Zr(e);t&&(i.url=t);continue}if("in"===o){e.advance();const t=e.peek(),n=[];for(;!e.isAtEnd()&&["new","window"].includes(e.peek().value.toLowerCase());)n.push(e.advance().value.toLowerCase());i.in=Wr(n.join(" ")||t.value,t);continue}if(!zr.has(o)||i.position){if("of"===o){e.advance(),"the"===e.resolveKeyword(e.peek().value).toLowerCase()&&e.advance();const t=Zr(e);t&&(i.of=t);continue}if("smoothly"!==o&&"instantly"!==o){if("+"===n.value||"-"===n.value||"number"===n.kind){let r=1;"+"!==n.value&&"-"!==n.value||(e.advance(),"-"===n.value&&(r=-1));const o=e.peek();if("number"!==o.kind)break;e.advance();let s=o.end;const a=e.peek();e.isAtEnd()||"px"!==a.value||a.start!==o.end||(s=e.advance().end),i.by=t({type:"literal",value:r*Number(o.value),raw:o.value,start:n.start,end:s,line:n.line,column:n.column});continue}if(0===r.length&&!i.of&&!i.url){if(ai(e)){const t=li(e);if(t){r.push(t);continue}}const t=Zr(e);if(t){r.push(t);continue}}break}e.advance(),i.behavior=Wr("smoothly"===o?"smooth":"instant",n)}else e.advance(),i.position=Wr(o,n)}else e.advance(),i[o]=Wr(o,n);else e.advance()}return Sr.fromIdentifier(n).withArgs(...r).withModifiers(i).endingAt(e.getPosition()).build()}],["push",Qr],["replace",Qr],["scroll",(e,n)=>function(e,n){return e.isAtEnd()?null:"to"===e.resolveKeyword(e.peek().value).toLowerCase()?function(e,t){const n=[],r={};for(e.advance();!wr(e,["when","where","catch","finally"]);){const t=e.peek(),i=e.resolveKeyword(t.value).toLowerCase();if("the"!==i)if(!Kr.has(i)||r.position){if("of"===i){e.advance();const t=Er(e,Xr);t&&(r.of=t);continue}if(!Yr(e,r)){if(0===n.length&&!r.of){const t=Er(e,Xr);if(t){n.push(t);continue}}break}}else e.advance(),r.position=Wr(i,t);else e.advance()}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(e,n):function(e){for(let t=0;12>t;t++){const n=e.peekAt(t);if(!n)return!1;const r=e.resolveKeyword(n.value).toLowerCase();if("by"===r)return!0;if(Jr.has(r))return!1}return!1}(e)?function(e,n){const r=[],i={};for(;!wr(e,["when","where","catch","finally"]);){const n=e.peek(),o=e.resolveKeyword(n.value).toLowerCase();if(Gr.has(o))e.advance(),i.direction=Wr(o,n);else{if("by"===o){e.advance();let n=1;const r=e.peek();"+"!==r.value&&"-"!==r.value||(e.advance(),"-"===r.value&&(n=-1));const o=e.peek();if("number"===o.kind){e.advance();const r=e.peek();let s=o.end;e.isAtEnd()||"px"!==r.value||r.start!==o.end||(s=e.advance().end),i.by=t({type:"literal",value:n*Number(o.value),raw:o.value,start:o.start,end:s,line:o.line,column:o.column})}else{const t=Er(e,Xr);t&&(i.by=t)}continue}if(!Yr(e,i)){if(0===r.length){const t=Er(e,Xr);if(t){r.push(t);continue}}break}}}return Sr.fromIdentifier(n).withArgs(...r).withModifiers(i).endingAt(e.getPosition()).build()}(e,n):null}(e,n)??si(e,n)],["tell",function(e,t){const n=e.parseExpression();if(!n)throw Error("tell command requires a target expression");e.check(g)&&e.advance();const r=[];for(;!e.isAtEnd();){if(e.checkIsCommand()){try{e.advance();const t=e.parseCommand();if(!t)break;r.push(t)}catch{break}if(e.match(u)||e.match(a))continue;if(e.check(c))break;if(e.check(l)){e.advance();break}if(e.checkIsCommand())continue;break}break}if(0===r.length)throw Error("tell command requires at least one command after the target");return Sr.fromIdentifier(t).withArgs(n,...r).endingAt(e.getPosition()).build()}],["pick",function(e,t){const n=Sr.fromIdentifier(t);xr(e,A);const r=e.peek().value,i=e=>({type:"literal",value:e,start:t.start,end:t.end}),o=()=>{if(!e.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return e.parseExpression()};if("first"===r){e.advance();const t=e.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===r){e.advance();const t=e.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===r){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const r=o(),s=n.withArgs(r).withModifier("variant",i("random"));return t&&s.withModifier("count",t),s.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?i("start"):e.parsePrimary();let s=!1;(e.match("to")||e.match(".."))&&(e.match("end")?s=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=o(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",t).withModifier("rangeMode",i(a));return s?l.withModifier("rangeEnd",i("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(e.getPosition()).build()}if("match"===r||"matches"===r){e.advance(),e.match("of");const t=e.parsePrimary();let s;e.matchOperator("|")&&(s=e.advance().value);const a=o(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",t);return s&&c.withModifier("flags",i(s)),c.endingAt(e.getPosition()).build()}return si(e,t)}],["start",function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd("start view transition");return Sr.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}],["swap",Fr],["morph",Fr],["show",Dr],["hide",Dr],["process",(e,t)=>function(e,t){if(!e.check("partials"))return null;const n=[];if(e.advance(),xr(e,b)){const t=Er(e,["using"]);t&&n.push(t)}const r=Hr(e),i=Sr.fromIdentifier(t).withArgs(...n);return Object.keys(r).length>0&&i.withModifiers(r),i.endingAt(e.getPosition()).build()}(e,t)??si(e,t)]]),ri=new Set(ni.keys());function ii(e){return{kind:"identifier",value:e.name,start:e.start??0,end:e.end??0,line:e.line??0,column:e.column??0}}const oi={positional:"primary",markers:[]};function si(e,t){return ti(e,ii(t),t.name.toLowerCase(),oi)}function ai(e){const t=e.peek();if("/"===t.value)return!0;if(e.checkIdentifierLike()){const n=e.peekAt(1);return!!n&&":"===n.value&&n.start===t.end}return!1}const ci=new Set(["{",")"]);function li(e){const t=e.savePosition(),n=e.peek();let r="",i=null;for(;!e.isAtEnd();){const t=e.peek();if(i&&t.start!==i.end)break;if("$"===t.value&&"{"===e.peekAt(1)?.value){e.advance();let n=e.advance(),o=1;for(;!e.isAtEnd()&&o>0;)n=e.advance(),"{"===n.value?o++:"}"===n.value&&o--;r+=e.getInputSlice(t.start,n.end),i=n;continue}if(ci.has(t.value))break;i=e.advance(),r+=i.value}if(!r||"/"===r)return e.restorePosition(t),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 ui(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function fi(e){const t=[],n=e.getPosition();do{if(!e.checkIdentifierLike())break;const n=e.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};e.consume(":","Expected ':' after property name in fetch named arguments");const i=e.parsePrimary();i&&t.push({key:r,value:i})}while(e.match(",")&&!e.isAtEnd());const r=e.getPosition();return{type:"objectLiteral",properties:t,start:n.start,end:r.end,line:n.line,column:n.column}}const di={positional:"none",markers:[],syntax:""},hi=e=>({positional:"expression",markers:[],syntax:e}),mi=hi("beep! [<expression>, \u2026]"),pi={append:{positional:"expression",markers:["to"],syntax:"append <value> [to <target>]"},prepend:{positional:"expression",markers:["to"],syntax:"prepend <value> [to <target>]"},make:{positional:"primary",markers:["a","an","from","called"],commaList:["from"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},throw:{positional:"primary",markers:[],syntax:"throw <error>"},"beep!":mi,beep:mi,blur:hi("blur [<target>]"),break:di,breakpoint:di,call:hi("call <expression>"),clear:hi("clear <target>"),close:hi("close [<target>]"),continue:di,copy:{positional:"expression",markers:["to"],syntax:"copy <source> [to clipboard]"},default:{positional:"expression",markers:["to"],syntax:"default <target> to <value>"},empty:hi("empty [<target>]"),exit:di,focus:hi("focus [<target>]"),get:hi("get <expression>"),log:hi("log <expression>[, <expression>\u2026]"),open:hi("open [<dialog>] [as modal|non-modal]"),"pseudo-command":hi("<method>(\u2026) [on|from|\u2026] <target>"),render:{positional:"expression",markers:["with"],syntax:"render <template> [with <variables>]"},reset:hi("reset [<form>]"),return:hi("return [<value>]"),select:hi("select [<target>]"),settle:{positional:"expression",markers:["for"],syntax:"settle [<target>] [for <timeout>]"}},yi={positional:"expression",markers:[],continuation:["into","from","to","with","by","at","before","after","over"]};function bi(e){return pi[e.toLowerCase()]??null}const gi=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]),vi=new Set(["s","seconds","ms","milliseconds"]);class wi{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors],e.recovered=!0),e}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}const e=this.peek(),t=e&&ae(e.value)?e.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==t){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const e=this.peekAt(1);if(null!==e&&("init"===e.value||"on"===e.value||"def"===e.value||void 0!==ae(e.value))){this.advance();continue}}if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def")){const t=this.peek(),n=t?ae(t.value):void 0;if(n){const t=this.advance(),r=n(this.getContext(),t);r&&e.push(r);continue}break}{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){Hn("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const t=[e];Hn(`\u2705 PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){Hn(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(Hn("\u2705 PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,Hn(`\u2705 PARSER: Added event handler, now have ${t.length} statements total`)),Hn(`\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 Hn("\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(t),tokens:this.tokens,error:this.error};Hn("\u2705 PARSER: No more event handlers, at end of input");break}}return Hn(`\u2705 PARSER: Finished parsing, creating Program node with ${t.length} statements`),this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return n&&["number","string","identifier"].includes(e.kind)?this.addError(`Unexpected token: ${e.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+e.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,warnings:this.warnings}}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,n=this.prattCache.get(t);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),i=wi.PRATT_TABLE.get(r.value);let o;if(i?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();o=i.prefix.handler(e,this.makePrattContext())}else o=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(o,t);if(e){o=e;continue}}const n=wi.PRATT_TABLE.get(t.value);if(!n?.infix){if(D.has(t.value)||U.has(t.value))break;break}const[r]=n.infix.bp;if(e>r)break;if("="===t.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(e){Hn("arrow body discarded after error:",e instanceof Error?e.message:e+"")}return this.createErrorNode()}if("+"===t.value||"-"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("+"===e.value||"-"===e.value))return this.addError(`Invalid operator combination: ${t.value}${e.value}`),o}if("*"===t.value||"/"===t.value||"%"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("*"===e.value||"/"===e.value||"%"===e.value||"+"===e.value||"-"===e.value))return this.addError("*"===t.value&&"*"===e.value?"Unexpected token: "+e.value:`Invalid operator combination: ${t.value}${e.value}`),o}const i=this.advance();if(this.isAtEnd()&&!wi.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(t,{node:o,endPos:this.current}),o}tryParseStringPostfix(e,t){const n=t.value;let r=null;if(gi.has(n)||vi.has(n)&&this.isNumericPostfixRoot(e)?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:e,unit:r,start:e.start,end:i.end,line:e.line,column:e.column}}isNumericPostfixRoot(e){const t=e;return"literal"===t.type&&"number"==typeof t.value||("unaryExpression"!==t.type||"-"!==t.operator&&"+"!==t.operator?!("binaryExpression"!==t.type||!["+","-","*","/"].includes(t.operator??"")):void 0!==t.argument&&this.isNumericPostfixRoot(t.argument))}canStartOperand(e){if(!e)return!1;const t=e.value;return!D.has(t)&&!U.has(t)&&("number"===e.kind||"string"===e.kind||"identifier"===e.kind||"symbol"===e.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(t))}makePrattContext(){const e=this;return{peek:()=>e.tokens.length>e.current?e.tokens[e.current]:void 0,advance:()=>{const t=e.tokens[e.current];return e.current++,t},parseExpr:t=>e.parseExpressionPratt(t),isStopToken:()=>{const t=e.tokens[e.current];return!t||D.has(t.value)||U.has(t.value)},atEnd:()=>e.current>=e.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else if("wait"===e.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):L(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):M(e)}createCommandFromIdentifier(e){const t=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(t))return this.parseCompoundCommand(e);const n={kind:"identifier",value:e.name,start:e.start??0,end:e.end??0,line:e.line??0,column:e.column??0};return ti(this.getContext(),n,t,bi(t)??yi)}isCompoundCommand(e){return ri.has(e.toLowerCase())}parseCompoundCommand(e){return function(e,t){const n=ni.get(t.name.toLowerCase());return n?n(e,t):null}(this.getContext(),e)}parsePutCommand(e){return Br(this.getContext(),e)}parseSetCommand(e){return Ur(this.getContext(),e)}parseHaltCommand(e){return Ar(this.getContext(),e)}parseMeasureCommand(e){return Nr(this.getContext(),e)}parseTriggerCommand(e){return Tr(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(Hn("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){Hn("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){Hn(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&&(Hn("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(Hn("\u2705 Parsed command:",r.name),t.push(r),e=!0)}catch(e){Hn("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n,this.recordDropped("Discarded a command that failed to parse: "+(e instanceof Error?e.message:e+""))}}else this.checkIdentifier()&&Hn("\u274c IDENTIFIER is not a command:",this.peek().value);if(!e){Hn("\u274c No command parsed, breaking. Current token:",this.peek().value),this.isAtEnd()||n()||this.recordDropped(`Not a command, and the rest of the body was discarded: '${this.peek().value}'`);break}Hn("\ud83d\udccd After parsing command, current token:",this.peek().value);const o=this.current;for(;!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)Hn("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.recordDroppedRange(o,this.current),this.match("then","and",","))Hn("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){Hn("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}Hn("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const t of e)if(this.check(t)){r=t;break}return this.check("end")||e.some(e=>this.check(e))||(r=""),Hn("\u2705 parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(e="repeat"){const{commands:t}=this.parseCommandListUntilTerminator([]);if(Hn('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw Hn('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${e} block`);return Hn('\u2705 Found "end", consuming it'),this.advance(),t}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",i=null,o=null,s=null,a=null,c=null,l=null;if(e.check(f)){e.advance(),r=f;const t=e.peek();_n(t)&&(c=t.value,e.advance()),e.check(b)&&(e.advance(),a=e.parseExpression())}else if(e.check(b))e.advance(),r=f,c="it",a=e.parseExpression();else if(e.check(d))e.advance(),r=d,s=e.parseExpression();else if(e.check(h))if(e.advance(),r=h,e.check(k)){e.advance(),r="until-event";const t=e.peek();if(Hn("\ud83d\udccd Parsing event name, current token:",{value:t.value,kind:t.kind}),!_n(t)&&!Fn(t))throw Error('Expected event name after "event"');if(i=t.value,e.advance(),Hn("\u2705 Got event name:",i,"Next token:",e.peek().value),Hn('\ud83d\udd0d Checking for "from", current token:',e.peek().value),e.check(v)){Hn('\u2705 Found "from", advancing...'),e.advance(),Hn('\ud83d\udccd After consuming "from", current token:',e.peek().value),xr(e,A)&&Hn('\u2705 Found "the", advancing...');const t=e.peek();Hn("\ud83d\udd0d Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),o=e.parsePrimary(),Hn("\u2705 After parsePrimary, eventTarget:",o)}else Hn('\u274c No "from" found, skipping target parsing')}else s=e.parseExpression();else e.check(m)?(e.advance(),r=m):(l=e.parseExpression(),e.check(p)&&(e.advance(),r=p));let u,g=null;if(e.check(w)){const t=e.peekAt(1);t&&t.value.toLowerCase()===y&&(e.advance(),e.advance(),g=y)}else if(e.check(y)){e.advance();const t=e.peek();_n(t)?(g=t.value,e.advance()):g=y}let E=null,x=!1;if(r===m){const t=e.parseRepeatBody();if(u=t.commands,"else"===t.terminator)e.advance(),E=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(x=!0,r=t.terminator,e.advance(),s=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();u=t.commands,t.hasElse&&(e.advance(),E=e.parseCommandListUntilEnd())}const S={start:t.start,end:t.end,line:t.line,column:t.column},T={loopType:hr(r,S)};c&&(T.for=hr(c,S)),a&&(T.in=a),l&&(T.times=l),s&&(T["while"===r?"while":"until"]=s),i&&(T.event=hr(i,S)),o&&(T.from=o),g&&(T.index=hr(g,S)),n.push(dr(u,{...S,end:S.end||0})),null!==E&&n.push(dr(E,{...S,end:S.end||0}));const C=Sr.from(t).withArgs(...n).withModifiers(T);return x&&C.withModifier("bottomTested",{type:"literal",value:!0,...S}),C.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const n=[];let r=null,i=null;e.check("each")&&e.advance();const o=e.peek();if(!_n(o))throw Error('Expected variable name after "for"');if(r=o.value,e.advance(),!e.check(b))throw Error('Expected "in" after variable name in for loop');if(e.advance(),i=e.parseExpression(),!i)throw Error('Expected collection expression after "in"');let s=null;if(e.check(w)){const t=e.peekAt(1);t&&t.value.toLowerCase()===y&&(e.advance(),e.advance(),s=y)}else if(e.check(y)){e.advance();const t=e.peek();_n(t)?(s=t.value,e.advance()):s=y}const a=e.parseCommandListUntilEnd("for");n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(hr(r,c)),n.push(i),s&&n.push(hr(s,c)),n.push(dr(a,{...c,end:c.end||0})),Sr.from({...t,value:"repeat"}).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const n=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!wr(e)){const r=e.parseExpression();return n.push(r),Sr.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{if(e.checkTimeExpression()||e.checkLiteral()||e.check("(")){if(r.push({kind:"duration",expr:e.parseExpression()}),e.check("or")){e.advance();continue}break}const t=e.peek();if(!_n(t))throw Error('Expected event name or duration after "for"');const n=t.value;e.advance();const i=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!_n(t))break;i.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(r.push({kind:"event",name:n,params:i}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let i=null;e.check(v)&&(e.advance(),xr(e,A),i=e.parsePrimary());const o={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(pr(r.map(e=>mr("duration"===e.kind?[{key:ur("duration",o),value:e.expr}]:[{key:ur("name",o),value:lr(e.name,`"${e.name}"`,o)},{key:ur("args",o),value:pr(e.params.map(e=>lr(e,`"${e}"`,o)),o)}],o)),o)),i&&n.push(i)}return Sr.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const n=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=e.advance().value,i=e.previous();if(n.push(ur(r,{start:i.start,end:i.end,line:i.line,column:i.column})),e.check("(")){e.advance();const r=[];for(;!e.isAtEnd()&&!e.check(")");)if(r.push(kr(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),r.length>0){const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(mr(r.map(e=>({key:e.name?ur(e.name,i):lr("_positional","_positional",i),value:e.value})),i))}}return Sr.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let i=null,o=null;const s=e.peek();if(e.checkAnySelector()||e.checkContextVar()||e.check("<")||_n(s)&&Rr.has(s.value)){const t=e.parsePrimary();("possessiveExpression"===t.type||"memberExpression"===t.type&&!t.computed)&&t.object&&t.property?.name?(o=t.object,i={type:"string",value:t.property.name,start:s.start||0,end:e.getPosition().end,line:s.line,column:s.column}):(o=t,e.check("'s")&&e.advance())}const a=e.peek();if(!i&&(_n(a)||"*"===a.value)){let t="";e.check("*")&&(t="*",e.advance());const n=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);n&&(t+=n,i={type:"string",value:t,start:a.start||0,end:e.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),!e.check(g))throw Error('Expected "to" keyword after property in transition command');e.advance();const c=e.parseExpression();if(r.to=c,e.check("over")){e.advance();const t=e.parseExpression();r.over=t}if(e.check(w)){e.advance();const t=e.parsePrimary();r.with=t}return Sr.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return Pr(this.getContext(),e)}parseIfCommand(e){return Or(this.getContext(),e)}parseRemoveCommand(e){return Ir(this.getContext(),e)}parseToggleCommand(e){return qr(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("?.")){const t=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(e,this.createIdentifier(t.value),!1);n.optional=!0,e=n}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}else{if(!this.check("'s"))break;{let t;this.advance(),this.check("*")?(this.advance(),t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):Gn(this.peek())&&this.peek().value.startsWith("@")?t=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),t=this.advance().value,this.consume("]","Expected ']' after attribute reference")):t=this.consumeIdentifierLike("Expected property name after possessive").value,e=this.createPossessiveExpression(e,this.createIdentifier(t))}}return e}parsePrimary(){if(this.check("*")){const e=this.current;if(this.advance(),!this.isAtEnd()&&_n(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),n=this.processEscapeSequences(t);return this.createLiteral(n,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value,t=e.slice(1,-2).trim(),n=this.createSelector(t);return n.fromQuery=!0,n.raw=e,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column-2}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end,line:e.line,column:e.column-1}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if((!e||"end"!==e.value&&"else"!==e.value&&"then"!==e.value)&&(this.matchPredicate(Yn)||this.matchPredicate(Vn)||this.matchPredicate(Dn)||this.matchPredicate(Bn)||this.matchPredicate(Fn))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(e.value):this.parseNavigationFunction(e.value)}const t=this.check(".")||this.check("?.");return"my"!==e.value||t?"its"!==e.value||t?"your"!==e.value||t?"the"===e.value?this.parseTheXofY():"values"===e.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:e.line,column:e.column}):this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Gn(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const e=this.peek().start;this.advance();const t=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}t.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:t,body:this.parseExpression(),start:e,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const e=this.advance().value;return this.createLiteral(e,"$"+e)}if(this.checkIdentifier()){const e=this.advance();let t=this.createIdentifier(e.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const e=this.advance();t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}}return t}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.check("["))this.advance(),t=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const e=this.previous().value,n=e.slice(1,-1);t=this.createLiteral(n,e)}else{if(!this.check("-")&&!this.checkPredicate(Yn))return this.addError("Expected property name in object literal"),this.createErrorNode();{let e="",n=!1;for(;this.check("-");)this.advance(),e+="-",n=!0;for(this.checkPredicate(Yn)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",n=!0,this.checkPredicate(Yn)&&(e+=this.advance().value);if(""===e||"-"===e)return this.addError("Expected property name in object literal"),this.createErrorNode();t=n?this.createLiteral(e,e):this.createIdentifier(e)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(e.push({key:t,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Yn))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);n=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,o=0,s=-1,a=-1;for(;!this.isAtEnd()&&(0!==o||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),0>s&&"number"==typeof e.start&&(s=e.start),"number"==typeof e.end&&(a=e.end),"$"===e.value&&this.check("{")&&(i=!0),"{"===e.value&&o++,"}"===e.value&&o--}const c=this.originalInput&&s>=0&&a>s?this.originalInput.slice(s,a):r.join(""),l=i?{type:"templateLiteral",value:c,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(c,c);if(t.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),n=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column},arguments:r,isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:i,errorHandler:o,finallyHandler:s}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==o&&{errorHandler:o},...void 0!==s&&{finallyHandler:s},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseErrorAndFinallyBlocks(){let e,t,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(e=this.advance().value),t=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==e&&{errorSymbol:e},...void 0!==t&&{errorHandler:t},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,i){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==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(e,t){const n=e.callee.name,r=this.peek();if(!(wi.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Yn(r)&&!this.isCommand(r.value)||Dn(r)))return{node:this.callExprToCommandNode(e,t),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!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),wi.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{o=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,i,o,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(Hn("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return Hn("\u26a0\ufe0f Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseTemporalKeywordModifiers(e){if(!this.check("debounced")&&!this.check("throttled"))return;const t=this.advance().value.toLowerCase(),n="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const i=this.advance(),o=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):r.endsWith("s")?1e3*parseFloat(r):parseInt(r,10);e[n]=o,Hn(`\ud83d\udd27 parseEventHandler: Parsed '${t} at ${i.value}' (${o}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);e[n]=r,Hn(`\ud83d\udd27 parseEventHandler: Parsed '${t} at ${r}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`);var r}parseEventHandler(){Hn("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const e=[];let t=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const e=this.tokens[this.current+1],n=e?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),t=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),Hn("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),Hn("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),Hn("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+t)}let r;if(Hn("\ud83d\udd27 parseEventHandler: Total events parsed: "+e.join(", ")),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);r=e?.name,Hn(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const i=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();i.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),Hn("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const o={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)o.once=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)o.prevent=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)o.stop=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),n=parseInt(t.value,10);if(isNaN(n))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(o.debounce=n,Hn(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(o.throttle=n,Hn(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else Hn(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${e}'`)}let s,a,c,l;if(this.parseTemporalKeywordModifiers(o),t&&(o.once=!0),Object.keys(o).length>0&&Hn("\ud83d\udd27 parseEventHandler: Parsed modifiers:",o),this.match("[")&&(s=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();a=e.value,Hn(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${e.kind})`),this.parseTemporalKeywordModifiers(o)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value,Hn("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(Hn("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),Hn("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(Hn(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(Hn(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){Hn("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment()){Hn("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();continue}if(this.check("end")){Hn("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){Hn(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const n=this.parseCommand();u.push(n);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.peek().value,t=this.parseCommandWithErrorRecovery();t?(u.push(t),Hn("\u2705 parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value))):this.recordDropped(`Command '${e}' failed to parse and was discarded`)}}else{if(!this.checkIdentifier()){this.isAtEnd()||this.check("end")||this.check("catch")||this.check("finally")||this.recordDropped(`Not a command, and the rest of the handler body was discarded: '${this.peek().value}'`);break}{const e=this.peek();if(this.isCommand(e.value)){const t=this.parseCommandWithErrorRecovery();t?u.push(t):this.recordDropped(`Command '${e.value}' failed to parse and was discarded`)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){Hn("\u26a0\ufe0f Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator){this.recordDroppedExpression(e);break}{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name)){this.recordDroppedExpression(e);break}{const n={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};u.push(n)}}}}}}const e=this.current;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.recordDroppedRange(e,this.current),!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===e.length?e[0]:e.join("|"),events:e,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 Hn(`\ud83d\udd27 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),p}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const i=new Set(r),o=[];let s;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Yn(e)?(r.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let s;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),n=i.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),s=t.value,this.advance())}}const{commands:a,terminator:c}=this.parseCommandListUntilTerminator(["catch","finally"]);let l,u,f;if("catch"!==c&&"finally"!==c||({errorSymbol:l,errorHandler:u,finallyHandler:f}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const d={type:"eventHandler",event:t,commands:n(a),...void 0!==l&&{errorSymbol:l},...void 0!==u&&{errorHandler:n(u)},...void 0!==f&&{finallyHandler:n(f)},...void 0!==s&&{target:s},...r.length>0&&{args:r},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};o.push(d)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}s={type:"initBlock",commands:n(this.parseCommandBlock(["end"])),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:r,eventHandlers:o,...void 0!==s?{initBlock:s}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,n=this.parseCommand();for(this.error&&this.error!==t&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(Hn("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)Hn("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){Hn('\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 t=this.peek(),n=this.getPosition(),r="Expected command, got: "+t.value;this.addError(r);const i=br(n,r,t.value);if(e.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===e.length?e[0]:function(e){return{type:"CommandSequence",commands:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1}}(e)}isTokenKeyword(e,t){return gr(e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();if(t.push(e),this.match("then","and",","))continue}}return t}parseCommand(){const e=this.parseCommandCore();if(e&&"command"===e.type&&!e.body&&(this.check("when")||this.check("where"))){const t=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(e.modifiers={...e.modifiers??{},[t]:n})}return e}parseCommandCore(){const e=this.previous();let n=e.value;if("beep"===n&&this.check("!")&&(this.advance(),n="beep!"),"fetch"===n)return function(e,n){const r={};let i=null;if(!e.isAtEnd()&&ai(e)&&(i=li(e)),i||(i=e.parsePrimary()),!i)return e.addError("fetch requires a URL"),Sr.from(n).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(r.with=e.parsePrimary());for(let n=0;3>n&&!e.isAtEnd();n++)if(!e.check("as")||r.as){if(!e.check("with")||r.with){if(e.check("do")&&!r.doNotThrow){const n=e.peekAt(1),i=e.peekAt(2);if("not"===n?.value&&"throw"===i?.value){const n=e.advance();e.advance();const i=e.advance();r.doNotThrow=t({type:"literal",value:!0,start:n.start,end:i.end,line:n.line,column:n.column});continue}}break}e.advance(),r.with=ui(e)?fi(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||xr(e,"a")||xr(e,"an"),r.as=e.parsePrimary();const o=Sr.from(n).withArgs(i).endingAt(e.getPosition());return Object.keys(r).length>0&&o.withModifiers(r),o.build()}(this.getContext(),e);const r=n.toLowerCase();return"repeat"===r?this.parseRepeatCommand(e):"for"===r?this.parseForCommand(e):"if"===r||"unless"===r?this.parseIfCommand(e):"wait"===r?this.parseWaitCommand(e):"install"===r?this.parseInstallCommand(e):"transition"===r?this.parseTransitionCommand(e):"add"===r?this.parseAddCommand(e):this.isCompoundCommand(r)?this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||{type:"command",name:r,args:[],partial:!0,start:(i=this.getPosition()).start,end:i.end,line:i.line,column:i.column}:"increment"!==n&&"decrement"!==n||this.isAtEnd()?ti(this.getContext(),e,n,bi(n)??yi):function(e,t){const n=t.value,r="increment"===n?"+":"-";let i=!1;e.check(T)&&(i=!0,e.advance());const o=e.parseExpression();if(!o)throw Error("Expected variable or expression after "+n);let s;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);s=t}else s=lr(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let a=o;i&&"identifier"===o.type&&(a={...o,scope:"global"});const c=fr(r,o,s,{start:t.start,end:e.previous().end,line:t.line,column:t.column});return c.coerceNumeric=!0,Sr.from(t).withName("set").withArgs(a).withModifier("to",c).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(this.getContext(),e);var i}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=this.getPosition(),n=[];if(this.match("of"))n.push(this.parseExpression());else{if(this.check("("))return this.finishCall(ur(e,t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||n.push(this.parsePrimary())}const r=this.createCallExpression(ur(e,t),n);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(r.relativePositional=e)}return r}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let e,t,n,r=!1,i=!1;return this.match("from")&&(e=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(t=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=!0),{from:e,within:t,inElt:n,inSearch:r,wrapping:i}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;return["first","last","next","previous","random","closest"].includes(t)?(this.advance(),this.parseNavigationFunction(t)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parseCall(),line:e.line,column:e.column}):this.createIdentifier(t))}parseContextPropertyAccess(e){const t=this.getPosition(),n=()=>ur(e,t);if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(n(),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 t="*"+e;return this.createMemberExpression(n(),this.createIdentifier(t),!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(n(),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Gn(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(n(),this.createIdentifier(e.value),!1)}const t=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(n(),this.createIdentifier(t.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;I(t)&&Hn(`\ud83d\udca1 Tip: CSS functions like ${t}() should be quoted for clean parsing. Use '${t}(...)' or \`${t}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return lr(e,t,this.getPosition())}createIdentifier(e){return ur(e,this.getPosition())}createBinaryExpression(e,t,n){return fr(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}spanFromLeftmost(e){const t=this.getPosition(),n=e?.start;return"number"==typeof n&&t.start>n?this.originalInput?{...wt(this.originalInput,n),start:n,end:t.end}:{...t,start:n}:t}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.spanFromLeftmost(e))}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.spanFromLeftmost(e))}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.spanFromLeftmost(e))}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(Hn(`\u2705 createProgramNode: Called with ${e.length} statements`),0===e.length)return Hn("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return Hn(`\u2705 createProgramNode: Returning single statement (type=${e[0].type})`),e[0];const t={type:"Program",statements:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1};return Hn(`\u2705 createProgramNode: Returning Program node with ${e.length} statements, type=${t.type}`),t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!ar(t)||t.value!==e||(this.advance(),0))}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Wn)}matchSelector(){return this.matchPredicate(Wn)}checkAnySelector(){return this.checkPredicate(zn)}checkLiteral(){return this.checkPredicate(Zn)}checkIdentifierLike(){return this.checkPredicate(_n)}checkIsCommand(){return this.checkPredicate(Bn)}checkCommandTerminator(){return this.checkPredicate(cr)}checkReference(){return this.checkPredicate(Jn)}checkTimeExpression(){return this.checkPredicate(Kn)}checkEvent(){return this.checkPredicate(Fn)}checkContextVar(){return this.checkPredicate(Dn)}checkComment(){return this.checkPredicate(Xn)}checkIdentifier(){return this.checkPredicate(Yn)}checkKeyword(){return this.checkPredicate(Vn)}checkString(){return this.checkPredicate(Qn)}matchString(){return this.matchPredicate(Qn)}checkNumber(){return this.checkPredicate(er)}matchNumber(){return this.matchPredicate(er)}checkBoolean(){return this.checkPredicate(tr)}matchBoolean(){return this.matchPredicate(tr)}checkTemplateLiteral(){return this.checkPredicate(nr)}matchTemplateLiteral(){return this.matchPredicate(nr)}checkQueryReference(){return this.checkPredicate(rr)}matchQueryReference(){return this.matchPredicate(rr)}checkIdSelector(){return this.checkPredicate(ir)}checkClassSelector(){return this.checkPredicate(or)}checkCssSelector(){return this.checkPredicate(sr)}checkBasicOperator(){return this.checkPredicate(ar)}matchBasicOperator(){return this.matchPredicate(ar)}matchTimeExpression(){return this.matchPredicate(Kn)}matchIdentifierLike(){return this.matchPredicate(_n)}matchComparisonOperator(){return this.matchPredicate(Un)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Yn,e)}consumeIdentifierLike(e){return this.consumePredicate(_n,e)}consumeEvent(e){return this.consumePredicate(Fn,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(e){const t=this.current+e;return t>=0&&this.tokens.length>t?this.tokens[t]:null}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let n=t.start||0,r=t.line||1,i=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,i=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,i=e.column||1,0===n&&this.current>0&&(n=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;n=e.start||0,r=e.line||1,i=e.column||1,0===n&&(n=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const n=this.tokens[t];if(n&&("+"===n.value||"-"===n.value)){e=n;break}}n=e.start||0,r=e.line||1,i=e.column||1}this.error={message:e,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)},this.errors.push(this.error)}recordDroppedRange(e,t){const n=this.tokens.slice(e,t).filter(e=>!Xn(e)&&"end"!==e.value);0!==n.length&&this.recordDropped(`Discarded input the parser could not place: '${n.map(e=>e.value).join(" ")}'`)}recordDropped(e){const t=this.peek();this.errors.push({message:e,line:Math.max(1,t.line||1),column:Math.max(1,t.column||1),position:Math.max(0,t.start||0)})}recordDroppedExpression(e){this.recordDropped("Not a command, and the rest of the handler body was discarded: "+(e&&"string"==typeof e.name?`'${e.name}'`:"a "+(e?.type??"expression")))}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const e=this.peek();if("then"===e.value||"end"===e.value||"on"===e.value)return;if(this.checkIsCommand()||this.isCommand(e.value)&&!this.isKeyword(e.value))return;Hn("\u26a0\ufe0f synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();r.push(e.value)}this.consume("]","Expected ']' after attribute literal");const i=r.join("");if(!i.includes("="))return{type:"attributeAccess",attributeName:i.replace(/^@/,""),start:e,end:this.previous().end,line:t,column:n};const o="["+i+"]";return{type:"literal",value:o,raw:o,start:e,end:this.previous().end,line:t,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 e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const 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:e,end:this.previous().end,line:t,column:n}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isKeyword:this.isKeyword.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>e.peekAt(t),getInputSlice:(e,t)=>this.originalInput?0>e||e>=this.originalInput.length?"":void 0!==t?this.originalInput.slice(e,t):this.originalInput.slice(e):""};return Object.defineProperty(t,"current",{get:()=>e.current,set:t=>{e.current=t},enumerable:!0,configurable:!0}),t}}function Ei(e,t){const n=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const n=e.length;for(;n>t.position&&(gt(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==yt(t,1))if('"'!==n){if("'"===n||"'"===n){const e=yt(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||/\s/.test(t.input[t.position-1]??" ")||n.kind!==ht.IDENTIFIER&&n.kind!==ht.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)kt(t);else{const e=t.position;bt(t),bt(t),vt(t,ht.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===yt(t,1)){const e=t.position;bt(t),bt(t),vt(t,ht.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=e&&e.kind===ht.IDENTIFIER&&$.has(e.value.toLowerCase()),i=e&&e.kind===ht.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===ht.OPERATOR&&")"!==e.value&&"]"!==e.value||r||i||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(Rt(yt(t))||"{"===yt(t)||"-"===yt(t))){Tt(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===ht.IDENTIFIER&&V.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==ht.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(bt(t),vt(t,ht.SYMBOL,"[")):(bt(t),vt(t,ht.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const e=yt(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){Nt(t);continue}}qt(n)?$t(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(vt(t,ht.UNKNOWN,n),bt(t)):Ot(t):jt(t)}else bt(t),vt(t,ht.OPERATOR,"]")}else bt(t),vt(t,ht.OPERATOR,"}");else bt(t),vt(t,ht.OPERATOR,"{");else Ct(t)}else Tt(t);else It(t)?At(t):$t(t);else St(t)}else kt(t);else xt(t)}return t.tokens}(e);return new wi(n,t,e).parse()}function xi(e,t){const n=e.registry?.get(t);if(!n)throw Error(`Expression '${t}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function ki(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}wi.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),wi.PRATT_TABLE=J,wi.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];const Si=new Set(["literal","string","identifier","selector","attributeAccess","binaryExpression","unaryExpression","callExpression","memberExpression","possessiveExpression","propertyOfExpression","arrayLiteral","objectLiteral","templateLiteral","asExpression","betweenExpression","typeCheckExpression","collectionExpression","conditionalExpression","stringPostfix","blockLiteral","propertyAccess","contextReference","eventHandler"]);async function Ti(e,t){switch(e.type){case"literal":return function(e){return e.value}(e);case"identifier":return Mi(e,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,i=e.left;if("="===n){const n=await Ai(e.right,t);if("identifier"===i?.type&&"string"==typeof i.name){const e=i.name;return e.startsWith("$")?re(t,e.slice(1),n):"global"===i.scope?re(t,e,n):"element"===i.scope?me(t,e,n):(t.locals||(t.locals=new Map),t.locals.set(e,n)),n}throw Error(`Assignment target must be a variable identifier (got '${i?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await Ai(e.left,t);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===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 Ai(e.right,t);if(i&&"function"==typeof i.querySelectorAll){const e=Array.from(i.querySelectorAll(r.value));return 0===e.length?null:"first"===n?e[0]:e[e.length-1]}}}if("selector"===i?.type&&i.fromQuery&&"string"==typeof i.value){const n=await Ai(e.right,t),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 Ai(e.right,t);return xi(t,"styleRef").evaluate(t,i.value.slice(1),n)}if("of"===n){const n=Ii(e.left);if(n){const r=await Ai(e.right,t);let i=r;for(const e of n){if(null==i)return;i=Me(i)?Be(i,e):i[e]}return"function"==typeof i?i.bind(r):i}}const o=await Ai(e.left,t);if("and"===n){if(!o)return o;const n=await Ai(e.right,t);return xi(t,"and").evaluate(t,o,n)}if("or"===n){if(o)return o;const n=await Ai(e.right,t);return xi(t,"or").evaluate(t,o,n)}const s=await Ai(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(o):o,l=e.ignoringCase?a(s):s;switch(n){case"+":{let n=o,r=s;return e.coerceNumeric&&("string"==typeof n&&(n=we(n)),"string"==typeof r&&(r=we(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:ki(await xi(t,"addition").evaluate(t,{left:n,right:r}))}case"-":return ki(await xi(t,"subtraction").evaluate(t,{left:o,right:s}));case"*":return ki(await xi(t,"multiplication").evaluate(t,{left:o,right:s}));case"/":return ki(await xi(t,"division").evaluate(t,{left:o,right:s}));case"%":case"mod":return ki(await xi(t,"modulo").evaluate(t,{left:o,right:s}));case"^":case"**":return ki(await xi(t,"power").evaluate(t,{left:o,right:s}));case">":case"is greater than":return xi(t,"greaterThan").evaluate(t,o,s);case"<":case"is less than":return xi(t,"lessThan").evaluate(t,o,s);case">=":case"is greater than or equal to":return xi(t,"greaterThanOrEqual").evaluate(t,o,s);case"<=":case"is less than or equal to":return xi(t,"lessThanOrEqual").evaluate(t,o,s);case"==":return xi(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=Pi(e,o,s);return void 0!==n?n:xi(t,"equals").evaluate(t,c,l)}case"!=":return xi(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const n=Pi(e,o,s);return void 0!==n?!n:xi(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return xi(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return xi(t,"strictNotEquals").evaluate(t,c,l);case"as":return xi(t,"as").evaluate(t,o,Vi(s));case"contains":case"contain":case"includes":case"include":return xi(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return xi(t,"doesNotContain").evaluate(t,c,l);case"starts with":return xi(t,"startsWith").evaluate(t,c,l);case"ends with":return xi(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await xi(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await xi(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return xi(t,"matches").evaluate(t,c,Hi(e.right,l));case"does not match":case"do not match":return!await xi(t,"matches").evaluate(t,c,Hi(e.right,l));case"in":case"is in":case"am in":return qi(o,s);case"is not in":case"am not in":return!qi(o,s);case"of":return s&&"object"==typeof s?s[o]:void 0;case"precedes":return Bi(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!Bi(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return Bi(o,s,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!Bi(o,s,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(e,t);case"asExpression":return async function(e,t){const n=await Ai(e.expression,t),r=Vi(e.targetType);return xi(t,"as").evaluate(t,n,r)}(e,t);case"betweenExpression":return async function(e,t){const n=await Ai(e.value,t),r=await Ai(e.min,t),i=await Ai(e.max,t),o=e=>"string"==typeof e?e.toLowerCase():e,[s,a,c]=e.ignoringCase?[o(n),o(r),o(i)]:[n,r,i],l=await Sn.between.evaluate(t,s,a,c);return e.negated?!l:l}(e,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await Ai(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(e,t);case"collectionExpression":return async function(e,t){const n=await Ai(e.collection,t);if(null==n)return n;const r=async(e,n)=>Ai(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=jn(e),i=[];for(const e of r)await n(t,e)&&i.push(e);return i}(n,e.right,r);case"sorted by":return async function(e,t,n,r){const i=[...jn(e)],o=await Promise.all(i.map(e=>r(t,e))),s=i.map((e,t)=>t);s.sort((e,t)=>{const n=o[e],r=o[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=s.map(e=>i[e]);return"desc"===n?a.reverse():a}(n,e.right,e.order??"asc",r);case"mapped to":return async function(e,t,n){const r=jn(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return o=await Ai(e.right,t),null==(i=n)?[]:(i+"").split(null==o?"":o+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return jn(e).map(e=>null==e?"":e+"").join(n)}(n,await Ai(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var i,o}(e,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await Ai(n,t);switch(e.operator){case"not":case"!":return Sn.not.evaluate(t,r);case"no":return Sn.no.evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return Sn.exists.evaluate(t,r);case"does not exist":return Sn.doesNotExist.evaluate(t,r);case"is empty":return Sn.isEmpty.evaluate(t,r);case"is not empty":return Sn.isNotEmpty.evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(e,t);case"memberExpression":return async function(e,t){const n=await Ai(e.object,t);if(e.computed){const r=await Ai(e.property,t);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return _i(n,e.property.name,t)}(e,t);case"propertyAccess":return async function(e,t){let n=await Ai(e.object,t);for(const r of(e.property+"").split(".")){if(null==n)return;n=await _i(n,r,t)}return n}(e,t);case"callExpression":return async function(e,t){const n=await Ai(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>Ai(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,i=await async function(e,t,n){return zi.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:Ai(e,n))):Promise.all(e.map(e=>Ai(e,n)))}(e.arguments,r,t);switch(r){case"closest":return tt.closest.evaluate(t,...i);case"previous":case"next":{const n=e.relativePositional;if(n){const e=n.from?Wi(await Ai(n.from,t)):t.me,o=n.within?Wi(await Ai(n.within,t)):void 0,s=n.inElt?await Ai(n.inElt,t):void 0;return xi(t,r).evaluate(t,i[0],e,{within:o,inElt:s,inSearch:n.inSearch,wrapping:n.wrapping})}return xi(t,r).evaluate(t,...i)}case"first":return xi(t,"first").evaluate(t,...i);case"last":return xi(t,"last").evaluate(t,...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(e.arguments.map(e=>Ai(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const i=await Ai(e.callee.object,t);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(e,t);case"selector":return async function(e,t){let n=e.value;if("string"==typeof n&&!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return tt.styleRef.evaluate(t,n.slice(1));if("string"==typeof n&&e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=await async function(e,t){const n=Xi(e),r=await Promise.all(n.filter(e=>"expr"in e).map(e=>Ni(e.expr,t)));return Yi(n,r)}(n,t),o=Ki(e,r);i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await tt.elementWithSelector.evaluate(t,o)}finally{i.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!e.fromQuery&&n.includes("{")&&(n=await function(e,t){return Ui(e,/\{([^}]*)\}/g,async(e,n)=>(await Ni(n.trim(),t)??"")+"")}(n,t));const r="string"==typeof n?Ki(e,n):n;return Se(await tt.elementWithSelector.evaluate(t,r),n,e.fromQuery)}(e,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return xi(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return tt.me.evaluate(t);case"your":case"yourself":return tt.you.evaluate(t);case"its":return tt.it.evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??tt.me.evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return tt.document.evaluate(t);case"window":return tt.window.evaluate(t);default:return}}(e,t);case"possessiveExpression":return async function(e,t){const n=await Ai(e.object,t),r=e.property.name;return xi(t,"possessive").evaluate(t,n,r)}(e,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await Ai(t,r)}}}(e,t);case"conditionalExpression":return async function(e,t){return await Ai(e.test,t)?Ai(e.consequent,t):e.alternate?Ai(e.alternate,t):void 0}(e,t);case"string":return e.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await Ai(r,t));return n}(e,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let i;i="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await Ai(e,t)+"",n[i]=await Ai(r.value,t)}return n}(e,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(e,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await Ai(e.target,t);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return xi(t,"possessive").evaluate(t,i,r)}(e,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await Ui(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const e=n.split(".");let r=Di(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(Di(n,t)??"")+""}catch{return""}}),n=await Ui(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const i=n||r;try{return await Ni(i,t)+""}catch{return"undefined"}}),n}(e,t);case"stringPostfix":return async function(e,t){return`${await Ai(e.expression,t)}${e.unit}`}(e,t);case"blockLiteral":return Fi(e,t);default:throw Error("Unhandled evaluable AST node type: "+e.type)}}async function Ai(e,t){if(!e)throw Error("Cannot evaluate null or undefined AST node");if("literal"===e.type)return e.value;if("identifier"===e.type)return Mi(e,t);if(Si.has(e.type))return Ti(e,t);const n=oe.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}class Ci extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}const $i=new Set(["literal","string","selector","identifier","contextReference","arrayLiteral","objectLiteral","asExpression","stringPostfix","blockLiteral","memberExpression"]);function ji(e,t){const n=e?.type;if("string"==typeof n&&$i.has(n))return function(e,t){switch(e.type){case"literal":case"string":return e.value;case"selector":return function(e,t){const n=e.value;if("string"!=typeof n)throw new Ci("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new Ci("selector");if(e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(e,t){const n=Xi(e),r=n.filter(e=>"expr"in e).map(e=>Oi(e.expr,t));return Yi(n,r)}(n,t),o=Ki(e,r),s=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new Ci("selector");i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(s.querySelectorAll(o))}finally{i.forEach(e=>e.removeAttribute("data-hs-query-id"))}}const r=!e.fromQuery&&n.includes("{")?function(e,t){return e.replace(/\{([^}]*)\}/g,(e,n)=>(Oi(n.trim(),t)??"")+"")}(n,t):n,i=Ki(e,r),o=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new Ci("selector");return Se(Array.from(o.querySelectorAll(i)),r,e.fromQuery)}(e,t);case"identifier":return function(e,t,n){return"me"===e||"my"===e||"I"===e?t.me:"you"===e||"your"===e||"yourself"===e?t.you:"it"===e||"its"===e?t.it??t.result:"result"===e?t.result??t.it:"window"===e?"undefined"!=typeof window?window:globalThis:"document"===e?"undefined"!=typeof document?document:void 0:"element"===n?he(t,e):t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):e.startsWith("$")&&t.globals?.has(e.slice(1))?t.globals.get(e.slice(1)):"body"===e&&"undefined"!=typeof document?document.body:"detail"===e?t.event?.detail??null:"sender"===e?t.event?.detail?.sender??null:void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(e.name,t,e.scope);case"contextReference":return function(e,t){switch(e){case"me":return t.me;case"you":return t.you;case"it":return t.it??t.result;case"event":return t.event;case"target":return t.target??t.event?.target??t.me;default:throw new Ci("contextReference")}}(e.contextType,t);case"arrayLiteral":return e.elements.map(e=>ji(e,t));case"objectLiteral":return function(e,t){const n={};for(const r of e.properties){const e=r.key;let i;i="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value+"":ji(e,t)+"",n[i]=ji(r.value,t)}return n}(e,t);case"asExpression":return Ye(ji(e.expression,t),Vi(e.targetType),t);case"stringPostfix":return`${ji(e.expression,t)}${e.unit}`;case"blockLiteral":return Fi(e,t);case"memberExpression":{const n=ji(e.object,t);if(null==n)return;if(n instanceof Element||Array.isArray(n)||"undefined"!=typeof Node&&n instanceof Node)throw new Ci("memberExpression");const r=n[e.computed?ji(e.property,t)+"":e.property.name];return"function"==typeof r?r.bind(n):r}default:throw new Ci((e.type??"unknown")+"")}}(e,t);throw new Ci("string"==typeof n?n:"unknown")}function Oi(e,t){const n=Ei(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return ji(n.node,t)}async function Ni(e,t){const n=Ei(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const r=t.registry?t:{...t,registry:await Li()};return Ai(n.node,r)}let Ri=null;async function Li(){if(!Ri){const e=await Promise.resolve().then(function(){return Ro});Ri=e.createFullExpressionRegistry()}return Ri}async function Mi(e,t){const n=e.name;return n.startsWith("$")?ee(n.slice(1),t):"global"===e.scope&&ee(n,t),"me"===n||"my"===n||"I"===n?tt.me.evaluate(t):"you"===n||"your"===n||"yourself"===n?tt.you.evaluate(t):"it"===n||"its"===n?tt.it.evaluate(t):"result"===n?tt.result.evaluate(t):"window"===n?tt.window.evaluate(t):"document"===n?tt.document.evaluate(t):"global"===e.scope&&t.globals?.has(n)?t.globals.get(n):"element"===e.scope?he(t,n):t.locals&&t.locals.has(n)?(ne(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?t.globals.get(n):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?t.globals.get(n.slice(1)):"body"===n&&"undefined"!=typeof document?document.body:"detail"===n?t.event?.detail??null:"sender"===n?t.event?.detail?.sender??null:void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function Ii(e){const t=e;if(!t)return null;if("identifier"===t.type&&"string"==typeof t.name)return[t.name];if("memberExpression"===t.type&&!t.computed){const e=Ii(t.object);if(!e)return null;const n=t.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...e,r]}return null}function qi(e,t){return Array.isArray(t)?t.includes(e):"string"==typeof t?t.includes(e+""):e instanceof Node&&t instanceof Node?e===t||t.contains(e):null!=t&&"object"==typeof t&&e in t}function Hi(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function Pi(e,t,n){if(void 0!==n)return;const r=e.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==t||"object"!=typeof t)return;const i=t[r.name];return"boolean"==typeof i?!0===i:void 0}function Bi(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function Vi(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e+""}function Fi(e,t){const n=e.parameters??[];return(...r)=>{const i=new Map(t.locals??new Map);n.forEach((e,t)=>i.set(e,r[t]));const o={...t,locals:i};try{return ji(e.body,o)}catch(t){if(t instanceof Ci)return Ai(e.body,o);throw t}}}function Di(e,t){if(t.locals?.has(e))return ne(e,t),t.locals.get(e);if("me"===e&&t.me)return t.me;if("you"===e&&t.you)return t.you;if("it"===e){const e=t.it??t.result;if(e)return e}if("result"===e){const e=t.result??t.it;if(e)return e}return"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function Ui(e,t,n){const r=[];let i;for(;null!==(i=t.exec(e));)r.push({index:i.index,length:i[0].length,replacement:await n(i[0],...i.slice(1))});let o=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:i}=r[e];o=o.substring(0,t)+i+o.substring(t+n)}return o}function _i(e,t,n){if("string"==typeof t&&t.startsWith("@")){const n=t.substring(1);return e&&"function"==typeof e.getAttribute?e.getAttribute(n):void 0}return e instanceof Element&&"string"==typeof t?Be(e,t):Cn(e)&&!(t in e)?xi(n,"possessive").evaluate(n,e,t):e?.[t]}const zi=new Set(["closest","previous","next"]);function Wi(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const Zi=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"),Ji=/[:&()[\]/]/g;function Ki(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace(Zi,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(Ji,"\\$&")}(t)}const Gi=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Xi(e){const t=[];let n,r=0;for(Gi.lastIndex=0;null!==(n=Gi.exec(e));)n.index>r&&t.push({lit:e.slice(r,n.index)}),t.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return e.length>r&&t.push({lit:e.slice(r)}),t}function Yi(e,t){let n="";const r=[];let i=0;for(const o of e){if("lit"in o){n+=o.lit;continue}const e=t[i++];Me(e)?(n+=`[data-hs-query-id='${r.length}']`,r.push(e)):n+=(e??"")+""}return{selector:n,elements:r}}class Qi{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,n,r,i){this.addCleanup(e,{type:"listener",target:t,eventName:n,cleanup:()=>{t.removeEventListener(n,r,i),this.debugMode&&Pn(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&Pn("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&Pn("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&Pn("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,n){this.addCleanup(e,{type:"custom",cleanup:t,description:n||"Custom cleanup"})}registerGlobal(e,t="custom",n){this.globalCleanups.push({type:t,cleanup:e,description:n||"Global cleanup"}),this.debugMode&&Pn("CleanupRegistry: Registered global cleanup: "+(n||t))}addCleanup(e,t){const n=this.elementCleanups.get(e);n?n.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&Pn(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let n=0;for(const e of t){try{e.cleanup(),n++}catch(e){this.debugMode&&Pn("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&Pn(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(e){let t=this.cleanupElement(e);const n=e.querySelectorAll("*");for(const e of n)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&Pn("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&Pn(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,n=0,r=0,i=0;for(const o of this.globalCleanups)switch(o.type){case"listener":e++;break;case"observer":t++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}class eo{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&Pn("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(n,t)}unregister(e){const t=e.toLowerCase(),n=this.sources.get(t);if(n){for(const[e,n]of this.subscriptions.entries())n.source===t&&(n.unsubscribe(),this.subscriptions.delete(e));return n.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,n){const r=this.get(e);if(!r)return void Pn("[EventSourceRegistry] Unknown event source: "+e);r.initialize?.();const i=r.subscribe(t,n);return this.subscriptions.set(i.id,i),i}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,n]of this.sources.entries())if(n.supports?.(e)??n.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}const to={evaluate:(e,t)=>Ai(e,t)};class no{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:"string"==typeof e?e:e?e.join(" | "):""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(In(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void In(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.variables||(e.variables=new Map);const i=e;let o,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(In(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!this.impl.ownsConditionalModifier&&!await Ai(r,e))return void In(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);o=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName,bodies:n.bodies},to,e)}else o=t;else In(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),o=t;if(In("CommandAdapterV2: Calling execute with parsed input:",o),2===this.impl.execute.length)s=await this.impl.execute(o,i);else{const e=Array.isArray(o)?o:[o];s=await this.impl.execute(i,...e)}return In("CommandAdapterV2: Command result:",s),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,s),s}catch(e){if(In(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return{isValid:!this.impl.validate||this.impl.validate(e),errors:[],suggestions:[]}}}class ro{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);Pn(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=t.toLowerCase();Pn(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new no(e,void 0,this.hookRegistry);this.adapters.set(n,r),$.add(n);const i=e.metadata?.aliases;if(i&&Array.isArray(i))for(const t of i){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r),$.add(n)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const n=this.getAdapter(e);return n?n.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let io=null;function oo(){return io||(io=function(e){const t=e?.commands??new ro,n=e?.eventSources??new eo,r=new Set,i={commands:t,eventSources:n,use(e){if(r.has(e.name))Pn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);e.setup?.(i),r.add(e.name)}},reset(){r.clear()}};return i}()),io}class so{constructor(e={}){const t=oo();this.options={enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,Pn(`[RegistryIntegration] Initialized (events=${this.options.enableEventSources})`)}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return Pn(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return Pn(`[RegistryIntegration] Found event source '${n}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(e,t,n);if(!r)throw Error(`Failed to subscribe to event source '${e}'`);return Pn(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}destroy(){this.eventSourceRegistry.destroy(),Pn("[RegistryIntegration] Destroyed")}}class ao extends Error{constructor(e){super(`'${e.type}' used outside of a loop`),this.signal=e,this.name="StrayControlFlowError"}}function co(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const lo=new WeakMap;function uo(e,t=new Set){if(null===e||"object"!=typeof e)return t;if(Array.isArray(e)){for(const n of e)uo(n,t);return t}const n=e;"identifier"===n.type&&"string"==typeof n.name&&t.add(n.name);for(const e of Object.keys(n))"start"!==e&&"end"!==e&&"line"!==e&&"column"!==e&&uo(n[e],t);return t}class fo{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.ops=new WeakMap,this.options={commandTimeout:1e4,enableErrorReporting:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=le,this.hookRegistry=new r,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Qi,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new so("object"==typeof e.registryIntegration?e.registryIntegration:{}),Pn("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,n)=>await this.installBehaviorOnElement(e,t,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const n of e)for(const e of n.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&Pn(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}trackListener(e,t,n,r,i){this.cleanupRegistry.registerListener(e,t,n,r,i)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),Pn("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){const n=await this.executeNode(e,t);if(s(n))return n.value;const r=n.error;if("return"===r.type){const e=r.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}if("halt"!==r.type&&"exit"!==r.type)throw new ao(r)}async executeNode(e,t){return this.prepareContext(t),this.compile(e)(t)}prepareContext(e){e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI)}compile(e){const t=this.ops.get(e);if(t)return t;const n=this.compileNode(e);return this.ops.set(e,n),n}compileSequence(e){const t=e.map(e=>this.compile(e));return async e=>{let n;for(const r of t){const t=await r(e);if(!s(t))return t;n=t.value}return i(n)}}compileNode(e){if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0],n=t?.message||"Skipped error node";return async()=>(Pn("\u26a0\ufe0f RUNTIME: Skipping error node: "+n),this.runtimeWarnings.push(n),i(void 0))}switch(e.type){case"command":{const t=e,n=(t.args??[]).map(e=>function(e){const t=e?.type;return"block"===t||"command"===t}(e)?this.compile(e):void 0),r=n.some(Boolean);return e=>this.processCommandWithResult(t,e,r?n:void 0)}case"initBlock":case"block":{const t=e,n=(Array.isArray(t.commands)?t.commands:[]).map(e=>this.compile(e)),r="initBlock"===e.type;return async e=>{for(const t of n){const n=await t(e);if(!s(n)){if(r&&"halt"===n.error.type)break;return n}}return i(void 0)}}case"sequence":case"CommandSequence":{const t=e;return e=>this.executeCommandSequenceWithResult(t.commands||[],e)}case"Program":return t=>this.executeProgram(e,t);default:return t=>this.dispatch(e,t)}}async dispatch(e,t){switch(Pn(`RUNTIME BASE: dispatch node type: '${e.type}'`),e.type){case"eventHandler":return i(await this.executeEventHandler(e,t));case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return i(await this.executeEventHandler(n,t))}case"behavior":return i(await this.executeBehaviorDefinition(e,t));case"def":return i(this.installFunction(e,t));case"objectLiteral":return i(await this.executeObjectLiteral(e,t));default:return await this.evaluateExpressionWithResult(e,t)}}async processCommandWithResult(e,t,n){const{name:r,args:s,modifiers:a}=e,c=r.toLowerCase();if(In(`RUNTIME BASE (Result): Processing command '${c}'`),!this.registry.has(c)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const l=await this.registry.getAdapter(c);if(!l)throw Error(`Command '${c}' is registered but failed to load adapter.`);try{const e=await l.execute(t,{args:s||[],modifiers:a||{},bodies:n,commandName:c,runtime:this});return"object"==typeof(u=e)&&null!==u&&"type"in u&&"string"==typeof u.type&&["halt","exit","break","continue","return"].includes(u.type)?o(e):i(e)}catch(e){throw this.logError(`Error executing command '${c}':`,e),e}var u}async executeCommandSequenceWithResult(e,t){let n;for(const r of e){if(this.hasErrorDiagnostics(r)){const e=r.diagnostics?.[0];Pn("\u26a0\ufe0f RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===r.type){const e=await this.compile(r)(t);if(!s(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),i(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(r,t);if(!s(e))return e;n=e.value}}return i(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await Ai(e,n);if(co(r)){const e={type:"command",name:r.command,args:[{type:"literal",value:r.selector}],isBlocking:!1},n=await this.processCommandWithResult(e,t);if(!s(n))throw new ao(n.error);return n.value}return r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await async function(e,t){try{return i(await Ai(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt)return o({type:"halt"});if(t.isExit)return o({type:"exit",returnValue:t.returnValue});if(t.isBreak)return o({type:"break"});if(t.isContinue)return o({type:"continue"});if(t.isReturn)return o({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!s(r))return r;const a=r.value;return co(a)?this.processCommandWithResult({type:"command",name:a.command,args:[{type:"literal",value:a.selector}],isBlocking:!1},t):i(a)}installFunction(e,t){const n=e.params??[],r=e.errorHandler,i=e.finallyHandler,o=e.errorSymbol,a=this.compileSequence(e.body??[]),c=r?this.compileSequence(r):void 0,l=i?this.compileSequence(i):void 0;t.globals.set(e.name,async(...e)=>{const r={...t,locals:new Map(t.locals)};n.forEach((t,n)=>{t&&r.locals.set(t,e[n])});const i=async e=>{const t=await e(r);if(!s(t)){const e=t.error;if("break"===e.type||"continue"===e.type)throw new ao(e);return"return"===e.type?e.returnValue:void 0}return t.value};if(!c&&!l)return await i(a);try{return await i(a)}catch(e){if(!c||e instanceof ao)throw e;return o&&r.locals.set(o,e),await i(c)}finally{l&&await i(l)}})}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return i(void 0);let n;const r=[],o=[],a=[],c=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"def"===t.type?o.push(t):"initBlock"===t.type?a.push(t):c.push(t);for(const e of o)this.executeNode(e,t);for(const e of r){const n=await this.executeNode(e,t);if(!s(n)){if("halt"===n.error.type||"exit"===n.error.type)break;return n}}for(const e of a){const r=await this.executeNode(e,t);if(!s(r)){if("halt"===r.error.type||"exit"===r.error.type)break;if("return"===r.error.type){n=r.error.returnValue;break}return r}n=r.value}for(const e of c){const r=await this.executeNode(e,t);if(!s(r)){if("halt"===r.error.type||"exit"===r.error.type)break;if("return"===r.error.type){n=r.error.returnValue;break}return r}n=r.value}return i(n)}async executeBlock(e,t){return this.compile(e)(t)}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const i=await this.execute(r.value,t);n[e]=i}return n}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:o}=e,s=e.imperativeInstaller;"function"==typeof s?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:s}),Pn(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:o&&o}),Pn(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){Pn("BEHAVIOR: installBehaviorOnElement called: "+e);let r=this.behaviorRegistry.get(e);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(r=this.behaviorRegistry.get(e)),!r))throw Error(`Behavior "${e}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(Pn(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),Pn(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));Pn("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const i={me:t,owner:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry};if(r.parameters)for(const e of r.parameters)i.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||i.locals.set(e,t);if(r.initBlock){Pn("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),Pn("BEHAVIOR: Init block completed for "+e)}catch(t){throw Pn(`BEHAVIOR: Init block error for ${e}:`,t),t}}if(Pn(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${e}`),r.eventHandlers){const t=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}Pn("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){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}=e,p=r&&r.length>0?r:[n];Pn(`BEHAVIOR: executeEventHandler: event='${n}', target='${o}'`);let y=[],b=null;if(o){const e="string"==typeof o?o.toLowerCase():"";if("window"===e||"the window"===e)b=window;else if("document"===e||"the document"===e||"body"===e)b=document;else if("me"===e||"myself"===e)y=t.me?[t.me]:[];else if("string"==typeof o&&t.locals.has(o)){const e=t.locals.get(o);Pn(`BEHAVIOR: Target resolution: found local '${o}', isElement: ${this.isElement(e)}`),this.isElement(e)?y=[e]:Array.isArray(e)?y=e.filter(e=>this.isElement(e)):"string"==typeof e&&(y=this.queryElements(e,t))}else Pn(`BEHAVIOR: Target resolution: querying for '${o}'`),y=this.queryElements(o,t)}else y=t.me?[t.me]:[];if(0===y.length&&!b)return void Pn(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(y,l,i,t);if("change"===n&&u)return void this.setupChangeObserver(u,i,t);const g=e.customEventSource;if(g&&this.registryIntegration){Pn(`BEHAVIOR: executeEventHandler - Using custom event source '${g}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),o={...t,locals:r,it:e,event:e};Pn(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},o)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,e)}};try{const r=this.registryIntegration.subscribeToEventSource(g,{event:n,handler:e,target:o,selector:a},t);Pn(`BEHAVIOR: Subscribed to custom event source '${g}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${g}' subscription ${r.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${g}':`,e)}return}const v=fo.createEventHandler(this,i,t,a,s,{errorSymbol:d,errorHandler:h,finallyHandler:m},1===p.length?c:void 0);let w,E=null;if(f){let e=v;if(f.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(f.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(f.debounce){const t=f.debounce;let n;w=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},E=()=>{n&&(clearTimeout(n),n=void 0)}}else if(f.throttle){const t=f.throttle;let n=0;w=r=>{const i=Date.now();t>i-n||(n=i,e(r))}}else w=e}else w=v;const x=f?.once?{once:!0}:void 0;if(b){for(const e of p)b.addEventListener(e,w,x),y.length>0?this.cleanupRegistry.registerListener(y[0],b,e,w):this.cleanupRegistry.registerGlobal(()=>b.removeEventListener(e,w),"listener",`Global ${e} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const e of y){for(const t of p){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const n of e){const e=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(e.synthetic=!0,w(e),x?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,w,x),this.cleanupRegistry.registerListener(e,e,t,w)}E&&this.cleanupRegistry.registerCustom(e,E,"debounce-timeout")}}static createEventHandler(e,t,n,r,i,o,a){const c=e.compileSequence(t),l=o?.errorHandler?e.compileSequence(o.errorHandler):void 0,u=o?.finallyHandler?e.compileSequence(o.finallyHandler):void 0;return async t=>{const f=lo.get(t)??0;if(f>=100)return;if(lo.set(t,f+1),r&&t.target instanceof Element)try{if(!t.target.matches(r)&&!t.target.closest(r))return}catch{Pn(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const d=new Map(n.locals),h={...n,locals:d,it:t,event:t};if(d.has("target")||h.locals.set("target",t.target),i&&i.length>0){const e=t,n=e.detail;for(const t of i)h.locals.set(t,e[t]??n?.[t]??null)}if(a){const n=t;for(const e of uo(a))!h.locals.has(e)&&e in n&&h.locals.set(e,n[e]);let r;try{r=await e.evaluateExpression(a,h)}catch(e){return void Pn("Event filter threw; skipping handler body:",e)}if(!r)return}e.prepareContext(h);const m=async t=>{let n;try{n=await t(h)}catch(t){throw e.logError("COMMAND FAILED:",t),t}if(s(n))return;const r=n.error;if("return"===r.type&&void 0!==r.returnValue&&Object.assign(h,{it:r.returnValue,result:r.returnValue}),"break"===r.type||"continue"===r.type)throw new ao(r)};if(l||u)try{await m(c)}catch(e){if(!l||e instanceof ao)throw e;o?.errorSymbol&&h.locals.set(o.errorSymbol,e),await m(l)}finally{u&&await m(u)}else await m(c)}}setupMutationObserver(e,t,n,r){Pn(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const i of e){const e=new MutationObserver(async e=>{for(const o of e)if("attributes"===o.type&&o.attributeName===t){qn(`MUTATION DETECTED: attribute '${t}' changed on`,i);const e={...r,me:i,it:o,locals:new Map(r.locals)},a=o.oldValue,c=i.getAttribute(t);e.locals.set("oldValue",a),e.locals.set("newValue",c);for(const t of n){let n;try{n=await this.executeNode(t,e)}catch(e){this.logError("Error executing mutation handler command:",e)}if(n&&!s(n)){const e=n.error.type;if("halt"===e||"exit"===e||"return"===e)break}}}});e.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(i,e),Pn("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){Pn("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(e,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(e=>this.isElement(e))),Pn(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const e of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){qn("CONTENT CHANGE DETECTED on",e,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",e);const o=i.oldValue,a=e.textContent;null!==o&&r.locals.set("oldValue",o),r.locals.set("newValue",a);for(const e of t){let t;try{t=await this.executeNode(e,r)}catch(e){this.logError("Error executing change handler command:",e)}if(t&&!s(t)){const e=t.error.type;if("halt"===e||"exit"===e||"return"===e)break}}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),Pn("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const n=t.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=e;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return Pn(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function ho(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}class mo{trackPerformance(e,t,n,r){}trackSimple(e,t,n,r=(n?"success":"error")){}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||je(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,n,r,i=[]){return{success:!1,error:{name:e,type:t,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,n=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:n}],suggestions:n}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":Ne(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":$e(e)?"String":je(e)?"Number":Oe(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):$e(e)?e.split(""):null==e?[]:Ne(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(je(e)&&Number.isFinite(e))return e;if($e(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Oe(e)?e?1:0:null}}const po=ct({value:at().describe("String literal value")}).strict(),yo=ct({value:function(e={}){return rt?ot():it({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:nt("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:nt("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:nt("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(vo||{}).describe("Number literal value")}).strict(),bo=ct({value:(rt?ot():it({validate:e=>"boolean"!=typeof e?{success:!1,error:nt("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}})).describe("Boolean literal value")}).strict(),go=ct({left:ut().describe("Left operand"),right:ut().describe("Right operand")}).strict();var vo;const wo={stringLiteral:new class extends mo{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=po,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid){const t=this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(e,n,!1),t}let i=t.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,e));const o=this.success(i,"string");return this.trackSimple(e,n,!0,i),o}catch(t){return this.trackSimple(e,n,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let n=e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=this.resolveExpression(n.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,n)=>{try{const e=this.resolveVariable(n,t);return void 0!==e?e+"":""}catch(e){return""}}),n}resolveExpression(e,t){if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++)r=r[n[e]];return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?(ne(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends mo{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=yo,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?Number.isFinite(t.value)?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends mo{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=bo,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends mo{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=go,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,n,!0,i),this.success(i,"string")}catch(t){return this.trackSimple(e,n,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=go.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if($e(e))return e;if(je(e))return""+e;if(Oe(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}};class Eo{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand");return{success:!0,value:Dt(r+Vt(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){const t=function(e){if(null==e)return Wt([Zt("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return Wt([Zt("type-mismatch","Expected object, got "+typeof e)],["Provide an object with left and right operands"]);const t=e;if(!("left"in t)||!("right"in t)){const e=[];return"left"in t||e.push("left"),"right"in t||e.push("right"),Wt([Zt("missing-argument",`Missing ${e.join(" and ")} operand${e.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(e);if(!t.isValid)return t;const{left:n,right:r}=e;return Ut(n)?Ut(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[Zt("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[Zt("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const xo={addition:new Eo,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand");return{success:!0,value:Dt(r-Vt(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand");return{success:!0,value:Dt(r*Vt(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t,n=!0){if(0===t){if(n)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(Vt(e,"left operand"),Vt(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(Vt(e,"left operand"),Vt(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Modulo failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(e){return(new Eo).validate(e)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand"),i=Vt(n,"right operand");return{success:!0,value:Dt(Math.pow(r,i),"power"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}}},ko={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const n=void 0!==t?t:e.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:$e(n)?n.length>0?n[0]:null:Ne(n)&&"length"in n&&je(n.length)&&n.length>0?n[0]:null},validate:e=>We(e,1,"first","collection")},So={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const e=n.children;return e.length>0?e[e.length-1]:null}return $e(n)?n.length>0?n[n.length-1]:null:Ne(n)&&"length"in n&&je(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>We(e,1,"last","collection")},To={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!je(n))throw Error("Index must be a number");const i=n,o=void 0!==r?r:e.it;if(null==o)return null;if(Array.isArray(o)){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}if(o instanceof NodeList||o instanceof HTMLCollection){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}if(o instanceof Element){const e=o.children,t=0>i?e.length+i:i;return t>=0&&e.length>t?e[t]:null}if($e(o)){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}if(Ne(o)&&"length"in o&&je(o.length)){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}return null},validate:e=>Ze(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function Ao(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;const e=n.querySelector(t);if(e)return e;n=n.nextElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Ao(r,t):null}function Co(e,t){let n=e.previousElementSibling;for(;n;){const e=Array.from(n.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(n.matches(t))return n;n=n.previousElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Co(r,t):null}function $o(e,t,n,r){if(n.inSearch){if(null==n.inElt)return;return function(e,t,n,r){const i=Array.from(t??[]),o=[];for(const t of i)(t.matches&&t.matches(n)||t===e)&&o.push(t);for(let t=0;o.length-1>t;t++)if(o[t]===e)return o[t+1];if(r){const e=o[0];if(e&&e.matches&&e.matches(n))return e}}(e,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),t,!!n.wrapping)}const i=n.within??("undefined"!=typeof document?document.body:null);if(i)return r?function(e,t,n,r){const i=t.querySelectorAll(n);for(let t=0;i.length>t;t++){const n=i[t];if(2===n.compareDocumentPosition(e))return n}return r?i[0]:void 0}(e,i,t,!!n.wrapping):function(e,t,n,r){const i=t.querySelectorAll(n);for(let t=i.length-1;t>=0;t--){const n=i[t];if(4===n.compareDocumentPosition(e))return n}return r?i[i.length-1]:void 0}(e,i,t,!!n.wrapping)}function jo(e){let t=0,n=e;for(;n&&n.parentElement;)t+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,t+=1e3;return t}const Oo={first:ko,last:So,at:To,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r,i]=t,o=r||e.me;return o&&o instanceof Element?n?i?$o(o,n,i,!0):Ao(o,n):o.nextElementSibling:null},validate:e=>We(e,3,"next","optional selector, optional fromElement, optional modifiers")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[n,r,i]=t,o=r||e.me;return o&&o instanceof Element?n?i?$o(o,n,i,!1):Co(o,n):o.previousElementSibling:null},validate:e=>We(e,3,"previous","optional selector, optional fromElement, optional modifiers")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[n,r,i]=t,o=i||e.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=jo(e);for(const e of r)if(jo(e)>i)return e;return null}(o,n,s):null},validate:e=>Ze(e,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[n,r,i]=t,o=i||e.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=jo(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(i>jo(t))return t}return null}(o,n,s):null},validate:e=>Ze(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}};function No(){return ho(tt,Sn,Qe,Oo,$n,wo,xo)}var Ro=Object.freeze({__proto__:null,conversion:Qe,conversionExpressions:Qe,createCommonRegistry:function(){return ho(tt,Sn,wo,xo,Qe,Oo)},createCoreRegistry:function(){return ho(tt,Sn,wo,xo)},createExpressionRegistry:ho,createFullExpressionRegistry:No,createFullRegistry:function(){return ho(tt,Sn,wo,xo,Qe,Oo,$n)},logical:Sn,logicalExpressions:Sn,mathematical:xo,positional:Oo,positionalExpressions:Oo,properties:$n,propertiesExpressions:$n,references:tt,referencesExpressions:tt,special:wo,specialExpressions:wo});function Lo(e,t,n,r,i,o){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),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(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(e||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(e,t,n){for(var r=arguments.length>2,i=0;t.length>i;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function Io(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function qo(e){return function(t,n){Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Ho(e){return{...e}}function Po(e){return()=>new e}function Bo(e,t){return e?`[${e}] ${t}`:t}function Vo(e,t,n){if(be(e))return e;if(!e){const e=t.me;if(!e)throw Error(Bo(n,"No target element \u2014 provide explicit target or ensure context.me is set"));return Do(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error(Bo(n,'Context reference "me" is not available'));return Do(t.me)}if("it"===r){if(!be(t.it))throw Error(Bo(n,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===r){if(!t.you)throw Error(Bo(n,'Context reference "you" is not available'));return Do(t.you)}const i=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw Error(Bo(n,"DOM not available \u2014 cannot resolve element selector"));const o=i.querySelector(r);if(!o)throw Error(Bo(n,"Element not found with selector: "+r));if(!be(o))throw Error(Bo(n,"Element found but is not an HTMLElement: "+r));return o}throw Error(Bo(n,"Invalid target type: "+typeof e))}function Fo(e,t){if(Array.isArray(e))return e.filter(be);if(ve(e))return Array.from(e).filter(be);if(be(e))return[e];if(!e){const e=t.me;return e&&be(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&be(t.me)?[t.me]:[];if("it"===n)return be(t.it)?[t.it]:[];if("you"===n)return t.you&&be(t.you)?[t.you]:[];const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let e=n;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.querySelectorAll(e);return Array.from(t).filter(be)}}return[]}function Do(e){if(be(e))return e;throw Error("Value is not an HTMLElement")}function Uo(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(Bo(n,'No "me" element in context'));if(!be(t.me))throw Error(Bo(n,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(Bo(n,'No "it" value in context'));if(!be(t.it))throw Error(Bo(n,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(Bo(n,'No "you" element in context'));if(!be(t.you))throw Error(Bo(n,"context.you is not an HTMLElement"));return t.you;default:throw Error(Bo(n,"Unknown possessive: "+e))}}async function _o(e,t,n,r,i={},o){let s=e;if((!s||0===s.length)&&i.fallbackModifierKey&&o){const e=o[i.fallbackModifierKey];e&&(s=[e])}if(!s||0===s.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!be(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of s){const i=await t.evaluate(e,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(be(i))a.push(i);else if(ve(i)){const e=Array.from(i).filter(be);a.push(...e)}else if(Array.isArray(i)){const e=i.filter(be);a.push(...e)}else{if("string"!=typeof i){if(null==i)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`)}try{let e=i;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const r=t.querySelectorAll(e),o=Array.from(r).filter(be);a.push(...o)}catch(e){throw Error(`Invalid CSS selector: "${i}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!be(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}"function"==typeof SuppressedError&&SuppressedError;class zo{constructor(){this.ownsConditionalModifier=!0}async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await _o(e.args,t,n,r)}}(e,t,n,this.mode),i=e.modifiers?.when??e.modifiers?.where,{matched:o,unmatched:s}=i?await async function(e,t,n,r){const i=[],o=[],s=r.it;try{for(const s of e)r.it=s,(await n.evaluate(t,r)?i:o).push(s)}finally{r.it=s}return{matched:i,unmatched:o}}(r,i,t,n):{matched:r,unmatched:void 0};return{targets:o,...void 0!==s&&{inverse:s},mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>be(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const n=e.dataset.originalDisplay;void 0!==n?(e.style.display=n||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let Wo=(()=>{let e,t,n=[qo({name:"hide"})],r=[],i=zo;var o=t=class extends i{constructor(){super(...arguments),this.mode="hide"}get metadata(){return o.metadata}async execute(e,t){for(const t of e.targets)this.hideElement(t);for(const t of e.inverse??[])this.showElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>be(e))}};return Io(t,"HideCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({description:"Hide elements by setting display to none",syntax:"hide [<target>] [when <condition>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>","hide <li/> when its textContent is empty"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Mo(t,r),o=t})();const Zo=Po(Wo);let Jo=(()=>{let e,t,n=[qo({name:"show"})],r=[],i=zo;var o=t=class extends i{constructor(){super(...arguments),this.mode="show"}get metadata(){return o.metadata}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n);for(const t of e.inverse??[])this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>be(e))&&"string"==typeof t.defaultDisplay}};return Io(t,"ShowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({description:"Show elements by restoring display property",syntax:"show [<target>] [when <condition>]",examples:["show me","show #modal","show .hidden","show <button/>","show <li/> when its textContent contains my value"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Mo(t,r),o=t})();const Ko=Po(Jo);function Go(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function Xo(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),n=e.indexOf("=");if(-1===n)return{name:e.trim()};const r=e.slice(0,n).trim();let i=e.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function Yo(e,t){for(const n of e)t(n);return e}function Qo(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function es(e,t,n){const r=e.hasAttribute(t);void 0!==n?r&&e.getAttribute(t)===n?e.removeAttribute(t):e.setAttribute(t,n):r?e.removeAttribute(t):e.setAttribute(t,"")}function ts(e){if(!e)return[];if("string"==typeof e)return e.trim().split(/[\s,]+/).map(e=>{const t=e.trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&rs(e));if(Array.isArray(e))return e.map(e=>{const t=(e+"").trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&rs(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&rs(n)?[n]:[]}function ns(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function rs(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!ns(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function is(e,t){return e.map(e=>{if(ns(e)){const n=function(e){const t=e.trim(),n=t.match(/^\{(.+)\}$/);return n?n[1].trim():t}(e),r=t.locals.get(n)??t.globals.get(n);return null!=r?r+"":(In(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}function os(e){return"string"==typeof e&&e.trim().startsWith("*")}function ss(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const n=t.substring(1).trim();return n?{property:n}:null}(e);if(!t)return null;const n=t.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function as(e,t,n){e.style.setProperty(t,n)}const cs=["dialog","details","summary","select"];function ls(e){return e&&"object"==typeof e?"string"==typeof e.selector?e.selector:"string"==typeof e.value?e.value:"string"==typeof e.name?e.name:null:null}async function us(e,t,n){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const n=ls(e);return"string"==typeof n&&n.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const n=ls(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:ls(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;if("attributeAccess"===e.type)return!0;if("selector"===e.type||"cssSelector"===e.type){const t=ls(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:ls(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class fs{async resolveTargets(e,t,n){const r=n?.[this.preposition];return _o(r?[r]:[],e,t,this.mode)}async evaluateFirst(e,t,n){return us(e,t,n)}parseClassNames(e){return ts(e)}isAttribute(e){return Go(e.trim())}isCSSProperty(e){return os(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>be(e))}(e)}validateType(e,t){return function(e,t){return"string"==typeof e&&t.includes(e)}(e,t)}validateStringArray(e,t=1){return Array.isArray(e)&&function(e,t=1){return Array.isArray(e)&&e.length>=t&&e.every(e=>"string"==typeof e&&e.length>0)}(e,t)}}let ds=(()=>{let e,t,n=[qo({name:"add"})],r=[],i=fs;var o=t=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return o.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t,n,e.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:o}=function(e){const t=Xo(e);return{name:t.name,value:t.value??""}}(i);return{type:"attribute",name:r,value:o,targets:await this.resolveTargets(t,n,e.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim(),o=e.args[1];if(!o)throw Error("add *property requires a value argument");const s=await t.evaluate(o,n);return{type:"styles",styles:{[r]:s+""},targets:await this.resolveTargets(t,n,e.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,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=is(e.classes,t);n.length>0&&Qo(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,Yo(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){Qo(e,Object.entries(t),(e,[t,n])=>{e.style.setProperty(t,n)})}(e.targets,e.styles)}var n,r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const n=t.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(e=>"string"==typeof e))return!1}return!0}};return Io(t,"AddCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const hs=Po(ds),ms={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function ps(e){const t=ms[e];if(void 0===t)throw Error(`Unknown semantic position '${e}'. Valid positions: ${Object.keys(ms).join(", ")}.`);return t}function ys(e){return e.includes("<")&&e.includes(">")}function bs(e,t,n){!function(e,t,n){"replace"!==n?ge(t)?function(e,t,n){switch(n){case"beforebegin":e.parentElement?.insertBefore(t,e);break;case"afterbegin":e.insertBefore(t,e.firstChild);break;case"beforeend":e.appendChild(t);break;case"afterend":e.parentElement?.insertBefore(t,e.nextSibling)}}(e,t,n):function(e,t,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').`);ys(t)?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t)}(e,t,n):function(e,t){ge(t)?(e.innerHTML="",e.appendChild(t)):ys(t)?e.innerHTML=t:e.textContent=t}(e,t)}(e,t,ps(n))}function gs(e,t,n){const r=e;if("function"==typeof r.moveBefore&&t.isConnected&&e.isConnected)try{return void r.moveBefore(t,n)}catch{}e.insertBefore(t,n)}function vs(e,t,n){switch(n){case"beforeend":for(const n of t)gs(e,n,null);break;case"afterbegin":for(let n=t.length-1;n>=0;n--)gs(e,t[n],e.firstChild);break;case"beforebegin":{const n=e.parentElement;if(!n)return;for(const r of t)gs(n,r,e);break}case"afterend":{const n=e.parentElement;if(!n)return;for(let r=t.length-1;r>=0;r--)gs(n,t[r],e.nextSibling);break}case"replace":e.innerHTML="";for(const n of t)gs(e,n,null)}}function ws(e){return!!e.parentNode&&(e.remove(),!0)}let Es=(()=>{let e,t,n=[qo({name:"remove"})],r=[],i=fs;var o=t=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return o.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(be(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&be(r[0]))return{type:"element",targets:r.filter(e=>be(e))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:Xo(i).name,targets:await this.resolveTargets(t,n,e.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(t,n,e.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,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=is(e.classes,t);n.length>0&&Qo(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,Yo(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){Qo(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)ws(t)}var n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}};return Io(t,"RemoveCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const xs=Po(Es);function ks(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Ss(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const n=ks(e);return n?n.milliseconds:t}return t}function Ts(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=ks(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function As(e){return e&&"none"!==e?e.split(",").map(e=>{const t=parseFloat(e.trim());return isNaN(t)?0:e.includes("s")&&!e.includes("ms")?1e3*t:t}):[0]}function Cs(e,t){let n=0;for(let r=0;e.length>r;r++)n=Math.max(n,(e[r]||0)+(t[r]||0));return n}function $s(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function js(e){return"DIALOG"===e.tagName}function Os(e){return"DETAILS"===e.tagName}function Ns(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&es(e,n)}}function Rs(e,t,n,r){const i=Ns(e,t,n),o=setTimeout(i,r);return()=>{clearTimeout(o)}}function Ls(e,t,n,r){const i=Ns(e,t,n),o=()=>{i(),e.removeEventListener(r,o)};return e.addEventListener(r,o,{once:!0}),()=>{e.removeEventListener(r,o)}}function Ms(e,t,n){if(t.startsWith("@")){const r=t.substring(1);return void(!1===n?e.removeAttribute(r):e.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(t){case"textContent":return void(e.textContent=r);case"innerHTML":return void(e.innerHTML=r);case"innerText":return void(e.innerText=r);case"id":return void(e.id=r);case"className":return void(e.className=r);case"value":return void("value"in e&&(e.value=r));case"checked":return void("checked"in e&&(e.checked=!!n))}if(t.includes(".")){const r=t.split(".");let i=e;for(let e=0;r.length-1>e;e++)if(i=i[r[e]],null==i)return;return void(i[r[r.length-1]]=n)}if(t.includes("-")||t in e.style)e.style.setProperty(t,r);else try{e[t]=n}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function Is(e){return null==e||""===e}function qs(e,t){return function(e){return!!e&&"object"==typeof e&&"string"==typeof e.type}(e)&&e.type===t}function Hs(e){return qs(e,"literal")}const Ps=/^the\s+(.+?)\s+of\s+(.+)$/i,Bs=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 Vs(e){return"string"==typeof e&&Ps.test(e)}function Fs(e,t){const n=e.match(Ps);if(!n)return null;try{return{element:Vo(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function Ds(e,t,n){if(function(e){if(!qs(e,"propertyOfExpression"))return!1;const t=e.property;return"object"==typeof t&&null!==t}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let i=await t.evaluate(e.target,n);return Array.isArray(i)&&(i=i[0]),be(i)?{element:i,property:r}:null}(e,t,n);if(function(e){if(!qs(e,"propertyAccess"))return!1;const t=e.property;return"string"==typeof t||"object"==typeof t&&null!==t&&"string"==typeof t.name}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let i=await t.evaluate(e.object,n);return Array.isArray(i)&&(i=i[0]),be(i)?{element:i,property:r}:null}(e,t,n);const r=e;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const e=r.object,i=r.property;let o=await t.evaluate(e,n);if(Array.isArray(o)&&(o=o[0]),!be(o))return null;const s=i?.name||i?.value;return s?{element:o,property:s}:null}return null}function Us(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):Be(t,n)}function _s(e,t){const{element:n,property:r}=e;r.startsWith("*")?as(n,r.substring(1),t+""):Ms(n,r,t)}async function zs(e,t,n){let r,i;if(e?.for){const i=await t.evaluate(e.for,n);r="number"==typeof i?i:"string"==typeof i?Ss(i):void 0}if(e?.until){const r=await t.evaluate(e.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function Ws(e,t){const n=t?.name,r=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return cs.includes(t)}(t)}(t);if(be(e)||Array.isArray(e)&&e.every(e=>be(e)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return cs.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const Zs=Po((()=>{let e,t,n=[qo({name:"toggle"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers?.between;if(qs(r,"arrayLiteral")&&r.elements.length>=2){const{duration:i,untilEvent:o}=await zs(e.modifiers,t,n),s=async e=>qs(e,"selector")?e.value:t.evaluate(e,n);return{type:"classes-between",classA:(await s(r.elements[0])+"").replace(/^\./,""),classB:(await s(r.elements[1])+"").replace(/^\./,""),targets:await _o([],t,n,"toggle",{fallbackModifierKey:"on"},e.modifiers),duration:i,untilEvent:o}}if(!e.args?.length)throw Error("toggle command requires an argument");const i=e.args[0],o=await Ds(i,t,n);if(o)return{type:"property",target:o};if("selector"===i.type&&"string"==typeof i.value&&i.value.startsWith("*")){let r=i.value,o=1;if("*"===r&&"identifier"===e.args[1]?.type&&(r="*"+e.args[1].name,o=2),"*"===r&&e.modifiers?.on){const i=e.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:o,untilEvent:s}=await zs(e.modifiers,t,n),a=ss(r);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:o,untilEvent:s}}}}const s=ss(r);if(s){const{duration:r,untilEvent:i}=await zs(e.modifiers,t,n),a={fallbackModifierKey:"on"};return{type:"css-property",property:s,targets:await _o(e.args.slice(o),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:i}}}const{duration:s,untilEvent:a}=await zs(e.modifiers,t,n),{value:c}=await us(i,t,n);if(Vs(c)){const e=Fs(c,n);if(e)return{type:"property",target:e}}const{type:l,expression:u}=Ws(c,i),f={fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:i}=Xo(u);return{type:"attribute",name:r,value:i,targets:await _o(e.args.slice(1),t,n,"toggle",f,e.modifiers),duration:s,untilEvent:a}}case"css-property":{const r=ss(u);if(!r)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:r,targets:await _o(e.args.slice(1),t,n,"toggle",f,e.modifiers)}}case"element":{let r;if(be(c))r=[c];else if(Array.isArray(c)&&c.every(e=>be(e)))r=c;else if(u){const e=document.querySelectorAll(u);r=Array.from(e).filter(e=>be(e))}else r=await _o([i],t,n,"toggle",f,e.modifiers);const o=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(r);if("dialog"===o){const i=await async function(e,t,n){if(!e?.as)return"non-modal";const r=await t.evaluate(e.as,n);return"string"==typeof r&&"modal"===r.toLowerCase()?"modal":"non-modal"}(e.modifiers,t,n);return{type:"dialog",mode:i,targets:r}}return"details"===o?{type:"details",targets:$s(r)}:"select"===o?{type:"select",targets:r}:{type:"classes",classes:ts(u),targets:r,duration:s,untilEvent:a}}default:{const r=ts(u||c);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await _o(e.args.slice(1),t,n,"toggle",f,e.modifiers),duration:s,untilEvent:a}}}}async execute(e,t){switch(e.type){case"classes":{const n=is(e.classes,t);if(0===n.length)return[...e.targets];if(Qo(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&Rs(t,"class",n[0],e.duration),e.untilEvent&&Ls(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,Yo(e.targets,e=>{es(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Rs(t,"attribute",e.name,e.duration),e.untilEvent&&Ls(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return Yo(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=Us(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||Bs.has(r)||Bs.has(r.toLowerCase())){const n=!t;return _s(e,n),n}if("number"==typeof t){const n=0===t?1:0;return _s(e,n),n}if("string"==typeof t){const r="__ht_"+n,i=e.element[r];return""===t&&void 0!==i?(_s(e,i),i):(e.element[r]=t,_s(e,""),"")}_s(e,!t)}(e.target),[e.target.element];case"dialog":return Yo(e.targets,t=>{return r=e.mode,void((n=t).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return Yo(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return Yo(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const n=t.classList.contains(e.classA),r=t.classList.contains(e.classB);n?(t.classList.remove(e.classA),t.classList.add(e.classB)):r?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Rs(t,"class",e.classA,e.duration),e.untilEvent&&Ls(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}};return Io(t,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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","toggle between .expanded and .collapsed","toggle .loading until click from #done"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Mo(t,r),i=t})());const Js=Po((()=>{let e,t,n=[qo({name:"put"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=["into","before","after","at","at start of","at end of"].find(t=>e.modifiers?.[t]);let i=e.args[0]??null,o=null,s=null;if(r)o=r,s=e.modifiers[r];else{if(!e.args[1])throw Error("put requires content and position");o="into",s=e.args[1]}if(!i)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const a=await t.evaluate(i,n),c=this.mapPosition(o);let l,u,f=null;if(s){const e=(d=s,d?.type||"unknown"),r=await Ds(s,t,n);if(r)return{value:a,targets:[r.element],position:"into",memberPath:r.property};if("memberExpression"===e){const e=s.object,r=s.property;if("selector"===e?.type)f=e.value;else if("identifier"===e?.type){const i=e.name;if("my"===i||"me"===i||"I"===i){if(n.me&&r?.name)return{value:a,targets:[n.me],position:"into",memberPath:r.name}}else if("its"===i||"it"===i){const e=await t.evaluate(s,n);"string"==typeof e&&(f=e)}else f=i}if(f&&r?.name)l=r.name;else if(!f&&!l){const e=await t.evaluate(s,n);"string"==typeof e&&(f=e)}}else if("identifier"===e&&"me"===s.name)f=null;else if("selector"===e||"cssSelector"===e)f=s.value||s.selector;else if("literal"===e){const e=s.value;if("string"==typeof e&&Vs(e)){const t=Fs(e,n);if(t)return{value:a,targets:[t.element],position:"into",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?f=e:u=e+""}else if("identifier"===e){const e=s.name;if(this.looksLikeCss(e))f=e;else{const r=Ae(await t.evaluate(s,n));if(r)return{value:a,targets:r,position:c,memberPath:l};u=e}}else{const e=await t.evaluate(s,n),r=Ae(e);if(r)return{value:a,targets:r,position:c,memberPath:l};"string"==typeof e&&(this.looksLikeCss(e)?f=e:u=e)}}var d;return u?{value:a,targets:[],position:c,memberPath:l,variableName:u}:{value:a,targets:await this.resolveTargets(f,n),position:c,memberPath:l}}async execute(e,t){const{value:n,targets:r,position:i,memberPath:o,variableName:s}=e;if(s)return t.locals&&t.locals.set(s,n),t[s]=n,void Object.assign(t,{it:n});if(o)for(const e of r)this.setProperty(e,o,n);else for(const e of r){const t=this.parseValue(n);Array.isArray(t)?vs(e,t,ps(i)):bs(e,t,i)}return r}mapPosition(e){switch(e){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: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!be(t.me))throw Error("put: no target and context.me is null");return[t.me]}return Te(e)}parseValue(e){return be(e)||Array.isArray(e)&&e.length>0&&e.every(be)||ge(e)?e:null==e?"":e+""}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,n){const r=t.split(".");let i=e;for(let e=0;r.length-1>e;e++){if(!i[r[e]])throw Error(`Property path "${t}" does not exist`);i=i[r[e]]}i[r[r.length-1]]=n}};return Io(t,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Ks={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function Gs(e){return e.replace(/[&<>"']/g,e=>Ks[e])}let Xs=(()=>{let e,t,n=[qo({name:"make"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers.an??e.modifiers.a??e.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const i=r.raw;let o="string"==typeof i&&i.startsWith("<")?i:await t.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(e,t){if(!e.includes("{"))return e;const n=/\{([^{}]+)\}/g,r=[];let i;for(;null!==(i=n.exec(e));){let e=i[0];try{const n=await Ni(i[1].trim(),t);null!=n&&(e=Gs(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:e})}let o=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,text:i}=r[e];o=o.slice(0,t)+i+o.slice(t+n)}return o}(o,n));const s=void 0!==e.modifiers.an?"an":"a",a=await async function(e,t,n){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const r=[];for(const i of e.args)r.push(await t.evaluate(i,n));return r}const r=await t.evaluate(e,n);return Array.isArray(r)?r:[r]}(e.modifiers.from,t,n),c=await async function(e,t,n){if(!e)return;if(("symbol"===e.type||"identifier"===e.type)&&"string"==typeof e.name)return e.name;const r=await t.evaluate(e,n);return"string"==typeof r?r:void 0}(e.modifiers.called,t,n);return{article:s,expression:o,constructorArgs:a,variableName:c}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:i}=e,o="string"==typeof n&&n.startsWith("<"),s=o&&n.endsWith("/>")?function(e){const t=e.slice(1,-2);let n="div",r=t;const i=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=t.slice(i[0].length));const o=document.createElement(n),s=r.split(/(?=[.#])/);for(const e of s)if(e.startsWith("#")){const t=e.slice(1);t&&(o.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&o.classList.add(t)}return o}(n):o&&/<\/[a-zA-Z]/.test(n)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstElementChild;if(n&&be(n))return n;const r=document.createElement("div");r.innerHTML=e.trim();const i=r.firstElementChild;return i&&be(i)?i:r}(n):function(e,t,n){if(be(e))return e;if("function"==typeof e){const n=e;return 0===t.length?new n:new n(...t)}const r=e+"";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===t.length?new i:new i(...t)}(n,r,t);return Object.assign(t,{it:s}),i&&xe(i,s,t),s}};return Io(t,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})();const Ys=Po(Xs),Qs=Po((()=>{let e,t,n=[qo({name:"empty"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"empty",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"EmptyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function ea(e){if("string"!=typeof e)return;const t=e.toLowerCase().trim();return"non-modal"===t||"nonmodal"===t?"non-modal":"modal"===t?"modal":void 0}function ta(e){return e.hasAttribute("popover")}const na=Po((()=>{let e,t,n=[qo({name:"open"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=$s(await _o(r,t,n,"open",{fallbackModifierKey:"on"},e.modifiers)),o=await async function(e,t,n,r){if(t?.as){const e=ea(await n.evaluate(t.as,r));if(e)return e}for(const t of e){const e=t;if("asExpression"!==e?.type)continue;const n=e.targetType,r=ea(n?.name??n?.value);if(r)return r}for(let t=0;e.length-1>t;t++){const i=e[t];if("identifier"===i?.type&&"as"===i.name?.toLowerCase()){const i=await n.evaluate(e[t+1],r);if("string"==typeof i){const e=i.toLowerCase().trim();if("non-modal"===e||"nonmodal"===e)return"non-modal";if("modal"===e)return"modal"}}}return"modal"}(e.args??[],e.modifiers??{},t,n);return{targets:i,dialogMode:o}}async execute(e,t){for(const t of e.targets)if(js(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(Os(t))t.open=!0;else if(ta(t)){const e=t;if("function"==typeof e.showPopover)try{e.showPopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>be(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}};return Io(t,"OpenCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function ra(e){return e.hasAttribute("popover")}const ia=Po((()=>{let e,t,n=[qo({name:"close"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:$s(await _o(e.args,t,n,"close",{fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(js(t))t.open&&t.close();else if(Os(t))t.open=!1;else if(ra(t)){const e=t;if("function"==typeof e.hidePopover)try{e.hidePopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"CloseCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function oa(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const sa=Po((()=>{let e,t,n=[qo({name:"select"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"select",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(oa(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),n=e?.defaultView;if(!e||!n)continue;const r=n.getSelection?.();if(r)try{const n=e.createRange();n.selectNodeContents(t),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"SelectCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function aa(e){return"FORM"===e.tagName}const ca=Po((()=>{let e,t,n=[qo({name:"reset"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"reset",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)aa(t)&&t.reset()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"ResetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function la(e,t,n,r){return e?new Promise(n=>{const i=()=>{o({event:null,timedOut:!1,cancelled:!0})},o=fa(()=>{e.removeEventListener(t,s),r&&r.removeEventListener("abort",i)},n),s=e=>{o({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,s),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function ua(e){return new Promise(t=>setTimeout(t,e))}function fa(e,t){let n=!1;return r=>{n||(n=!0,e(),t(r))}}const da=Po((()=>{let e,t,n=[qo({name:"wait"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await ua(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,i=(await la(r,e.eventName)).event;if(Object.assign(t,{it:i}),e.destructure)for(const n of e.destructure)n in i&&t.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const e of i.destructure)e in r&&t.locals.set(e,r[e]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(e,t,n){return{type:"time",milliseconds:Ts(await t.evaluate(e,n))}}async parseEventArrayWait(e,t,n,r){let i;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");i=e}i||(i=r.me??void 0);const o=[];for(const t of e){const e=t;if("objectLiteral"!==e.type||!e.properties)continue;let s,a="",c=[];for(const t of e.properties){const e=t.key?.name||t.key?.value;if("name"===e&&t.value){if("string"!=typeof t.value.value)throw Error("wait for: event name must be a string");a=t.value.value}else"args"===e&&t.value?.elements?c=t.value.elements.map(e=>e.value||e.name||""):"duration"===e&&t.value&&(s=t.value)}if(s){const e=await n.evaluate(s,r);o.push({type:"time",milliseconds:Ts(e)})}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 executeRace(e,t){const n=new AbortController,r=n.signal,i=e.map(e=>"time"===e.type?ua(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):la(e.target??t.me??document,e.eventName,0,r).then(t=>({result:t.event,winningCondition:e})));try{return await Promise.race(i)}finally{n.abort()}}};return Io(t,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),ha=new Map;let ma=[/^4\d{2}$/,/^5\d{2}$/],pa=(()=>{let e,t,n=[qo({name:"fetch"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),i=this.parseResponseType(e.modifiers.as);return{url:r,responseType:i,options:await this.parseRequestOptions(e.modifiers.with,t,n),throwOnError:!e.modifiers.doNotThrow&&"response"!==i}}async execute(e,t){const n=Date.now(),{url:r,responseType:i,options:o}=e,s=new AbortController;let a;t.me&&(a=()=>s.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...o,signal:s.signal},l=ha.get(i);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;o.timeout&&(u=setTimeout(()=>s.abort(),o.timeout));try{let o=await fetch(r,c);if(t.me){const e={response:o};this.dispatchEvent(t.me,"fetch:afterResponse",e),o=e.response}if(e.throwOnError&&function(e){const t=e+"";return ma.some(e=>e.test(t))}(o.status)){const e=Error(`Fetch failed for ${r}: HTTP ${o.status} ${o.statusText}`.trim());throw e.response=o,e.isFetchStatusError=!0,e}const s=await this.handleResponse(o,i,t);t.me&&this.dispatchEvent(t.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(t,{it:s}),a}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r){const t=e;if(null==r&&"identifier"===t?.type&&t.name)throw Error(`fetch: URL expression "${t.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(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(ha.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,n){if(!e)return{};const r=await t.evaluate(e,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const 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(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[n,r]of Object.entries(e))t.set(n,r+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,n){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const r=ha.get(t);return r?r.handler(e,n):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),1===n.childNodes.length&&be(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}};return Io(t,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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" }','fetch "/api/optional" as json do not throw'],sideEffects:["network","event-dispatching"],category:"async",compatibility:"standard"}),Mo(t,r),i=t})();const ya=Po(pa);async function ba(e,t,n){const r=await t.evaluate(e,n),i=Array.isArray(r)?r[0]:r;return be(i)?i:null}async function ga(e,t,n,r){if(!e)return null;const i=e,o=i.type;if(r.nodeWriters&&o){const t=ce(o);if(t)return{kind:"node-write",node:e,writer:t}}if(r.selectorSource&&"selector"===o&&"string"==typeof i.value)return{kind:"selector",selector:i.value};const s=await async function(e,t,n,r){const i=e;if("attributeAccess"===i?.type)return{elements:await r(),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const e=await ba(i.right,t,n);if(e)return{elements:[e],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const e=await ba(i.object,t,n);if(e)return{elements:[e],name:i.property.attributeName}}return null}(e,t,n,r.scopeElements);if(s)return{kind:"attribute",elements:s.elements,name:s.name};const a=await Ds(e,t,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 e=i.scope;return{kind:"variable",name:i.name,scope:"element"===e||"global"===e?e:void 0}}return null}const va=Po((()=>{let e,t,n=[qo({name:"set"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],i=r?.name||r?.value,o=r?.scope,s=await ga(r,t,n,{scopeElements:()=>this.resolveTargets(e.modifiers.on,t,n),nodeWriters:!0,styleSplit:!0});if(s)return function(e,t){switch(e.kind){case"node-write":return{type:"node-write",node:e.node,value:t,writer:e.writer};case"attribute":return{type:"attribute",elements:e.elements,name:e.name,value:t};case"style":return{type:"style",element:e.element,property:e.property,value:t+""};case"property":return{type:"property",element:e.target.element,property:e.target.property,value:t};default:throw Error(`set: unrequested write-target rung '${e.kind}'`)}}(s,await this.extractValue(e,t,n));if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,e,t,n);if(i)return i}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await t.evaluate(r,n):i,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(be(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(Vs(a)){const r=Fs(a,n);if(r){const i=await this.extractValue(e,t,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(a,e,t,n)}if("string"==typeof a&&os(a)){const r=a.substring(1).trim(),i=await this.extractValue(e,t,n);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,n),property:r,value:i+""}}if("string"==typeof a&&Go(a)){const r=a.substring(1).trim(),i=await this.extractValue(e,t,n);return{type:"attribute",elements:await this.resolveTargets(e.modifiers.on,t,n),name:r,value:i}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=Uo(r[1],n),o=await this.extractValue(e,t,n);return{type:"property",element:i,property:r[2],value:o}}}if(be(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(a)&&a.length>0&&be(a[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(e,t,n),scope:"element"===o||"global"===o?o:void 0}}async execute(e,t){switch(e.type){case"variable":return"element"===e.scope?me(t,e.name,e.value):"global"===e.scope?xe(e.name,e.value,t,"global"):xe(e.name,e.value,t),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":for(const t of e.elements)t.setAttribute(e.name,e.value+"");return Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return Ms(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return as(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[n,r]of Object.entries(e.properties))Ms(t,n,r);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};case"node-write":return await e.writer(e.node,e.value,t),Object.assign(t,{it:e.value}),{target:e.node.name??"",value:e.value,targetType:"variable"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,n,r){const i=e.object,o=e.property;if(i?.name&&o?.name){const e=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const i=Uo(e,r),s=await this.extractValue(t,n,r);return{type:"property",element:i,property:o.name,value:s}}}const s=e.object,a=e.computed;if(s){const i=s;let c;if("memberExpression"===i.type&&!i.computed&&"style"===i.property?.name&&i.object){const e=await n.evaluate(i.object,r);c=(e&&"object"==typeof e&&"style"in e?e.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(e.property,r)+"":o?.name||"";if(i)return{type:"member-assignment",container:c,property:i,value:await this.extractValue(t,n,r)}}}return null}async extractValue(e,t,n){if(e.modifiers.to)return t.evaluate(e.modifiers.to,n);const r=e.args[1];if(r)return t.evaluate(r,n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return Vo(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return Fo(e?await t.evaluate(e,n):void 0,n)}async parseTheXofY(e,t,n,r){const i=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw Error('Invalid "the X of Y" syntax');const[,o,s]=i,a=Vo(s,r),c=await this.extractValue(t,n,r);return{type:"property",element:a,property:o.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&Array.isArray(t.elements)&&t.elements.every(be)&&"value"in t;case"property":return"string"==typeof t.property&&be(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&be(t.element)&&"string"==typeof t.value;case"object-literal":return null!==t.properties&&"object"==typeof t.properties&&Array.isArray(t.targets)&&t.targets.length>0;default:return!1}}};return Io(t,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),wa=Po((()=>{let e,t,n=[qo({name:"get"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const r=e.args[0],i=await t.evaluate(r,n);return i instanceof NodeList&&1===i.length||Array.isArray(i)&&1===i.length?{value:i[0]}:{value:i}}execute(e,t){return t.it=e.value,Object.assign(t,{result:e.value}),{value:e.value}}validate(e){return"object"==typeof e&&null!==e&&"value"in e}};return Io(t,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function Ea(e){return e&&"object"==typeof e&&e.type||"unknown"}let xa=(()=>{let e,t,n=[qo({name:"increment"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",i=await async function(e,t,n,r){if(!e.args||0===e.args.length)throw Error(r+" command requires a target");const i=e.args[0];let o,s,a;const c=Ea(i);if("identifier"===c)o=i.name,i.scope&&(s=i.scope);else if("literal"===c)o=i.value;else{const e=ce(c);if(e){const r=await t.evaluate(i,n),s="number"==typeof r?r:null==r?0:Number(r)||0;o=s,a={node:i,writer:e,currentValue:s}}else{const e=await t.evaluate(i,n);o=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=s;for(let r=1;e.args.length>r;r++){const i=e.args[r];if(Hs(i)){const e=i.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(i){const e=await t.evaluate(i,n);"number"==typeof e&&(l=e)}}const f=e.modifiers?.by;if(f){const e=f.value;if("literal"===Ea(f)&&"number"==typeof e)l=e;else if("literal"!==Ea(f)){const e=await t.evaluate(f,n);"number"==typeof e&&(l=e)}}return{target:o,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(e,t,n,r);return{...i,operation:r}}async execute(e,t){const{target:n,property:r,scope:i,amount:o=1,operation:s="increment",customWrite:a}=e;if(a){const e=isFinite(o)?o:1,n="increment"===s?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(be(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?we(n.getAttribute(t)):we(n[t]):we(n.value||n.textContent)}return"string"==typeof e?"element"===n?we(Ee(e,r,"element")):"global"===n?we(Ee(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],i=ke(n[0],t);return i?we(i[r]):0}(e,r):we("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:Ee(e,r)):we(e)}(n,r,i,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(o)?o:1;l="increment"===s?c+e:c-e}return function(e,t,n,r,i){if(be(e)){const n=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?n.setAttribute(t,r+""):n[t]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof e){if("element"===n)return void xe(e,r,i,"element");if("global"===n)return void xe(e,r,i,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),i=r[1],o=ke(r[0],n);o&&(o[i]=t)}(e,r,i);if("me"===e&&i.me)return void(i.me.value=r);if("it"===e)return void Object.assign(i,{it:r});if("you"===e&&i.you)return void(i.you.value=r);xe(e,r,i)}}(n,r,i,l,t),Object.assign(t,{it:l}),l}};return Io(t,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})();const ka=Po(xa),Sa=Po(xa),Ta=Po((()=>{let e,t,n=[qo({name:"default"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(1>e.args.length)throw Error("default command requires a target");const r=await this.extractValue(e,t,n),i=e.args[0],o=function(e){if("contextReference"!==e?.type)return null;const t=e.name;return"string"!=typeof t?null:t.startsWith(":")?{name:t.slice(1),scope:"element"}:t.startsWith("$")?{name:t.slice(1),scope:"global"}:null}(i);if(o)return{type:"variable",name:o.name,value:r,scope:o.scope};const s=await ga(i,t,n,{scopeElements:async()=>n.me?[n.me]:[],bareReference:!0});if(s)return function(e,t){switch(e.kind){case"attribute":return{type:"attribute",elements:e.elements,name:e.name,value:t};case"property":return{type:"property",element:e.target.element,property:e.target.property,value:t};case"variable":{const n=e.name.startsWith("$"),r=n?e.name.slice(1):e.name,i=n?"global":e.scope;return{type:"variable",name:r,value:t,...i?{scope:i}:{}}}default:throw Error(`default: unrequested write-target rung '${e.kind}'`)}}(s,r);const a=await t.evaluate(e.args[0],n);if(be(a))return{type:"element",element:a,value:r};if(Array.isArray(a)&&be(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(e,t,n){if(e.modifiers?.to)return t.evaluate(e.modifiers.to,n);const r=e.args[1];if(r)return t.evaluate(r,n);throw Error('default command requires a value (use "to <value>")')}async execute(e,t){switch(e.type){case"variable":return this.defaultVariable(t,e.name,e.value,e.scope);case"attribute":return this.defaultAttribute(t,e.elements,e.name,e.value);case"property":return this.defaultElementProperty(t,e.element,e.property,e.value);case"element":return this.defaultElementValue(t,e.element,e.value)}}defaultVariable(e,t,n,r){const i=Ee(t,e,r);return null!=i?{target:t,value:n,wasSet:!1,existingValue:i,targetType:"variable"}:(xe(t,n,e,r),Object.assign(e,{it:n}),{target:t,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,n,r){if(0===t.length)throw Error("No element context available for attribute default");const i=t.filter(e=>null===e.getAttribute(n));if(0===i.length)return{target:"@"+n,value:r,wasSet:!1,existingValue:t[0].getAttribute(n),targetType:"attribute"};for(const e of i)e.setAttribute(n,r+"");return Object.assign(e,{it:r}),{target:"@"+n,value:r,wasSet:!0,targetType:"attribute"}}defaultElementProperty(e,t,n,r){const i=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const n=t.split(".");let r=e;for(const e of n){if(null==r)break;r=r[e]}return r}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(t,n);return Is(i)?(Ms(t,n,r),Object.assign(e,{it:r}),{target:n,value:r,wasSet:!0,targetType:"property"}):{target:n,value:r,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(e,t,n){const r=function(e){return"value"in e?e.value:e.textContent}(t);return Is(r)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,n),Object.assign(e,{it:n}),{target:"element",value:n,wasSet:!0,targetType:"element"}):{target:"element",value:n,wasSet:!1,existingValue:r,targetType:"element"}}};return Io(t,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function Aa(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const Ca=Po((()=>{let e,t,n=[qo({name:"clear"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.args?.[0],i=function(e){if(!e)return null;const t=e.type,n=e.name;if("string"!=typeof n||""===n)return null;if("variable"===t||"identifier"===t)return{name:n,scope:e.scope};if("contextReference"===t){if(n.startsWith(":"))return{name:n.slice(1),scope:"element"};if(n.startsWith("$"))return{name:n.slice(1),scope:"global"}}return null}(r);if(i)try{const e=await t.evaluate(r,n);if(!be(e)&&!Array.isArray(e))return{type:"variable",...i}}catch{return{type:"variable",...i}}return{type:"form-fields",targets:await _o(e.args,t,n,"clear",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return xe(e.name,null,t,e.scope),void Object.assign(t,{it:null});for(const t of e.targets)Aa(t)&&("SELECT"===t.tagName?t.selectedIndex=-1:t.value="")}validate(e){if("object"!=typeof e||null===e)return!1;if("variable"===e.type)return"string"==typeof e.name;if("form-fields"===e.type){const t=e.targets;return Array.isArray(t)&&t.every(e=>be(e))}return!1}};return Io(t,"ClearCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function $a(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}let ja=(()=>{let e,t,n=[qo({name:"trigger"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r="send"===e.commandName?.toLowerCase()?"send":"trigger",i=r;if(!e.args?.length)throw Error(i+" command requires an event name");const o=e=>e?.type||"unknown",s=e.args[0];let a,c,l;if("functionCall"===o(s)||"callExpression"===o(s)){a=s.name||s.callee?.name;const e=s.args||s.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===o(s)||"keyword"===o(s))a=s.name;else{const e=await t.evaluate(s,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,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(e.modifiers?.with,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const i=[];for(const r of e){const e=await t.evaluate(r,n);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&n.me)i.push(n.me);else if("you"===e&&n.you)i.push(n.you);else if("it"===e&&n.it)i.push(n.it);else if(be(e))i.push(e);else if(e instanceof NodeList)i.push(...Array.from(e).filter(be));else if(Array.isArray(e))i.push(...e.filter(be));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);i.push(...Array.from(t).filter(be));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);i.push(e)}else i.push(document);else i.push(window)}if(!i.length)throw Error(r+": no valid targets");return i}async parseEventDetail(e,t,n){if(!e?.length)return;if(1===e.length){const r=e[0];if("objectLiteral"!==r?.type)return await t.evaluate(r,n)}const r={};for(const i of e){const e=await t.evaluate(i,n);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,n]=e.split(":",2);r[t.trim()]=$a(n.trim())}}else Object.assign(r,e)}return Object.keys(r).length?r:void 0}async parseEventOptions(e,t,n){const r={bubbles:!0,cancelable:!0,composed:!1};if(!e)return r;const i=e,o=qs(i,"arrayLiteral")?i.elements:[e];for(const e of o){const i=await t.evaluate(e,n);if("string"==typeof i){const e=i.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 Io(t,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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","send saved to #form with bubbles cancelable"],sideEffects:["event-dispatch"],aliases:["send"],category:"event",compatibility:"standard"}),Mo(t,r),i=t})();const Oa=Po(ja),Na=Po(ja),Ra=Po((()=>{let e,t,n=[qo({name:"go"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers;if(r.back)return{kind:"back"};if(r.forward)return{kind:"forward"};const i=void 0!==r.in;if(void 0!==r.url){const e=await t.evaluate(r.url,n)+"";if(!this.isValidUrl(e))throw Error(`Invalid URL: "${e}"`);return{kind:"url",url:e,newWindow:i}}const o=r.of??e.args[0];if(!o&&!r.position)throw Error("Go command requires arguments");const s=o?await t.evaluate(o,n):"body";if("string"==typeof s&&this.isBareUrl(s)&&!r.of&&!r.position)return{kind:"url",url:s,newWindow:i};const a=this.resolveScrollTarget(s,n);if(!a)throw Error("Target element not found: "+s);const c=r.position?await t.evaluate(r.position,n)+"":void 0,l={vertical:"top",horizontal:"nearest"};"top"===c||"middle"===c||"bottom"===c?l.vertical=c:"left"!==c&&"center"!==c&&"right"!==c||(l.horizontal=c,l.vertical="nearest");const u="instant"===(r.behavior?await t.evaluate(r.behavior,n):void 0)?"instant":"smooth";let f=0;if(void 0!==r.by){const e=Number((await t.evaluate(r.by,n)+"").replace(/px$/,""));Number.isNaN(e)||(f=e)}return{kind:"scroll",target:a,position:l,offset:f,behavior:u}}async execute(e,t){if("back"===e.kind||"forward"===e.kind)return await this.goHistory(e.kind),{result:e.kind,type:"back"};if("url"===e.kind)return this.navigate(e.url,e.newWindow),{result:e.url,type:"url"};const{target:n,position:r,offset:i,behavior:o}=e;if("undefined"!=typeof window){const e=this.mapVerticalPosition(r.vertical),t=this.mapHorizontalPosition(r.horizontal);if(n.scrollIntoView?.({behavior:o,block:e,inline:t}),0!==i){const{x:e,y:t}=this.calculateScrollPosition(n,r,i);window.scrollTo?.({left:e,top:t,behavior:o})}}return{result:n,type:"scroll"}}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}navigate(e,t){if(t){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e))}async goHistory(e){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");"back"===e?window.history.back():window.history.forward()}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=e.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(t.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(t.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)}}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&be(t.me))return t.me;if("it"===n&&be(t.it))return t.it;if("you"===n&&be(t.you))return t.you;const r=Ee(n,t);if(be(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}};return Io(t,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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 url "https://example.com" in new window',"go to top of #header","go to bottom of #footer smoothly"],sideEffects:["navigation","scrolling"],category:"navigation",compatibility:"standard"}),Mo(t,r),i=t})());function La(e,t){const n=e.bodies?.[t];if(!n)throw Error(`${e.commandName??"command"}: argument ${t} is a body but was not compiled \u2014 run it through the runtime`);return n}function Ma(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const n=Ee(e,t);return void 0!==n?!!n:!!e}return!!e}const Ia=Po((()=>{let e,t,n=[qo({name:"if"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(r+" command requires a condition to evaluate");let i,o;if("unless"===r){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");i=La(e,1)}else if(e.args.length>=2&&e.args[1]&&(i=La(e,1),o=3>e.args.length?void 0:La(e,2)),!i)throw Error('if command requires "then" branch with commands');return{mode:r,condition:await t.evaluate(e.args[0],n),thenCommands:i,elseCommands:o}}async execute(e,t){const{mode:n,condition:r,thenCommands:i,elseCommands:o}=e,a=Ma(r,t);let c,l,u;if(("unless"===n?!a:a)?(c="then",u=i):o&&"if"===n?(c="else",u=o):c="none",u){const e=await u(t);if(!s(e))return e.error;l=e.value}return{mode:n,conditionResult:a,executedBranch:c,result:l}}};return Io(t,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),qa=Ia,Ha=Ia;let Pa=(()=>{let e,t,n=[qo({name:"repeat"})],r=[];var o=t=class{get metadata(){return o.metadata}async parseInput(e,t,n){let r,i,o;if(e.modifiers?.index){const i=await t.evaluate(e.modifiers.index,n);"string"==typeof i&&(r=i)}{const t=[];for(let n=e.args.length-1;n>=0;n--){const r=e.args[n];if("block"===r?.type&&r.commands&&(t.unshift(n),2===t.length))break}2===t.length?(i=La(e,t[0]),o=La(e,t[1])):1===t.length&&(i=La(e,t[0]))}const s=e.modifiers??{},a=e=>async function(e,t,n){if(!e)return;const r=e;if(qs(r,"string"))return r.value;if(qs(r,"literal")&&"string"==typeof r.value)return r.value;if(qs(r,"identifier"))return r.name;const i=await t.evaluate(e,n);return"string"==typeof i?i:void 0}(e,t,n),c=await a(s.loopType)??null,l=!!s.bottomTested&&await t.evaluate(s.bottomTested,n);if("for"===c||s.for){const e=await a(s.for),c=s.in&&await t.evaluate(s.in,n);if(!e||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:e,collection:Array.isArray(c)?c:[c],indexVariable:r,commands:i,elseCommands:o}}if("times"===c||s.times){const e=s.times&&await t.evaluate(s.times,n),a="number"==typeof e?e:parseInt(e+"",10);if(isNaN(a))throw Error("times loops require a count number");return{type:"times",count:a,indexVariable:r,commands:i,elseCommands:o}}if("while"===c||s.while){const e=s.while;if(!e)throw Error("while loops require a condition");return{type:"while",condition:e,indexVariable:r,commands:i,elseCommands:o,bottomTested:l}}if("until-event"===c||s.event){const e=await a(s.event);if(!e)throw Error("until-event loops require an event name");let c=n.me;if(s.from){const e=s.from,r=qs(e,"identifier")?e.name:void 0;if("document"===r)c=document;else if("window"===r&&"undefined"!=typeof window)c=window;else{const e=await t.evaluate(s.from,n);e instanceof EventTarget?c=e:"document"===e?c=document:"undefined"!=typeof window&&e===window&&(c=window)}}return{type:"until-event",eventName:e,eventTarget:c,indexVariable:r,commands:i,elseCommands:o}}if("until"===c||s.until){const e=s.until;if(!e)throw Error("until loops require a condition");return{type:"until",condition:e,indexVariable:r,commands:i,elseCommands:o,bottomTested:l}}if("forever"===c)return{type:"forever",indexVariable:r,commands:i,elseCommands:o};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:n,variable:r,collection:o,condition:a,count:c,indexVariable:l,commands:u,elseCommands:f,bottomTested:d,eventName:h,eventTarget:m}=e;let p,y;switch(n){case"for":({config:p,iterCtx:y}=function(e,t,n){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:n}}}(o,r,l));break;case"times":({config:p,iterCtx:y}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(c,l));break;case"while":({config:p,iterCtx:y}=function(e,t,n,r){return{config:{type:"while",shouldContinue:()=>t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(a,Ma,t,l));break;case"until":({config:p,iterCtx:y}=function(e,t,n,r){return{config:{type:"until",shouldContinue:()=>!t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(a,Ma,t,l));break;case"until-event":({config:p,iterCtx:y}=function(e,t,n){const r={index:0,eventFired:!1,indexVariable:n};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{r.eventFired=!0}}},iterCtx:r}}(h,m,l));break;case"forever":({config:p,iterCtx:y}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(l));break;default:throw Error("Unknown repeat type: "+n)}if(d){const e=p.shouldContinue;p.shouldContinue=async t=>0===t.index||await e(t)}const b=await async function(e,t,n,r){const i=e.maxIterations??1e4;let o,a=0,c=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>a&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,t),n.indexVariable&&t.locals&&t.locals.set(n.indexVariable,a);const i=await r(t);if(!s(i)){const t=i.error;if("break"===t.type){c=!0;break}if("continue"===t.type){a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}return{iterations:a,lastResult:o,interrupted:c,signal:t}}o=i.value,a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:a,lastResult:o,interrupted:c}}(p,t,y,u??(async()=>i(void 0)));if(b.signal)return b.signal;if(0===b.iterations&&!b.interrupted&&f){const e=await f(t);if(!s(e))return e.error;const r=e.value;return Object.assign(t,{it:r}),{type:n,iterations:0,completed:!0,lastResult:r}}return Object.assign(t,{it:b.lastResult}),{type:n,iterations:b.iterations,completed:!b.interrupted,lastResult:b.lastResult,interrupted:b.interrupted}}};return Io(t,"RepeatCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),o=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=Ho({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" }',"repeat for item in items index i log i end"],sideEffects:["iteration","conditional-execution"],category:"control-flow",compatibility:"standard"}),Mo(t,r),o=t})();const Ba=Po(Pa);class Va{async parseInput(e,t,n){return{signalType:this.signalType}}async execute(e,t){return"exit"===this.signalType?{type:"exit",returnValue:void 0}:{type:this.signalType}}}let Fa=(()=>{let e,t,n=[qo({name:"break"})],r=[],i=Va;var o=t=class extends i{constructor(){super(...arguments),this.signalType="break"}get metadata(){return o.metadata}};return Io(t,"BreakCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const Da=Po(Fa);let Ua=(()=>{let e,t,n=[qo({name:"continue"})],r=[],i=Va;var o=t=class extends i{constructor(){super(...arguments),this.signalType="continue"}get metadata(){return o.metadata}};return Io(t,"ContinueCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const _a=Po(Ua),za=Po((()=>{let e,t,n=[qo({name:"halt"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(e.modifiers.the)return{target:n.event};const[r]=e.args;return r?{target:await t.evaluate(r,n)}:{}}async execute(e,t){let n=e.target;if(("the"===n&&t.event||"object"==typeof n&&null!==n&&"the"===n.target&&t.event)&&(n=t.event),this.isEvent(n)){const e=n;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}return"halted"in t&&(t.halted=!0),{type:"halt"}}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}};return Io(t,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Wa=Po((()=>{let e,t,n=[qo({name:"return"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return e.args&&0!==e.args.length?{value:await t.evaluate(e.args[0],n)}:{value:void 0}}async execute(e,t){const{value:n}=e;return"returnValue"in t&&(t.returnValue=n),Object.assign(t,{it:n}),{type:"return",returnValue:n}}};return Io(t,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());let Za=(()=>{let e,t,n=[qo({name:"exit"})],r=[],i=Va;var o=t=class extends i{constructor(){super(...arguments),this.signalType="exit"}get metadata(){return o.metadata}};return Io(t,"ExitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const Ja=Po(Za),Ka=Po((()=>{let e,t,n=[qo({name:"throw"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const[r]=e.args;if(!r)throw Error("throw command requires a message or error object");return{message:await t.evaluate(r,n)}}async execute(e,t){const{message:n}=e;let r;throw r=n instanceof Error?n:Error("string"==typeof n?n:n+""),r}};return Io(t,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Ga=Po((()=>{let e,t,n=[qo({name:"call"})],r=[];var i=t=class{get metadata(){return i.metadata}parseInput(e,t,n){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:n}=e,r=t.locals?.get("__evaluator"),i=r?await r.evaluate(n,t):await Ai(n,t);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(t,{it:o,result:o}),{result:o,wasAsync:a,expressionType:s}}};return Io(t,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());class Xa{constructor(){this.name="pseudo-command"}get metadata(){return Xa.metadata}async parseInput(e,t,n){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const r=e.args[0].properties||[];let i,o,s="",a=[];for(const e of r){const r=e.value;switch(e.key?.name||e.key?.value){case"methodName":s=r?.value||await t.evaluate(r,n)+"";break;case"methodArgs":"arrayLiteral"===r?.type&&r.elements?a=await Promise.all(r.elements.map(e=>t.evaluate(e,n))):"literal"===r?.type&&Array.isArray(r.value)&&(a=await Promise.all(r.value.map(e=>t.evaluate(e,n))));break;case"preposition":const e=r?.value;e&&"null"!==e&&(i=e);break;case"target":case"targetExpression":o=await t.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>e.args.length)throw Error("pseudo-command requires method name and target expression");const r=await t.evaluate(e.args[0],n)+"",i=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,n))):[];let o,s;const a=["from","on","with","into","at","to"];for(const r of a)if(e.modifiers?.[r]){s=r,o=await t.evaluate(e.modifiers[r],n);break}if(!o&&e.args[2]&&(o=await t.evaluate(e.args[2],n)),!o)throw Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:s,targetExpression:o}}async execute(e,t){const{methodName:n,methodArgs:r,targetExpression:i}=e;try{const e=await this.resolveTarget(i,t);if(null==e)throw Error("Target expression resolved to "+e);const o=this.resolveMethod(e,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,e,r);return t.locals.set("result",s),Object.assign(t,{it:s}),{result:s,methodName:n,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const n=e.split(".");let r="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(n[0])?(r=t.locals.get(n[0]),n.shift()):t.variables?.has(n[0])?(r=t.variables.get(n[0]),n.shift()):t.globals.has(n[0])&&(r=t.globals.get(n[0]),n.shift());for(const e of n){if(null==r)return null;r=r[e]}return r}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const n=t.split(".");let r=e;for(let e=0;n.length>e;e++){const t=n[e];if(null==r)return null;if(!(t in r))return null;if(r=r[t],e===n.length-1&&"function"==typeof r)return r}return null}async executeMethod(e,t,n){try{const r=e.apply(t,n);return r&&"object"==typeof r&&"then"in r?await r:r}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}Xa.metadata=Ho({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 Ya=Po((()=>{let e,t,n=[qo({name:"focus"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"focus",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"FocusCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Qa=Po((()=>{let e,t,n=[qo({name:"blur"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"blur",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"BlurCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function ec(e){return be(e)?e:e+""}class tc{constructor(e){this.position=e}concat(e,t){const n=null==e?"":e+"",r=t+"";return"append"===this.position?n+r:r+n}pushInto(e,t){return"append"===this.position?e.push(t):e.unshift(t),e}async parseInput(e,t,n){if(!e.args?.length)throw Error(this.name+" requires content");const r=await t.evaluate(e.args[0],n),i=e.modifiers?.to??e.target;if(!i)return{kind:"implicit",content:r};const o=await ga(i,t,n,{scopeElements:async()=>be(n.me)?[n.me]:[],selectorSource:!0,bareReference:!0});if(o)return function(e,t){switch(e.kind){case"selector":return{kind:"selector",selector:e.selector,content:t};case"attribute":return{kind:"attribute",elements:e.elements,name:e.name,content:t};case"property":return{kind:"property",property:e.target,content:t};case"variable":return{kind:"variable",name:e.name,scope:e.scope,content:t};default:throw Error(`unrequested write-target rung '${e.kind}'`)}}(o,r);const s=await t.evaluate(i,n),a=function(e){if(be(e))return[e];if(Array.isArray(e)&&e.length>0&&e.every(e=>be(e)))return e;if(e&&"object"==typeof e&&"number"==typeof e.length&&"function"==typeof e.item){const t=Array.from(e).filter(e=>be(e));return t.length?t:null}return null}(s);return a?{kind:"elements",elements:a,content:r}:{kind:"value",target:s,content:r}}async execute(e,t){switch(e.kind){case"selector":return this.done(t,this.insertIntoSelector(e.selector,e.content));case"elements":return this.done(t,this.insertIntoEach(e.elements,e.content));case"attribute":{for(const t of e.elements)t.setAttribute(e.name,this.concat(t.getAttribute(e.name),e.content));const n=e.elements[0]?.getAttribute(e.name)??this.concat(null,e.content);return Object.assign(t,{it:n}),{target:"@"+e.name,value:n,targetType:"attribute"}}case"property":{const n=Us(e.property),r=this.combineValue(n,e.content);return be(n)||_s(e.property,r),Object.assign(t,{it:r}),{target:e.property.element,value:r,targetType:"property"}}case"variable":return this.executeVariable(e,t);case"value":{const n=this.combineValue(e.target,e.content,!0);return Object.assign(t,{it:n}),{target:e.target,value:n,targetType:this.targetTypeOf(e.target)}}case"implicit":return this.execImplicit(t,e.content)}}insertIntoSelector(e,t){return this.insertIntoEach(Te(e),t)}insertIntoEach(e,t){const n=ec(t);for(const t of e)bs(t,n,this.position);return e}combineValue(e,t,n=!1){if(Array.isArray(e))return this.pushInto(e,t);if(e instanceof Set)return e.add(t),e;if(be(e))return bs(e,ec(t),this.position),e;if(n&&null!=e&&"string"!=typeof e&&"number"!=typeof e)throw Error(`Unable to ${this.name} a value!`);return this.concat(e,t)}targetTypeOf(e){return Array.isArray(e)?"array":e instanceof Set?"set":be(e)?"element":"result"}executeVariable(e,t){if("me"===e.name||"you"===e.name){const n="me"===e.name?t.me:t.you;if(be(n))return bs(n,ec(e.content),this.position),Object.assign(t,{it:n}),{target:n,value:n,targetType:"element"}}if("it"===e.name||"result"===e.name)return this.execImplicit(t,e.content);const n=Ee(e.name,t,e.scope),r=this.combineValue(n,e.content);return Array.isArray(n)||n instanceof Set||be(n)||xe(e.name,r,t,e.scope),Object.assign(t,{it:r}),{target:e.name,value:r,targetType:this.targetTypeOf(n)}}execImplicit(e,t){const n=e.it??e.result,r=this.combineValue(n,t);return Object.assign(e,{it:r,result:r}),{target:"result",value:r,targetType:this.targetTypeOf(n)}}done(e,t){const n=1===t.length?t[0]:t;return Object.assign(e,{it:n}),{target:n,value:n,targetType:"element"}}}const nc=Po((()=>{let e,t,n=[qo({name:"append"})],r=[],i=tc;var o=t=class extends i{get metadata(){return o.metadata}constructor(){super("append")}};return Io(t,"AppendCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})()),rc=Po((()=>{let e,t,n=[qo({name:"prepend"})],r=[],i=tc;var o=t=class extends i{get metadata(){return o.metadata}constructor(){super("prepend")}};return Io(t,"PrependCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})()),ic=Po((()=>{let e,t,n=[qo({name:"transition"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("transition requires property and value");let r,i;const o=await t.evaluate(e.args[0],n),s=e=>Array.isArray(e)||ve(e)?e[0]:e,a=s(o);if(be(a)||"string"==typeof o&&/^[#.]|^(?:me|it|you)$/.test(o))i=a,r=await t.evaluate(e.args[1],n)+"";else{if(e.args.length>=2)throw Error("transition: target element not found");if(null==o){const o=function(e){if(!e||"object"!=typeof e)return null;const t=e;if("identifier"===t.type&&"string"==typeof t.name&&t.name)return{property:t.name};if("propertyAccess"===t.type||"memberExpression"===t.type){const e=t.property,n="string"==typeof e?e:"string"==typeof e?.name?e.name:void 0;if(n)return{property:n,objectNode:t.object}}return null}(e.args[0]);if(!o)throw Error("transition requires a CSS property");if(r=o.property,void 0!==o.objectNode){const e=s(await t.evaluate(o.objectNode,n));be(e)&&(i=e)}}else r=o+""}if(!r||"undefined"===r||"null"===r)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let c=await t.evaluate(e.modifiers.to,n);void 0===c&&"identifier"===e.modifiers.to.type&&(c=e.modifiers.to.name);const l={property:r,value:c};return void 0!==i&&(l.target=i),e.modifiers?.over&&(l.duration=await t.evaluate(e.modifiers.over,n)),e.modifiers?.with&&(l.timingFunction=await t.evaluate(e.modifiers.with,n)+""),l}async execute(e,t){let{property:n}=e;const{target:r,value:i,duration:o,timingFunction:s}=e;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const a=Vo(r,t,"transition"),c=Ss(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 e=a.style.getPropertyValue(n);a.style.removeProperty(n),d=getComputedStyle(a).getPropertyValue(n),e&&a.style.setProperty(n,e),h=!0}a.style.setProperty(n,d);const m=await function(e,t,n){return new Promise(r=>{const i=n=>{n.target===e&&n.propertyName===t&&s({completed:!0,cancelled:!1})},o=n=>{n.target===e&&n.propertyName===t&&s({completed:!1,cancelled:!0})},s=fa(()=>{e.removeEventListener("transitionend",i),e.removeEventListener("transitioncancel",o),clearTimeout(a)},r);e.addEventListener("transitionend",i),e.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 Io(t,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),oc=Po((()=>{let e,t,n=[qo({name:"measure"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){let r,i,o;if(e.args?.length){const o=e.args[0];if("identifier"===o.type&&o.name){const s=o.name.toLowerCase();if("me"===s||"it"===s||"you"===s){const s=await t.evaluate(o,n);if(be(s)&&(r=s,e.args.length>1)){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else i=o.name}else{const s=await t.evaluate(o,n);if(be(s)||"string"==typeof s&&/^[#.]/.test(s)){if(r=s,e.args.length>1){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else"string"==typeof s&&(i=s)}}e.modifiers?.set&&(o=await t.evaluate(e.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(e,t){const n=Vo(e.target,t,"measure"),r=e.property||"width",i=this.getMeasurement(n,r);return e.variable&&t.locals&&t.locals.set(e.variable,i.value),Object.assign(t,{it:i.value}),{result:i.value,wasAsync:!1,element:n,property:r,value:i.value,unit:i.unit,stored:!!e.variable}}getMeasurement(e,t){const n=getComputedStyle(e);if(t.startsWith("*")){const e=n.getPropertyValue(t.substring(1)),r=parseFloat(e);if(!isNaN(r)){const t=e.match(/([a-zA-Z%]+)$/);return{value:r,unit:t?t[1]:""}}return{value:e,unit:""}}const r=t.toLowerCase(),i=e.getBoundingClientRect(),o={width:()=>i.width,height:()=>i.height,top:()=>i.top,left:()=>i.left,right:()=>i.right,bottom:()=>i.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(o[r])return{value:o[r](),unit:"px"};const s=n.getPropertyValue(t),a=parseFloat(s);if(!isNaN(a)){const e=s.match(/([a-zA-Z%]+)$/);return{value:a,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}};return Io(t,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),sc=Po((()=>{let e,t,n=[qo({name:"settle"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){let r,i;const[o]=e.args;if(o){const e=await t.evaluate(o,n);(be(e)||"string"==typeof e&&(e.startsWith("#")||e.startsWith(".")||"me"===e||"it"===e||"you"===e))&&(r=e)}e.modifiers?.for&&(i=await t.evaluate(e.modifiers.for,n));const s={};return void 0!==r&&(s.target=r),void 0!==i&&(s.timeout=i),s}async execute(e,t){const{target:n,timeout:r}=e,i=Vo(n,t,"settle"),o=Ss(r,5e3),s=Date.now(),a=getComputedStyle(i),c=As(a.transitionDuration),l=As(a.transitionDelay),u=As(a.animationDuration),f=As(a.animationDelay),d=Cs(c,l),h=Cs(u,f),m=Math.max(d,h);var p,y,b;return{element:i,settled:(await(p=i,y=m,b=o,y>0?new Promise(e=>{const t=e=>{e.target===p&&r({completed:!0,type:"transition"})},n=e=>{e.target===p&&r({completed:!0,type:"animation"})},r=fa(()=>{p.removeEventListener("transitionend",t),p.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(o)},e);p.addEventListener("transitionend",t),p.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},y+50),o=setTimeout(()=>{r({completed:!1,type:"timeout"})},b)}):Promise.resolve({completed:!0,type:"timeout"}))).completed,timeout:o,duration:Date.now()-s}}};return Io(t,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());const ac=Po((()=>{let e,t,n=[qo({name:"take"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error('take requires property, "from", and source');const{value:r}=await us(e.args[0],t,n),i=r+"",o=e.modifiers?.from?await t.evaluate(e.modifiers.from,n):void 0;let s;if(!s&&e.modifiers?.for&&(s=await t.evaluate(e.modifiers.for,n)),void 0===o&&!i.startsWith("."))throw Error('take requires property, "from", and source');return{property:i,source:o,target:s}}async execute(e,t){const n=e.property.trim();if(n.startsWith(".")){const r=n.substring(1);let i;if(null!=e.source)i=Fo(e.source,t);else{const e=t.me?.ownerDocument??("undefined"!=typeof document?document:null);i=e?Array.from(e.querySelectorAll("."+r)):[]}for(const e of i)e.classList.remove(r);const o=Fo(e.target,t);if(0===o.length)throw Error("take: no recipient element found");for(const e of o)e.classList.add(r);return{targetElement:o[0],property:e.property,value:r}}const r=Vo(this.firstOf(e.source),t,"take"),i=Vo(e.target?this.firstOf(e.target):void 0,t,"take"),o=this.takeProperty(r,e.property);return this.putProperty(i,e.property,o),{targetElement:i,property:e.property,value:o}}firstOf(e){const t=null!==e&&"object"==typeof e&&"number"==typeof e.length&&"function"==typeof e.item;if(Array.isArray(e)||t){const t=e[0];if(void 0===t)throw Error("take: no matching elements");return t}return e}takeProperty(e,t){const n=t.trim(),r=n.toLowerCase();if("class"===r||"classes"===r){const t=Array.from(e.classList);return e.className="",t}if(n.startsWith(".")){const t=n.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(n.startsWith("@")){const t=n.substring(1),r=e.getAttribute(t);return e.removeAttribute(t),r}if(n.startsWith("data-")){const t=e.getAttribute(n);return e.removeAttribute(n),t}if("id"===r){const t=e.id;return e.id="",t}if("title"===r){const t=e.title;return e.title="",t}if("value"===r&&"value"in e){const t=e.value;return e.value="",t}const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(n.includes("-")||i in e.style||n in e.style){let t;return i in e.style?(t=e.style[i],e.style[i]=""):n in e.style?(t=e.style[n],e.style[n]=""):(t=e.style.getPropertyValue(n),e.style.removeProperty(n)),t}const o=e.getAttribute(t);return null!==o?(e.removeAttribute(t),o):null}putProperty(e,t,n){if(null==n)return;const r=t.trim(),i=r.toLowerCase();if("class"===i||"classes"===i)return void(Array.isArray(n)?n.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof n&&(e.className=n));if(r.startsWith("."))return void(n&&e.classList.add(r.substring(1)));if(r.startsWith("@"))return void e.setAttribute(r.substring(1),n+"");if(r.startsWith("data-"))return void e.setAttribute(r,n+"");if("id"===i)return void(e.id=n+"");if("title"===i)return void(e.title=n+"");if("value"===i&&"value"in e)return void(e.value=n+"");const o=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());r.includes("-")||o in e.style||r in e.style?o in e.style?e.style[o]=n+"":r in e.style?e.style[r]=n+"":e.style.setProperty(r,n+""):e.setAttribute(t,n+"")}};return Io(t,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),cc=Po((()=>{let e,t,n=[qo({name:"js"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){let r,i;if(0===e.args.length)throw Error("js command requires JavaScript code");const o=e.args[0],s=e.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(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const a={code:r};return i&&i.length>0&&(a.parameters=i),a}async execute(e,t){const{code:n,parameters:r=[]}=e;if(!n.trim())return{result:void 0,executed:!1,codeLength:n.length,parameters:r,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,r),i=Function(...Object.keys(e),n),o=await i(...Object.values(e));return void 0!==o&&Object.assign(t,{it:o}),{result:o,executed:!0,codeLength:n.length,parameters:r,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,n)=>{let r=e.locals?.get(n);return void 0===r&&(r=e.variables?.get(n)),void 0===r&&(r=e[n]),t[n]=r,t},{})}}};return Io(t,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),lc=Po((()=>{let e,t,n=[qo({name:"log"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}};return Io(t,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),uc=Po((()=>{let e,t,n=[qo({name:"tell"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(2>e.args.length)throw Error("tell command requires a target and at least one command");const r=await t.evaluate(e.args[0],n),i=function(e){const t=[];for(let n=1;e.args.length>n;n++)t.push(La(e,n));return t}(e);return{target:r,commands:i}}async execute(e,t){const{target:n,commands:r}=e,i=Fo(n,t);if(0===i.length)throw Error("tell command found no target elements");const o=[];for(const e of i){const n={...t,me:e,you:e};for(const e of r){let t;try{t=await e(n)}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}if(!s(t))return t.error;const r=t.value;o.push(r),Object.assign(n,{it:r})}}return{targetElements:i,commandResults:o,executionCount:i.length*r.length}}};return Io(t,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),fc=Po((()=>{let e,t,n=[qo({name:"copy"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const[r]=e.args;if(!r)throw Error("copy command requires a source (text or element)");return{source:await t.evaluate(r,n),format:"text"}}async execute(e,t){const{source:n,format:r="text"}=e,i=this.extractText(n,r,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(i),this.dispatchCopyEvent(t,"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(t,"copy:success",{text:i,method:"execCommand"}),{success:!0,text:i,format:r,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:i,error:"All copy methods failed"}),{success:!1,text:i,format:r,method:"fallback"}}extractText(e,t,n){if("string"==typeof e)return e;if(be(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===n.me&&be(n.me)){const e=n.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,n){if(be(e.me)){const r=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!1});e.me.dispatchEvent(r)}}};return Io(t,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function dc(e,t,n,r){return e.evaluate(function(e,t){if(!e)throw Error(t+" is required");return e}(n,r),t)}const hc=Po((()=>{let e,t,n=[qo({name:"pick"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers?.variant,i=r?.value;if("first"===i||"last"===i){const r=await t.evaluate(e.args[0],n),o=await dc(t,n,e.modifiers.count,"pick: count");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 t.evaluate(e.args[0],n);if(!Array.isArray(r))throw Error("pick random: source must be an array");let i;if(e.modifiers.count){const r=await t.evaluate(e.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 t.evaluate(e.args[0],n);if(!Array.isArray(r)&&"string"!=typeof r)throw Error("pick items: source must be an array or string");const i=e.modifiers.rangeStart,o="start"===i?.value?"start":await dc(t,n,e.modifiers.rangeStart,"pick: start"),s="start"===o?"start":Number(o);let a;if(e.modifiers.rangeEnd)if("end"===e.modifiers.rangeEnd.value)a="end";else{const r=await t.evaluate(e.modifiers.rangeEnd,n);a=Number(r)}const c=e.modifiers.rangeMode;return{variant:"range",array:r,rangeStart:s,rangeEnd:a,rangeMode:c?.value??"default"}}if("match"===i||"matches"===i){const r=await t.evaluate(e.args[0],n);if("string"!=typeof r)throw Error(`pick ${i}: source must be a string, got ${typeof r}`);const o=await dc(t,n,e.modifiers.regex,"pick: regex"),s="string"==typeof o?o:o+"",a=e.modifiers.flags,c=a?.value;return{variant:i,source:r,regex:s,flags:c}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{variant:"random",items:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const n=e.variant??"random";if("first"===n){const n=e.array??[],r=n.slice(0,e.count??0);return Object.assign(t,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"array",variant:"first"}}if("last"===n){const n=e.array??[],r=e.count??0,i=r>0?n.slice(-r):[];return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:n.length,sourceType:"array",variant:"last"}}if("range"===n){const n=e.array??[];let r="start"===e.rangeStart?0:e.rangeStart??0,i=void 0===e.rangeEnd?r+1:"end"===e.rangeEnd?n.length:e.rangeEnd;"inclusive"===e.rangeMode?i++:"exclusive"===e.rangeMode&&r++;const o=n.slice(r,i);return Object.assign(t,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"array",variant:"range"}}if("match"===n){const n=e.source??"",r=RegExp(e.regex??"",e.flags).exec(n);return Object.assign(t,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"string",variant:"match"}}if("matches"===n){const n=e.source??"",r=e.flags??"g",i=RegExp(e.regex??"",r.includes("g")?r:"g"+r),o=Array.from(n.matchAll(i));return Object.assign(t,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"string",variant:"matches"}}const r=e.items??e.array??[];if(0===r.length)throw Error("Cannot pick from empty collection");if(void 0===e.count){const n=Math.floor(Math.random()*r.length),i=r[n];return Object.assign(t,{it:i}),{selectedItem:i,selectedIndex:n,sourceLength:r.length,sourceType:e.items?"items":"array",variant:"random"}}const i=r.slice(),o=[];for(let t=0;e.count>t&&i.length>0;t++){const e=Math.floor(Math.random()*i.length);o.push(i.splice(e,1)[0])}return Object.assign(t,{it:o}),{selectedItem:o,sourceLength:r.length,sourceType:e.items?"items":"array",variant:"random"}}};return Io(t,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());const mc=Po((()=>{let e,t,n=[qo({name:"beep"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return 0===e.args.length?{expressions:[]}:{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const n=e.expressions||[];if(0===n.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const r=[];console.group("\ud83d\udd14 beep! Debug Output");for(const e of n){const t=this.debugExpression(e);r.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:n.length,debugged:!0,outputs:r}}debugContext(e){console.group("\ud83d\udd14 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":be(e)?"HTMLElement":e instanceof Element?"Element":e instanceof Node?"Node":e instanceof Error?"Error":e instanceof Date?"Date":e instanceof RegExp?"RegExp":typeof e}getRepresentation(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Array.isArray(e))return`Array(${e.length}) [${e.slice(0,3).map(e=>this.getRepresentation(e)).join(", ")}${e.length>3?"...":""}]`;if(be(e)){const t=e;return`<${t.tagName.toLowerCase()}${t.id?"#"+t.id:""}${t.className?"."+t.className.split(" ").join("."):""}/>`}if(e instanceof Error)return"Error: "+e.message;if("string"==typeof e)return e.length>50?`"${e.substring(0,47)}..."`:`"${e}"`;if("object"==typeof e)try{const t=Object.keys(e);return`Object {${t.slice(0,3).join(", ")}${t.length>3?"...":""}}`}catch{return"[Object]"}return e+""}};return Io(t,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),pc=Po((()=>{let e,t,n=[qo({name:"breakpoint"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}};return Io(t,"BreakpointCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),Mo(t,r),i=t})());class yc{constructor(){this.name="install"}get metadata(){return yc.metadata}async parseInput(e,t,n){if(1>e.args.length)throw Error("install command requires a behavior name");const r=e.args[0];let i,o;if(i="identifier"===r?.type&&"string"==typeof r.name?r.name:await t.evaluate(r,n)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(i))throw Error(`Behavior name must be PascalCase (start with uppercase): "${i}"`);const s=e.args[1];if(s){const e=await t.evaluate(s,n);if(e&&"object"==typeof e&&!Array.isArray(e)){o=e;for(const e of Object.keys(o))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}let a;return e.modifiers?.on&&(a=await t.evaluate(e.modifiers.on,n)),{behaviorName:i,parameters:o,target:a}}async execute(e,t){const{behaviorName:n,parameters:r={},target:i}=e;try{const e=this.resolveTarget(i,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(n,t))throw Error(`Behavior "${n}" is not defined. Define it using the 'behavior' keyword before installing.`);const o=[];for(const i of e){const e=await this.installBehavior(n,i,r,t);o.push(e)}return{success:!0,behaviorName:n,installedCount:o.length,instances:o}}catch(e){throw Error(`Failed to install behavior "${n}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(be(e))return[e];throw Error('No target specified and "me" is not available in context')}if(be(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>be(e));if(0===t.length)throw Error("Target array contains no valid HTMLElements");return t}if("string"==typeof e){if("me"===e){const e=t.me||t.locals.get("me");if(be(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),n=Array.from(t).filter(e=>be(e));if(0===n.length)throw Error(`No elements found matching selector: "${e}"`);return n}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>be(e));if(0===t.length)throw Error("Target collection contains no valid HTMLElements");return t}if("object"==typeof e&&"element"in e){const t=e.element;if(be(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+e)}behaviorExists(e,t){const n=t.locals.get("_behaviors");if(n&&"object"==typeof n){const t=n;if(t.has(e))return!0;if(t.resolve&&t.resolve(e))return!0}if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors){if(t.behaviors.has(e))return!0;if(t.behaviors.resolve&&t.behaviors.resolve(e))return!0}}return!1}async installBehavior(e,t,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(e,t,n)}if("undefined"!=typeof globalThis){const r=globalThis._hyperscript;if(r?.behaviors?.install)return await r.behaviors.install(e,t,n)}throw Error("Behavior system not available in context")}}yc.metadata=Ho({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 bc{constructor(){this.name="render"}get metadata(){return bc.metadata}async parseInput(e,t,n){if(1>e.args.length)throw Error("render command requires a template");const r=await t.evaluate(e.args[0],n);let i;if(!i&&e.modifiers?.with){const r=await t.evaluate(e.modifiers.with,n);r&&"object"==typeof r&&(i=r)}return{template:r,variables:i}}async execute(e,t){const{template:n,variables:r={}}=e,i=this.extractTemplateContent(n,t),o=this.createTemplateContext(t,r),s=[],a=await this.processTemplate(i,o,s),c=this.createDOMElement(a);return Object.assign(t,{it:c}),{element:c,rendered:a,directivesProcessed:s}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let n=e;if(!n.includes("<")&&!n.includes("$")){const e=this.resolveVariable(n,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(n=e)}const r=n.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return r?r[1]:n}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,n){const r=e.split("\n"),i=[];let o=0;for(;r.length>o;){const e=r[o].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:s}=await this.processRepeatDirective(r,o,t);i.push(s),o=e,n.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:s}=await this.processIfDirective(r,o,t,n);i.push(s),o=e,n.push("@if")}else if("@else"===e||"@end"===e)o++;else{const n=this.processVariableInterpolation(e,t);i.push(n),o++}}return i.join("\n")}async processRepeatDirective(e,t,n){const r=e[t].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(e,t+1),c=[];if(Array.isArray(o))for(const e of o){const t={...n,locals:new Map([...n.locals.entries(),["it",e]])},r=await this.processTemplate(a.join("\n"),t,[]);c.push(r)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(e,t,n,r){const i=e[t].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(e,t+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(e,t){const n=[];let r=1,i=t;for(;e.length>i&&r>0;){const t=e[i].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(r++,n.push(e[i])):"@end"===t?(r--,r>0&&n.push(e[i])):n.push(e[i]),i++}return{endIndex:i-1,blockContent:n}}extractIfElseBlock(e,t){const n=[],r=[];let i=1,o=t,s=!1;for(;e.length>o&&i>0;){const t=e[o].trim();if(t.startsWith("@if "))i++;else{if("@else"===t&&1===i){s=!0,o++;continue}if("@end"===t&&(i--,0===i))break}s?r.push(e[o]):n.push(e[o]),o++}return{endIndex:o,blockContent:n,elseContent:r}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=n.trim();if(e.startsWith("unescaped ")){const n=e.substring(10).trim();return(this.evaluateExpression(n,t)||"")+""}const r=this.evaluateExpression(e,t);return this.escapeHtml((r||"")+"")}catch(t){return In(`render: template interpolation error for ${n}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const n=Number(e);if(!isNaN(n)&&""!==e.trim())return n;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++){if("object"!=typeof r||null===r)return;r=r[n[e]]}return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it??t.result:"you"===e?t.you:"result"===e?t.result??t.it:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}function gc(){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>')}bc.metadata=Ho({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 vc=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],wc=function(e,t){const n=new ro(null);for(const t of e)n.register(t);return new fo({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0})}([Zo(),Ko(),hs(),xs(),Zs(),Js(),Ys(),Qs(),na(),ia(),sa(),ca(),da(),ya(),va(),wa(),ka(),Sa(),Ta(),Ca(),Oa(),Na(),Ra(),qa(),Ba(),Da(),_a(),za(),Wa(),Ja(),Ha(),Ka(),Ga(),new Xa,Ya(),Qa(),nc(),rc(),ic(),oc(),sc(),ac(),cc(),lc(),uc(),fc(),hc(),mc(),pc(),new yc,new bc],{expressionRegistry:No()}),Ec={async execute(e,t,n){const r=gc(),i=r.parseSemantic(e,t);if(.5>i.confidence||!i.node)throw Error(`Failed to parse "${e}" in language "${t}" (confidence: ${i.confidence.toFixed(2)})`);const o=r.buildAST(i.node),s=ye(n);return wc.execute(o.ast,s)},parse(e,t){const n=gc(),r=n.parseSemantic(e,t);return.5>r.confidence||!r.node?null:n.buildAST(r.node).ast},translate:(e,t,n)=>gc().translate(e,t,n),getAllTranslations:(e,t)=>gc().getAllTranslations(e,t),createContext:pe,runtime:wc,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","log","tell","copy","pick","beep","install","render"],supportedLanguages:vc,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await Tc():e instanceof HTMLElement&&await Sc(e)},process:async e=>Ec.processNode(e)},xc=new WeakSet;let kc=null;async function Sc(e){if(xc.has(e))return;const t=e.getAttribute("_");if(t)try{const n=function(e){const t=e.getAttribute("data-lang");if(t&&vc.includes(t))return t;let n=e;for(;n;){const e=n.getAttribute("lang");if(e){const t=e.split("-")[0].toLowerCase();if(vc.includes(t))return t}n=n.parentElement}return"en"}(e);Hn(`ATTR-ML: Processing element with lang="${n}":`,t.substring(0,60));const r=gc(),i=r.parseSemantic(t,n);if(.5>i.confidence||!i.node)return void Hn(`ATTR-ML: Low confidence (${i.confidence.toFixed(2)}) for: ${t}`);const o=r.buildAST(i.node),s=ye(e);await wc.execute(o.ast,s),xc.add(e),Hn("ATTR-ML: Successfully processed element")}catch(e){Hn("ATTR-ML: Error processing element:",e.message)}}async function Tc(){const e=document.querySelectorAll("[_]");Hn(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(Sc(e))}),await Promise.all(t),Hn("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:e.length}}))}function Ac(){"undefined"!=typeof MutationObserver&&(kc=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&Sc(t).catch(e=>{Hn("ATTR-ML: Error processing dynamic element:",e)});const n=t.querySelectorAll?.("[_]");n?.forEach(e=>{e instanceof HTMLElement&&Sc(e).catch(e=>{Hn("ATTR-ML: Error processing dynamic descendant:",e)})})})}),kc.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=Ec,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(()=>Ac())}):Tc().then(()=>Ac())),e.default=Ec,e.hyperfixi=Ec,Object.defineProperty(e,"l",{value:!0}),e}({});
1
+ var _hyperfixiMultilingualInternal=function(e){"use strict";function t(e){return e}function n(e){return e}class r{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const n of this.afterExecuteHooks)await n(e,t)}async runOnError(e,t){let n=t;for(const t of this.onErrorHooks){const r=await t(e,n);r instanceof Error&&(n=r)}return n}shouldIntercept(e,t){for(const n of this.interceptCommandHooks)if(n(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function i(e){return{ok:!0,value:e}}function o(e){return{ok:!1,error:e}}function s(e){return!0===e.ok}const a="then",c="else",l="end",u="and",f="for",d="while",h="until",m="forever",p="times",y="index",b="in",g="to",v="from",w="with",E="of",x="on",k="event",S="behavior",T="global",A="the",C="start",$=new Set(["add","append","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"]),j=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),O="at end of",N=["into","before","after","at",j,O,"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=e=>$.has(e.toLowerCase()),M=e=>R.has(e.toLowerCase()),I=e=>q.has(e.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"]),P=new Set(["and","or","not","no"]),B=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","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]),D=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),U=new Set([")","]","}",","]);function _(e,t){return{infix:{bp:[e,e+1],handler:t??((t,n,r)=>{const i=r.parseExpr(e+1);return{type:"binaryExpression",operator:n.value,left:t,right:i,start:t.start,end:i.end??n.end,line:t.line??n.line,column:t.column??n.column}})}}}function z(e,t){return{infix:{bp:[e+1,e],handler:(t,n,r)=>{const i=r.parseExpr(e);return{type:"binaryExpression",operator:n.value,left:t,right:i,start:t.start,end:i.end??n.end,line:t.line??n.line,column:t.column??n.column}}}}}function W(e,t){return{prefix:{bp:e,handler:t??((t,n)=>{const r=n.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:r,argument:r,prefix:!0,start:t.start,end:r.end??t.end,line:t.line,column:t.column}})}}}function Z(e){return(t,n,r)=>{const i=r.advance();if(!i||!i.value)throw Error(`Type check requires a type name after 'is ${e?"not ":""}a/an', got: <end>`);let o=!0;const s=r.peek();return s&&"!"===s.value&&(r.advance(),o=!1),{type:"typeCheckExpression",value:t,typeName:i.value,nullOk:o,negated:e,start:t.start,end:i.end}}}const J=function(...e){const t=new Map;for(const n of e)for(const[e,r]of n){const n=t.get(e);t.set(e,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return t}(new Map([["or",_(10)],["||",_(10)],["and",_(20)],["&&",_(20)],["==",_(30)],["!=",_(30)],["<",_(30)],[">",_(30)],["<=",_(30)],[">=",_(30)],["is",_(30)],["matches",_(30)],["contains",_(30)],["starts with",_(30)],["ends with",_(30)],["does not start with",_(30)],["does not end with",_(30)],["is between",_(30,(e,t,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:e,min:r,max:o,negated:!1,start:e.start,end:o.end}})],["is not between",_(30,(e,t,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:e,min:r,max:o,negated:!0,start:e.start,end:o.end}})],["am between",_(30,(e,t,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:e,min:r,max:o,negated:!1,start:e.start,end:o.end}})],["am not between",_(30,(e,t,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:e,min:r,max:o,negated:!0,start:e.start,end:o.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:r,start:e.start,end:r.end}})],["sorted by",_(28,(e,t,n)=>{const r=n.parseExpr(29);let i="asc";const o=n.peek();if(o&&"string"==typeof o.value){const e=o.value.toLowerCase();"asc"===e||"ascending"===e?(n.advance(),i="asc"):"desc"!==e&&"descending"!==e||(n.advance(),i="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:r,order:i,start:e.start,end:r.end}})],["mapped to",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:r,start:e.start,end:r.end}})],["split by",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:r,start:e.start,end:r.end}})],["joined by",_(28,(e,t,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:r,start:e.start,end:r.end}})],["+",{..._(40),...W(80)}],["-",{..._(40),...W(80)}],["*",_(50)],["/",_(50)],["%",_(50)],["mod",_(50)],["^",z(60)],["**",z(60)],["as",_(70,(e,t,n)=>{const r=()=>{const e=n.peek();!e||"a"!==e.value&&"an"!==e.value||n.advance();const t=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&t&&"identifier"===t.type){n.advance();const e=n.advance();if(e&&void 0!==e.value)return{...t,name:`${t.name+""}:${e.value}`,end:e.end}}return t};let i=r(),o={type:"asExpression",expression:e,targetType:i,start:e.start,end:i.end??t.end,line:e.line??t.line,column:e.column??t.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const e=r();o={type:"asExpression",expression:o,targetType:e,start:o.start,end:e.end??o.end,line:o.line,column:o.column}}return o})],["not",W(80)],["!",W(80)],["no",W(27)]]),new Map([["===",_(30)],["!==",_(30)],["is not",_(30)],["am",_(30)],["is in",_(30)],["is not in",_(30)],["precedes",_(30)],["does not precede",_(30)],["follows",_(30)],["does not follow",_(30)],["is a",_(30,Z(!1))],["is an",_(30,Z(!1))],["is not a",_(30,Z(!0))],["is not an",_(30,Z(!0))],["has",_(30)],["have",_(30)],["match",_(30)],["include",_(30)],["includes",_(30)],["equals",_(30)],["does not contain",_(30)],["does not include",_(30)],["am in",_(30)],["am not in",_(30)],["is really",_(30)],["is not really",_(30)],["is equal",_(30)],["is not equal",_(30)],["contain",_(30)],["do not contain",_(30)],["does not contains",_(30)],["do not match",_(30)],["does not match",_(30)],["is equal to",_(30)],["is not equal to",_(30)],["is really equal to",_(30)],["is not really equal to",_(30)],["really equals",_(30)],["is greater than",_(30)],["is less than",_(30)],["is greater than or equal to",_(30)],["is less than or equal to",_(30)],["in",_(30)],["of",z(30)],["really",_(30)],["exists",{prefix:{bp:80,handler:(e,t)=>({type:"unaryExpression",operator:e.value,operand:t.parseExpr(80),start:e.start})},infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["does not exist",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is not empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["some",W(80)]]),new Map([["=",z(5)]])),K=new Set,G=new Set,X=new Set,Y=new Set;function Q(e,t){void 0!==console&&console.error(`[hyperfixi] ${e} threw:`,t)}function ee(e,t){if(0!==G.size)for(const n of G)try{n(e,t)}catch(e){Q("globalReadHook",e)}}function te(e,t,n){if(0!==X.size)for(const r of X)try{r(e,t,n)}catch(e){Q("localWriteHook",e)}}function ne(e,t){if(0!==Y.size)for(const n of Y)try{n(e,t)}catch(e){Q("localReadHook",e)}}function re(e,t,n){if(e.globals.set(t,n),0!==K.size)for(const r of K)try{r(t,n,e)}catch(e){Q("globalWriteHook",e)}}const ie=new Map,oe=new Map,se=new Map;function ae(e){return ie.get(e.toLowerCase())}function ce(e){return se.get(e)}const le=new Map,ue=new WeakMap;function fe(e){let t=ue.get(e);return t||(t=new Map,ue.set(e,t)),t}function de(e){return e.owner||(e.me instanceof Element?e.me:null)}function he(e,t){const n=de(e);if(n)return ne(t,e),fe(n).get(t)}function me(e,t,n){const r=de(e);r&&(fe(r).set(t,n),te(t,n,e))}function pe(e,t){return{me:e??null,owner:e??null,it:null,you:null,result:null,locals:new Map,globals:t||le}}function ye(e){if(!e)return pe();if(e.locals instanceof Map&&e.globals instanceof Map)return e;const t=pe(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}function be(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function ge(e){if(null===e||"object"!=typeof e)return!1;const t=e.nodeType;return 1===t||3===t||11===t}function ve(e){return null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(Symbol.iterator in e||"function"==typeof e.item)}function we(e){if(null==e)return 0;if("number"==typeof e)return isFinite(e)?e:0;if("string"==typeof e)return parseFloat(e);if("boolean"==typeof e)return e?1:0;if(Array.isArray(e))return e.length;if("object"==typeof e){if("length"in e&&"number"==typeof e.length)return e.length;if("function"==typeof e.valueOf){const t=e.valueOf();if("number"==typeof t)return t}return NaN}return 0}function Ee(e,t,n){return"element"===n?he(t,e):"global"===n&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==n&&t.locals&&t.locals.has(e)?(ne(e,t),t.locals.get(e)):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===n&&t.locals&&t.locals.has(e)?(ne(e,t),t.locals.get(e)):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function xe(e,t,n,r){if("element"!==r){if("global"===r)return re(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))return void re(n,e.slice(1),t);if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void te(e,t,n);if(n.globals&&n.globals.has(e))return re(n,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(n.variables&&n.variables.has(e))n.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void re(n,e,t);n.locals.set(e,t),te(e,t,n)}}else me(n,e,t)}function ke(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Ee(e,t)}function Se(e,t,n){return n||"string"!=typeof t||!t.startsWith("#")?e:Array.isArray(e)?e[0]??null:e}function Te(e){if("undefined"==typeof document)throw Error("DOM not available");const t=Array.from(document.querySelectorAll(e)).filter(e=>be(e));if(!t.length)throw Error(`No elements: "${e}"`);return t}function Ae(e){if(be(e))return[e];if(Array.isArray(e)){const t=e.filter(be);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(be);return t.length>0?t:null}return null}const Ce=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,n]of this.types)if(n.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),n=this.types.get(t);return n?.hyperscriptType??"unknown"}coerce(e,t,n){const r=this.types.get(t);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(r.isType(e))return e;if(this.config.cacheCoercions){const n=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(e),o=r.coerceFrom?.[i];if(o){const r=o(e,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(e,t){const n=this.types.get(t);if(!n)return!1;if(n.isType(e))return!0;const r=this.inferType(e);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(e,t){const n=this.types.get(t);return n&&(e===t||n.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const n=e;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,n)=>{t[n+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function $e(e){const t=Ce.get("String");return t?t.isType(e):"string"==typeof e}function je(e){const t=Ce.get("Number");return t?t.isType(e):"number"==typeof e}function Oe(e){const t=Ce.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Ne(e){const t=Ce.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Re(e){const t=Ce.get("Function");return t?t.isType(e):"function"==typeof e}function Le(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function Me(e){return e instanceof Element}function Ie(e){return e instanceof HTMLElement}const qe=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function He(e,t){return qe.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const Pe={id:e=>e.id,classname:e=>e.className,class:e=>e.className,tagname:e=>e.tagName.toLowerCase(),innertext:e=>e.textContent?.trim(),innerHTML:e=>e.innerHTML,outerhtml:e=>e.outerHTML,value:e=>function(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}(e)?e.value:void 0,checked:e=>function(e){return null!==e&&"object"==typeof e&&"tagName"in e&&"INPUT"===e.tagName}(e)?e.checked:void 0,disabled:e=>"disabled"in e?e.disabled:void 0,selected:e=>function(e){return null!=e&&"object"==typeof e&&"tagName"in e&&"OPTION"===e.tagName}(e)?e.selected:void 0,tabindex:e=>Le(e)?e.tabIndex:void 0,hidden:e=>Le(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling,next:e=>e.nextElementSibling,previous:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e.getAttribute("name");n&&"value"in e&&t.append(n,e.value)}),t}(e)};function Be(e,t){if(t.startsWith("*"))return function(e,t){if(!Ie(e))return;if(t.startsWith("computed-"))return getComputedStyle(e).getPropertyValue(t.slice(9))||"";const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}(e,t.slice(1));if(t.startsWith("computed-")){const n=t.slice(9);return Ie(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return He(e,t.slice(1));const n=Pe[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return He(e,t);const r=e[t];return Re(r)?r.bind(e):r}const Ve={1:"one",2:"two",3:"three",4:"four",5:"five"};function Fe(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${i=t,Ve[i]??i+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var i;return null}function De(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function Ue(e,t,n){return Fe(e,1,t,n)??De(e,0,t,n)}function _e(e,t){return Fe(e,2,t,"left, right")}function ze(){return null}function We(e,t,n,r){return e.length>t?`${n} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${r?` (${r})`:""}`:null}function Ze(e,t,n,r,i){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${i?` (${i})`:""}`:null}const Je={conversions:{dynamicResolvers:[]}},Ke={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":$e(e)?e:Ne(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Oe(e))return e;if(null==e)return!1;if($e(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return je(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(je(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(je(e))return e;if(null==e)return 0;const t=(e+"").trim();if(!t)return 0;try{return function(e){if(e=e.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(e))throw Error("Invalid characters in math expression");try{const t=Function(`"use strict"; return (${e})`)();if(!je(t)||!isFinite(t))throw Error("Expression did not evaluate to a finite number");return t}catch(e){throw Error("Math expression evaluation failed: "+(e instanceof Error?e.message:e+""))}}(t)}catch(e){return console.warn("Math conversion failed:",e),0}},Int:e=>{const t=Ke.Number(e);return Math.trunc(t)},Float:e=>{const t=Ke.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if($e(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return new Date(t,n-1,r)}return new Date(e)},JSON:e=>{if(!$e(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(Ne(e))return e;if($e(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{const t=document.createDocumentFragment(),n=Array.isArray(e)||e instanceof NodeList?Array.from(e):[e];for(const e of n)if(e instanceof Node)t.append(e);else{const n=document.createElement("template");n.innerHTML=null==e?"":e+"",t.append(n.content)}return t},HTML:e=>$e(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:Ke.String(e)).join(""):e instanceof Element?e.outerHTML:Ke.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=Ge(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=Ge(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?Ke.Values(e,t):e;if(!Ne(n))return"";const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return""+r},Set:e=>new Set(e),Map:e=>new Map(Object.entries(e??{})),Keys:e=>e instanceof Map?Array.from(e.keys()):Object.keys(e??{}),Entries:e=>e instanceof Map?Array.from(e.entries()):Object.entries(e??{}),Reversed:e=>Array.from(e).reverse(),Unique:e=>[...new Set(e)],Flat:e=>Array.from(e).flat(),"Values:Form":(e,t)=>{const n=Ke.Values(e,t);return Ke.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=Ke.Values(e,t);return JSON.stringify(n)}};function Ge(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}const Xe={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 Ye(e,t,n){if("string"!=typeof t)throw Error("Conversion type must be a string");if(t.startsWith("Fixed")){const{precision:n}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):0}:{}}(t);return Ke.Number(e).toFixed(n??0)}if(null==e)return e;let r=Ke[t];if(r)return r(e,n);const i=Xe[t.toLowerCase()];if(i&&(r=Ke[i],r))return r(e,n);const o=Je.conversions[t];if("function"==typeof o)return o(e,n);for(const n of Je.conversions.dynamicResolvers){const r=n(t,e);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+t),e}const Qe={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;return Ye(n,r,e)},validate:e=>Fe(e,2,"as","value, type")??De(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[n,r]=t;if(!$e(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 $e(n);case"number":return je(n)&&!isNaN(n);case"boolean":return Oe(n);case"object":return Ne(n);case"array":return Array.isArray(n);case"function":return Re(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||Ne(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>Fe(e,2,"is","value, type")??De(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Fe(e,1,"async","expression")}};function et(e,t){if(t.startsWith("computed-")){const n=t.substring(9);return getComputedStyle(e).getPropertyValue(n)||""}const n=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[n]}const tt={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:ze},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:ze},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it??e.result,validate:ze},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it??e.result,validate:ze},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result??e.it,validate:ze},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:e=>Ue(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:e=>Ue(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:e=>Ue(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:e=>Ue(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let n=t[0];if(n&&"object"==typeof n&&"type"in n){const e=n;"identifier"===e.type&&e.name?n=e.name:"literal"===e.type&&"string"==typeof e.value&&(n=e.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return e.me?e.me.closest(n):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:ze},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:ze},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:ze},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const n=t[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const i=r.querySelectorAll(n);return Array.from(i)},validate:e=>Ue(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const i=r||e.me;if(i&&i instanceof HTMLElement)return et(i,n)},validate:e=>Ze(e,1,2,"styleRef","property, optional element")??De(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&e.me?i=e.me instanceof HTMLElement?e.me:null:"its"===n&&e.it&&(i=e.it instanceof HTMLElement?e.it:null),i)return et(i,r)},validate:e=>Fe(e,2,"possessiveStyleRef","possessor, property")??De(e,0,"possessiveStyleRef","possessor")??De(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const n=t[0],r=t[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&e.me?i=e.me instanceof HTMLElement?e.me:null:"it"===r&&e.it&&(i=e.it instanceof HTMLElement?e.it:null),i)return et(i,n)},validate:e=>Fe(e,2,"ofStyleRef","property, reference")??De(e,0,"ofStyleRef","property")??De(e,1,"ofStyleRef","reference")}};function nt(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const rt="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 it;function ot(){return it({validate:e=>({success:!0,data:e})})}function st(e,t){if(rt)return ot();const n=it({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:nt("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(t?.strict){const t=Object.keys(e),n=Object.keys(r).filter(e=>!t.includes(e));if(n.length>0)return{success:!1,error:nt("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[t,n]of Object.entries(e)){const e=r[t];if(!(t in r)&&!n.t)return{success:!1,error:nt("missing-argument",`Required field "${t}" is missing`,t)};const o=n.validate(e);if(!o.success)return{success:!1,error:nt("validation-error",o.error.message||`Field "${t}" validation failed`,o.error.path?`${t}.${o.error.path}`:t)};void 0!==o.data&&(i[t]=o.data)}return{success:!0,data:i}}});return n.strict=()=>st(e,{strict:!0}),n}it=function(e){return e.describe||(e.describe=function(e){return this.description=e,this}),e.safeParse||(e.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),e.parse||(e.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),e.optional||(e.optional=function(){const e=this.validate.bind(this),t={...this,t:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return it(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&e>r.data.length?{success:!1,error:nt("runtime-error",`String must be at least ${e} characters long`)}:r}};return it(n)}),e.max||(e.max=function(e){const t=this.validate.bind(this),n={...this,validate:n=>{const r=t(n);return r.success&&"string"==typeof r.data&&r.data.length>e?{success:!1,error:nt("runtime-error",`String must be at most ${e} characters long`)}:r}};return it(n)}),e.default||(e.default=function(e){const t=this.validate.bind(this),n={...this,i:e,o:!0,validate:n=>void 0===n?{success:!0,data:e}:t(n)};return it(n)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?e(i.data)?i:{success:!1,error:nt("runtime-error",t||"Refinement validation failed")}:i}};return it(r)}),new Proxy(e,{get:(e,t,n)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,n):function(...e){return n}})};const at=e=>function(e={}){return rt?ot():it({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:nt("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:nt("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:nt("runtime-error",`String must be at most ${e.maxLength} characters long`)}:e.pattern&&!e.pattern.test(t)?e.pattern.source.startsWith("^")&&e.pattern.source.endsWith("$")?{success:!1,error:nt("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:nt("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),ct=e=>st(e),lt=e=>function(e){return rt?ot():it({validate:t=>{if(!Array.isArray(t))return{success:!1,error:nt("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:nt("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const n=[];for(let r=0;e.length>r;r++){const i=e[r].validate(t[r]);if(!i.success)return{success:!1,error:nt("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(e),ut=()=>ot();class ft{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(this.ttl>=Date.now()-t.timestamp)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU(),this.cache.set(e,{result:t,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[n,r]of this.accessOrder)t>r&&(t=r,e=n);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,n)=>e+(t-n.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const dt=new class{constructor(){this.domQueryCache=new ft(200,3e3),this.exprResultCache=new ft(500,2e3),this.cssMatchCache=new ft(100,5e3),this.formValueCache=new ft(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(e);return this.domQueryCache.set(t,r),r}querySelectorAll(e){const t="querySelectorAll:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,r),r}getElementById(e){const t="getElementById:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(e);return this.domQueryCache.set(t,r),r}getElementsByClassName(e){const t="getElementsByClassName:"+e,n=this.domQueryCache.get(t);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,r),r}matches(e,t){const n=`matches:${this.getElementCacheKey(e)}:${t}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=e.matches(t);return this.cssMatchCache.set(n,i),i}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),n=this.formValueCache.get("formValue:"+t);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(e,t){const n=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+n,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(e.cache.keys()))"string"==typeof n&&n.includes(t)&&e.delete(n)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),n=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${n}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([n,r])=>{e-r.timestamp>t.ttl&&t.delete(n)})})}};var ht;"undefined"!=typeof window&&setInterval(()=>{dt.cleanup()},1e4),function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(ht||(ht={}));const mt=new Set(["+","-","*","/","mod"]),pt=new Set(["ms","s","seconds","minutes","hours","days"]);function yt(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function bt(e){const t=e.input[e.position];return e.position++,"\n"===t?(e.line++,e.column=1):"\r"===t?("\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1):e.column++,t}function gt(e){const t=e.input,n=t.length;for(;n>e.position;){const n=t[e.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;bt(e)}}function vt(e,t,n,r,i){const o=r??e.position-n.length,s=e.position;let a=e.column-n.length;void 0!==r&&(a=wt(e.input,r).column);const c={kind:t,value:n,start:o,end:s,line:Et(e,o),column:a};e.tokens.push(c)}function wt(e,t){let n=1,r=-1;const i=Math.min(t,e.length);for(let t=0;i>t;t++){const i=e[t];"\n"===i?(n++,r=t):"\r"===i&&(n++,e.length>t+1&&"\n"===e[t+1]&&t++,r=t)}return{line:n,column:t-r}}function Et(e,t){return wt(e.input,t).line}function xt(e){const t=e.position;let n="";for(bt(e),bt(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=bt(e);vt(e,ht.COMMENT,"--"+n,t)}function kt(e){const t=e.position,n=bt(e);let r=n;for(;e.input.length>e.position;){const t=bt(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=bt(e))}vt(e,ht.STRING,r,t)}function St(e){const t=e.position;bt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){bt(e);break}if("\\"===t){if(bt(e),e.input.length>e.position){const t=bt(e);switch(t){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=t}}}else n+=bt(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);vt(e,ht.TEMPLATE,n,t)}function Tt(e){const t=e.position;let n=bt(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=bt(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=bt(e),"}"===t)break}vt(e,ht.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)bt(e),e.input.length>e.position&&(n+=bt(e));else{if(!Lt(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=bt(e)}}vt(e,ht.SELECTOR,n,t)}}function At(e){const t=e.position;if(Mt(e))return void function(e,t){const n=e.input;let r="",i=0,o="";for(;n.length>e.position;){const t=n[e.position];if(o)r+=bt(e),t===o&&(o="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===n[e.position+1]){for(;n.length>e.position&&">"!==n[e.position];)r+=bt(e);if(n.length>e.position&&(r+=bt(e)),i--,0>=i)break;continue}let t=!1,o="";for(;n.length>e.position;){const i=n[e.position];if(o)r+=bt(e),i===o&&(o="");else if('"'!==i&&"'"!==i){if(">"===i){t="/"===n[e.position-1],r+=bt(e);break}r+=bt(e)}else o=i,r+=bt(e)}if(t||i++,0>=i)break;continue}r+=bt(e)}else o=t,r+=bt(e)}vt(e,ht.SELECTOR,r,t)}(e,t);let n="";for(n+=bt(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=bt(e),"/"===t&&">"===r){n+=bt(e);break}}vt(e,ht.SELECTOR,n,t)}function Ct(e){const t=e.position;let n=bt(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!Lt(t)&&"_"!==t&&"-"!==t)break;n+=bt(e)}vt(e,ht.SYMBOL,n,t)}function $t(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===yt(e,1))return n="'s",bt(e),bt(e),void vt(e,ht.OPERATOR,n,t);const i=e.input.substring(e.position,e.position+2),o=e.input.substring(e.position,e.position+3);["===","!=="].includes(o)?(n=o,bt(e),bt(e),bt(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,bt(e),bt(e)):n=bt(e),vt(e,ht.OPERATOR,n,t)}function jt(e){const t=e.position,n=e.input,r=n.length;let i="";for(;r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=bt(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(i+=bt(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=bt(e)}if(r>e.position){const t=n[e.position];if("e"===t||"E"===t){const t=r>e.position+1?n[e.position+1]:"",o=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">o||o>"9"))for(i+=bt(e),"+"!==n[e.position]&&"-"!==n[e.position]||(i+=bt(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=bt(e)}}}const o=e.position;let s="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;s+=bt(e)}pt.has(s)?vt(e,ht.TIME,i+s,t):(e.position=o,vt(e,ht.NUMBER,i,t))}function Ot(e){const t=e.position,n=e.input,r=n.length;let i="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;i+=bt(e)}const o=function(e,t,n){const r=t.toLowerCase(),i=e.position;if("'s"===t||"'s"===t)return!1;const o=e.tokens[e.tokens.length-1];if(o&&(o.kind===ht.IDENTIFIER||o.kind===ht.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}gt(e);let s="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=bt(e)}if(s){const t=s.toLowerCase(),i=`${r} ${t}`,o=function(e,t,n,r){const i=t.toLowerCase(),o=n.toLowerCase();if("at"===i){const t=e.position;if("the"===o){gt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;n+=bt(e)}const i=n.toLowerCase();if("start"===i||"end"===i){gt(e);let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;t+=bt(e)}if("of"===t.toLowerCase())return vt(e,ht.IDENTIFIER,`at the ${i} of`,r),!0}return e.position=t,!1}if("start"===o||"end"===o){gt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;n+=bt(e)}return"of"===n.toLowerCase()?(vt(e,ht.IDENTIFIER,`at ${o} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(o)return!0;const a=function(e,t,n){const r=e.position;let i=`${t} ${n}`,o=e.position;const s=[t,n];for(;8>s.length&&(gt(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const n=e.input[e.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;t+=bt(e)}if(!t)break;s.push(t.toLowerCase());const n=s.join(" ");B.has(n)&&(i=n,o=e.position)}return B.has(i)&&i!==`${t} ${n}`?(e.position=o,i):(e.position=r,null)}(e,r,t);if(a)return vt(e,ht.OPERATOR,a,n),!0;if(B.has(i))return vt(e,ht.OPERATOR,i,n),!0}return B.has(r)?(e.position=i,vt(e,ht.OPERATOR,t,n),!0):(e.position=i,!1)}(e,i,t);if(o)return;const s=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||P.has(t)||mt.has(e)||mt.has(t)||B.has(t)?ht.OPERATOR:ht.IDENTIFIER}(i);vt(e,s,i,t)}function Nt(e){const t=e.position,n=e.input,r=n.length;bt(e);let i="$";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;i+=bt(e)}vt(e,ht.IDENTIFIER,i,t)}function Rt(e){return/[a-zA-Z]/.test(e)}function Lt(e){return/[a-zA-Z0-9]/.test(e)}function Mt(e){const t=e.input,n=t[e.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=e.position+1,i="";for(;t.length>r&&/[a-zA-Z0-9-]/.test(t[r]);)i+=t[r],r++;return i.length>0&&-1!==t.indexOf("</"+i+">",r)}function It(e){if(Mt(e))return!0;let t=e.position+1,n=!1;for(;e.input.length>t;){const r=e.input[t];if("/"===r&&e.input.length>t+1&&">"===e.input[t+1])return n;if(Lt(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,t++;else{if(" "!==r&&"\t"!==r)return!1;t++}if(t-e.position>50)return!1}return!1}function qt(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const Ht=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const n=performance.now()-t;return this.startTimes.delete(e),n}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=dt.getPerformanceStats();this.metrics.cacheHitRate=e.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Pt(){dt.cleanup(),Ht.getMetrics().memoryUsage>52428800&&Ht.reset()}let Bt=null;function Vt(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const n=e.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${t} cannot be converted to number: "${e}"`);return r}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const n=e[0];if(Array.isArray(n))throw Error(t+" is a nested array, cannot convert to number");return Vt(n,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const n=parseFloat(e);if(!isNaN(n))return n}}const n=e.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Ft(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const n=parseFloat(t);return isNaN(n)?null:n}return"boolean"==typeof e?e?1:0:null==e?0:null}function Dt(e,t){if(!Number.isFinite(e)){if(Number.isNaN(e))throw Error(t+" resulted in non-finite value: NaN");throw Error(`${t} resulted in non-finite value: ${e>0?"Infinity":"-Infinity"}`)}return e}function Ut(e){try{return Vt(e,"_"),!0}catch{return!1}}function _t(e,t,n){if("==="===n)return e===t;if("!=="===n)return e!==t;if(null==e||null==t)return function(e,t,n){if(null==e&&null==t)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,n);const[r,i]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const n=parseFloat(e),r=parseFloat(t);return isNaN(n)||isNaN(r)?[e,t]:[n,r]}const n=Ft(e),r=Ft(t);return null!==n&&null!==r?[n,r]:[e+"",t+""]}(e,t);switch(n){case">":return r>i;case"<":return i>r;case">=":return r>=i;case"<=":return i>=r;case"==":return zt(e,t);case"!=":return!zt(e,t);default:return!1}}function zt(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const n=parseFloat(t);return!isNaN(n)&&e===n}if("string"==typeof e&&"number"==typeof t){const n=parseFloat(e);return!isNaN(n)&&n===t}return"boolean"==typeof e?zt(e?1:0,t):"boolean"==typeof t?zt(e,t?1:0):e+""==t+""}function Wt(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function Zt(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function Jt(e,t,n,r,i,o=!0,s){return r}function Kt(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}"undefined"!=typeof window&&function(e=3e4){Bt&&clearInterval(Bt),Bt=setInterval(Pt,e)}();const Gt=lt([ut(),ut()]),Xt=lt([ut(),at()]),Yt={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){try{return Jt(0,0,0,t==n)}catch(e){throw e}},validate:e=>_e(e,"equals"),inputSchema:Gt,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)"}}},Qt={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,n)=>t===n,validate:e=>_e(e,"strictEquals")},en={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],evaluate:async(e,t,n)=>t!=n,validate:e=>_e(e,"notEquals")},tn={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,n)=>t!==n,validate:e=>_e(e,"strictNotEquals")},nn={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,n)=>_t(t,n,"<"),validate:e=>_e(e,"lessThan")},rn={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],evaluate:async(e,t,n)=>_t(t,n,"<="),validate:e=>_e(e,"lessThanOrEqual")},on={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,n)=>_t(t,n,">"),validate:e=>_e(e,"greaterThan")},sn={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],evaluate:async(e,t,n)=>_t(t,n,">="),validate:e=>_e(e,"greaterThanOrEqual")},an={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){try{return Jt(0,0,0,t&&n)}catch(e){throw e}},validate:e=>_e(e,"and"),inputSchema:Gt,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)"}}},cn={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,n)=>t||n,validate:e=>_e(e,"or")},ln={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>Fe(e,1,"not","operand")},un={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){let n;return n=null==t||($e(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Ne(t)||0!==Object.keys(t).length)),n},validate:e=>Fe(e,1,"isEmpty","value")},fn={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){let n;return n=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:($e(t),!1)),n},validate:e=>Fe(e,1,"no","value")},dn={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await un.evaluate(e,t),validate:e=>Fe(e,1,"isNotEmpty","value")},hn={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>mn(t),validate:e=>Fe(e,1,"exists","value")};function mn(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const pn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>!mn(t),validate:e=>Fe(e,1,"doesNotExist","value")},yn={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){let r;if(t&&n){if(Kt(t)&&Kt(n))return r=t.contains(n),r;if($e(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&Kt(n))return r=e.contains(n),r;if(e&&$e(n)&&n.match(/^[.#][\w-]+$/)){const t=document.querySelector(n);return r=!!t&&e.contains(t),r}}if($e(n)&&n.match(/^[.#][\w-]+$/)&&Kt(t)){const e=document.querySelector(n);return r=!!e&&t.contains(e),r}}if($e(t)&&$e(n))r=t.includes(n);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);r=e.includes(n)||n instanceof Node&&e.some(e=>e instanceof Node&&e.contains(n))}else r=!(!Ne(t)||!$e(n))&&n in t;return r},validate:e=>Fe(e,2,"contains","container, value")},bn={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,n)=>!await yn.evaluate(e,t,n),validate:e=>Fe(e,2,"doesNotContain","container, value")},gn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,n)=>null!=t&&null!=n&&(t+"").startsWith(n+""),validate:e=>Fe(e,2,"startsWith","str, prefix")},vn={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,n)=>null!=t&&null!=n&&(t+"").endsWith(n+""),validate:e=>Fe(e,2,"endsWith","str, suffix")},wn={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){let i=n,o=r;if(null!=i&&null!=o&&i>o){const e=i;i=o,o=e}return null!=i&&null!=o&&t>=i&&o>=t},validate:e=>Fe(e,3,"between","value, min, max")},En={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){try{let e;if(t instanceof Element&&$e(n)){const r=n;if(r.startsWith(".")||r.startsWith("#")||r.startsWith(":")||r.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(r))try{e=function(e,t){return dt.matches(e,t)}(t,r)}catch(t){e=!1}else e=!1}else if($e(t)&&$e(n)){const r=t,i=n;try{e=(i.startsWith("/")&&i.endsWith("/")?RegExp(i.slice(1,-1)):RegExp(i)).test(r)}catch(t){e=r.includes(i)}}else e=!1;return Jt(0,0,0,e)}catch(e){throw e}},validate:e=>Fe(e,2,"matches","element, selector"),inputSchema:Xt,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)"}}},xn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){let r=!1;if(t instanceof Element&&$e(n)){const e=n;e.startsWith(".")?r=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(r=t.hasAttribute(e.slice(1,-1)))}return r},validate:e=>Fe(e,2,"has","element, selector")},kn={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],evaluate:async(e,t,n)=>!await xn.evaluate(e,t,n),validate:e=>Fe(e,2,"doesNotHave","element, selector")},Sn={equals:Yt,strictEquals:Qt,notEquals:en,strictNotEquals:tn,lessThan:nn,lessThanOrEqual:rn,greaterThan:on,greaterThanOrEqual:sn,and:an,or:cn,not:ln,no:fn,isEmpty:un,isNotEmpty:dn,exists:hn,doesNotExist:pn,contains:yn,doesNotContain:bn,startsWith:gn,endsWith:vn,between:wn,matches:En,has:xn,doesNotHave:kn},Tn=new Set(["__proto__","constructor","prototype"]);function An(e,t){if(e instanceof Element)return Be(e,t);if(Ne(e)){if(Tn.has(t))return;return e[t]}return e[t]}function Cn(e){let t;if(Array.isArray(e))t=e;else{if(!("undefined"!=typeof NodeList&&e instanceof NodeList||"undefined"!=typeof HTMLCollection&&e instanceof HTMLCollection))return!1;t=Array.from(e)}return 0!==t.length&&t.every(e=>e instanceof Element||null!=e&&"object"==typeof e&&e.constructor!==Object&&!Array.isArray(e))}const $n={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[n,r]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return Cn(n)&&!(r in n)?Array.from(n,e=>An(e,r)):An(n,r)}},validate:e=>Fe(e,2,"possessive","element, property")??De(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[n]=t;if(e.me){if("string"!=typeof n)throw Error("Property name must be a string");if(e.me instanceof Element)return Be(e.me,n);if(Ne(e.me)){if(Tn.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>Ue(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[n]=t;if(null==e.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=e.it;if(r instanceof Element)return Be(r,n);if(Ne(r)){if(Tn.has(n))return;return r[n]}return r[n]},validate:e=>Ue(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[n]=t;if(e.you){if("string"!=typeof n)throw Error("Property name must be a string");if(e.you instanceof Element)return Be(e.you,n);if(Ne(e.you)){if(Tn.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>Ue(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[n,r]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Be(r,n);if(Ne(r)){if(Tn.has(n))return;return r[n]}return r[n]}},validate:e=>Fe(e,2,"of","property, object")??De(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[n,r]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");const i=r||e.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:e=>Ze(e,1,2,"attribute","attributeName, optional element")??De(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[n,r,i]=t;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const o=i||e.me;return!!(o&&o instanceof Element)&&o.getAttribute(n)===r},validate:e=>Ze(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??De(e,0,"attributeWithValue","attribute name")??De(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:e=>Ue(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[n]=t;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:e=>Ue(e,"idReference","idValue")}};function jn(e){return Array.isArray(e)?e:null==e?[]:"string"==typeof e?[e]:e instanceof NodeList||e instanceof HTMLCollection||"number"==typeof e.length?Array.from(e):[e]}const On=function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),Nn=On,Rn=On,Ln=On,Mn=On,In=(...e)=>{Nn&&console.log("\ud83d\udd27",...e)},qn=(...e)=>{Rn&&console.log("\ud83c\udfaf",...e)},Hn=(...e)=>{Ln&&console.log("\ud83d\udcdd",...e)},Pn=(...e)=>{Mn&&console.log("\ud83d\ude80",...e)};function Bn(e){return e.kind===ht.IDENTIFIER&&$.has(e.value.toLowerCase())}function Vn(e){return e.kind===ht.IDENTIFIER&&F.has(e.value.toLowerCase())}function Fn(e){return e.kind===ht.IDENTIFIER&&V.has(e.value.toLowerCase())}function Dn(e){return e.kind===ht.IDENTIFIER&&H.has(e.value.toLowerCase())}function Un(e){return B.has(e.value.toLowerCase())}function _n(e){return e.kind===ht.IDENTIFIER}function zn(e){return e.kind===ht.SELECTOR}function Wn(e){return e.kind===ht.SELECTOR&&!e.value.startsWith("<")}function Zn(e){return e.kind===ht.STRING||e.kind===ht.NUMBER||e.kind===ht.TEMPLATE}function Jn(e){return e.kind===ht.IDENTIFIER}function Kn(e){return e.kind===ht.TIME}function Gn(e){return e.kind===ht.SYMBOL}function Xn(e){return e.kind===ht.COMMENT}function Yn(e){if(e.kind!==ht.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!($.has(t)||F.has(t)||V.has(t)||H.has(t))}function Qn(e){return e.kind===ht.STRING}function er(e){return e.kind===ht.NUMBER}function tr(e){if(e.kind===ht.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function nr(e){return e.kind===ht.TEMPLATE}function rr(e){return e.kind===ht.SELECTOR&&e.value.startsWith("<")}function ir(e){return e.kind===ht.SELECTOR&&e.value.startsWith("#")}function or(e){return e.kind===ht.SELECTOR&&e.value.startsWith(".")}function sr(e){return e.kind===ht.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function ar(e){if(e.kind!==ht.OPERATOR)return!1;const t=e.value.toLowerCase();return!P.has(t)&&!B.has(t)}function cr(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function lr(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function ur(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function fr(e,t,n,r){return{type:"binaryExpression",operator:e,left:t,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function dr(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function hr(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function mr(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function pr(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function yr(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function br(e,t,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...n&&{source:n}}],start:e.start,end:e.end,line:e.line,column:e.column}}function gr(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const vr=[a,u,c,l];function wr(e,t=[]){if(e.isAtEnd())return!0;for(const t of vr)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function Er(e,t=[]){if(!wr(e,t))return e.parseExpression()}function xr(e,t){return!!e.check(t)&&(e.advance(),!0)}function kr(e){const t=e.savePosition();let n;if(e.checkIdentifierLike()){const r=e.peek().value;e.advance(),e.check(":")?(e.advance(),n=r):e.restorePosition(t)}const r=e.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}class Sr{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Sr(e.value);return t.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},t}static fromIdentifier(e){const t=new Sr(e.name);return void 0!==e.start&&(t.startPos={start:e.start,end:e.end??0,line:e.line??1,column:e.column??1}),t}static named(e){return new Sr(e)}withArgs(...e){return this.args.push(...e),this}withBody(e){return this.body=e,this}withImplicitTarget(e){return this.implicitTarget=e,this}withModifier(e,t){return this.modifiers||(this.modifiers={}),this.modifiers[e]=t,this}withModifiers(e){return this.modifiers={...this.modifiers,...e},this}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=e,this}blocking(e=!0){return this.isBlocking=e,this}startingAt(e){return this.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},this}endingAt(e){return this.endPos={start:e.start??this.startPos?.start??0,end:e.end,line:e.line??this.startPos?.line??1,column:e.column??this.startPos?.column??1},this}build(){const e={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(e.body=this.body),this.implicitTarget&&(e.implicitTarget=this.implicitTarget),this.modifiers&&(e.modifiers=this.modifiers),this.originalCmd&&(e.originalCommand=this.originalCmd),e}clone(){const e=new Sr(this.name);return e.args=[...this.args],e.body=this.body?[...this.body]:void 0,e.implicitTarget=this.implicitTarget,e.isBlocking=this.isBlocking,e.modifiers=this.modifiers?{...this.modifiers}:void 0,e.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function Tr(e,n){const r=[];let i="";const o=e.peek().start||0,s=e.peek().line||1,a=e.peek().column||1;if(e.checkIdentifierLike()){for(i=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),i+=":",e.checkIdentifierLike()&&(i+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=kr(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),r.push({type:"functionCall",name:i,args:t,start:o,end:e.getPosition().end,line:s,column:a})}else r.push({type:"string",value:i,start:o,end:e.getPosition().end,line:s,column:a})}const c=[...r],l={};for(;!wr(e);){if(e.check(x)||e.check(g)){e.advance();const t=Er(e,[w]);t&&(l.on=t);continue}if(e.check(w)){e.advance();const n=[];for(;!wr(e,[x,g]);){const t=e.savePosition(),r=e.parsePrimary();r&&n.push(r),e.savePosition()===t&&e.advance()}const r=n[0],i=n[n.length-1];l.with=t({type:"arrayLiteral",elements:n,...void 0!==r?.start?{start:r.start}:{},...void 0!==i?.end?{end:i.end}:{},...void 0!==r?.line?{line:r.line}:{},...void 0!==r?.column?{column:r.column}:{}});continue}const n=e.savePosition(),r=e.parsePrimary();r&&c.push(r),e.savePosition()===n&&e.advance()}const u=Sr.fromIdentifier(n).withArgs(...c);return Object.keys(l).length>0&&u.withModifiers(l),u.endingAt(e.getPosition()).build()}function Ar(e,t){const n=Sr.fromIdentifier(t);if(e.check(A)){const t=e.advance(),r=e.check(k)?e.advance():t;n.withModifier("the",{type:"literal",value:"event",start:t.start,end:r.end,line:t.line,column:t.column})}return n.endingAt(e.getPosition()).build()}function Cr(e,t){const n=[],r=()=>e.check(l)||t&&e.check(c);for(;!e.isAtEnd()&&!r();){if(Xn(e.peek())){e.advance();continue}if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))break;e.advance();const t=e.parseCommand();t&&n.push(t),(e.check(a)||e.check(u)||e.check(","))&&e.advance()}return n}const $r=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function jr(e,t,n){return null!==t&&!$r.has(t.value?.toLowerCase?.()??"")&&(e.checkIsCommand()||e.isCommand(n.value?.toLowerCase()))}function Or(e,t){const n=[];let r=!1;const i=e.savePosition();let o=null;for(let n=0;500>n&&!e.isAtEnd();n++){const n=e.peek();if(n.value===a){r=!0;break}if(n.value===l||n.value===S||"def"===n.value||n.value===x)break;if(void 0!==n.line&&n.line!==t.line&&jr(e,o,n))break;Xn(n)||(o=n),e.advance()}e.restorePosition(i);let s=!1;if(!r){const n=e.savePosition(),r=t.line,i=100;let o=!1,a=null;for(;!e.isAtEnd()&&i>e.current-n;){const t=e.peek(),n=t.value?.toLowerCase();if(o&&void 0!==t.line&&t.line!==r)break;if(n===S||"def"===n||n===x)break;if(n===c||n===l){t.line===r&&(s=!0);break}if(jr(e,a,t)){if(void 0!==t.line&&t.line!==r){s=!0;break}o=!0}Xn(t)||(a=t),e.advance()}e.restorePosition(n)}const u=r||s;let f;if(u)f=e.parseExpression();else{const n=[],r=20;let i=0,o=!0;for(;!e.isAtEnd()&&!e.check(a)&&(o||!e.checkIsCommand()&&!e.isCommand(e.peek().value))&&r>i;){o=!1;const t=e.savePosition();n.push(e.parseLogicalAnd()),e.savePosition()===t&&e.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:t.line,column:t.column}}if(n.push(f),u){xr(e,a);const r=Cr(e,!0);if(0===r.length&&e.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");n.push(dr(r,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}));let i=!1;if(e.check(c))if(e.advance(),e.check("if")){const t=e.peek();e.advance();const r=Or(e,t);n.push(dr([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column})),i=!0}else{const r=Cr(e,!1);n.push(dr(r,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}i||e.isAtEnd()||e.consume(l,"Expected 'end' after if block")}else{if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))throw Error("Expected command after if condition in single-line form");{e.advance();const r=e.parseCommand();n.push(dr([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}}return Sr.from(t).withArgs(...n).endingAt(e.getPosition()).build()}function Nr(e,t){const n=[],r={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(n.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();n.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();n.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();r.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const i=Sr.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const Rr=new Set(["my","its","your"]);function Lr(e){return{type:"literal",value:e,raw:e}}function Mr(e){const t={};if(xr(e,f)){const n=e.parseExpression();return n&&(t.for=n),t}if(!e.check(h))return t;e.advance();const n=e.peek();if(!n||!_n(n))return t;e.advance();let r=n.value;if(e.check(":")){e.advance();const t=e.peek();t&&_n(t)&&(e.advance(),r=`${r}:${t.value}`)}if(t.until=Lr(r),xr(e,v)){const n=Er(e);n&&(t.from=n)}return t}function Ir(e,t){const n=[],r=Er(e,[v]);r&&n.push(r);const i={};if(xr(e,v)){const t=Er(e);t&&(i.from=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(i).endingAt(e.getPosition()).build()}function qr(e,t){const n=[],r={};if(e.check("between")){e.advance();const t=[],n=Er(e,[u]);if(n&&"binaryExpression"===n.type&&"and"===n.operator)n.left&&t.push(n.left),n.right&&t.push(n.right);else{n&&t.push(n),xr(e,u);const r=Er(e,[v,x,f]);r&&t.push(r)}const i=t[0],o=t[t.length-1];r.between={type:"arrayLiteral",elements:t,...void 0!==i?.start?{start:i.start}:{},...void 0!==o?.end?{end:o.end}:{},...void 0!==i?.line?{line:i.line}:{},...void 0!==i?.column?{column:i.column}:{}}}else{const t=Er(e,[v,x]),i="asExpression"===t?.type?function(e){const t="string"==typeof e?e:e?.name;return"modal"===t||"non-modal"===t?t:void 0}(t.targetType):void 0;t&&void 0!==i&&t.expression?(n.push(t.expression),r.as=Lr(i)):t&&n.push(t),void 0===i&&e.check("modal")&&(e.advance(),r.as=Lr("modal"))}if(xr(e,v)||xr(e,x)){const t=Er(e);t&&(r.on=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers({...r,...Mr(e)}).endingAt(e.getPosition()).build()}function Hr(e){if(!e.check("using"))return{};if(e.advance(),!e.match("view"))throw Error("expected 'view transition' after 'using'");if(!e.match("transition"))throw Error("expected 'transition' after 'using view'");return{viewTransition:Lr("transition")}}function Pr(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=Er(e,[g]);t&&n.push(t)}const r={};if(xr(e,g)){const t=Er(e);t&&(r.to=t)}return Sr.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}function Br(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const r=e.peek();if(!r||!N.includes(r.value))return e.addError(`Expected operation keyword (${N.join(", ")}) after put expression, got: ${r?.value}`),null;let i=e.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=j:"at end of"===o||"at the end of"===o?i=O:"at"===i&&(e.check(C)||e.check(A)?(xr(e,A),e.check(C)&&(e.advance(),e.check(E)&&(e.advance(),i=j))):e.check(l)&&(e.advance(),e.check(E)&&(e.advance(),i=O)));const s=e.parseExpression();return s?Sr.fromIdentifier(t).withArgs(n).withModifier(i,s).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Vr=["afterbegin","afterend","beforebegin","beforeend","delete","innerhtml","innermorph","into","morph","none","outerhtml","outermorph","over"];function Fr(e,t){const n=[],r={};if(!e.isAtEnd()){const t=e.peek(),n=t?.value?.toLowerCase();n&&Vr.includes(n)&&(e.advance(),r.strategy=Lr(n))}const i="delete"===r.strategy?.value;xr(e,E);const o=i?e.parseExpression():Er(e,[w]);if(o&&n.push(o),!i&&xr(e,w)){const t=Er(e,["using"]);t&&(r.with=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers({...r,...Hr(e)}).endingAt(e.getPosition()).build()}function Dr(e,t){const n=[],r={};if(!(wr(e,["catch","finally"])||e.check("when")||e.check("where")||e.check(w))){const t=e.parseExpression();t&&n.push(t)}if(xr(e,w)){const t=function(e){if(!e)return null;const t="string"==typeof e.name?e.name:"string"==typeof e.value?e.value:null;return null===t?null:t.replace(/^\*/,"")}(e.parseExpression());null!==t&&(r.with=Lr(t))}const i=Sr.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}function Ur(e,t){const n=e.savePosition();let r=null,i=[];try{r=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end}}(e)??function(e){if(!e.check(T)&&!e.check("local"))return null;const t=e.advance(),n=e.advance();return{type:"identifier",name:n.value,scope:t.value,start:t.start,end:n.end}}(e)??function(e){if(!e.check(A))return null;const t=e.savePosition();e.advance();const n=e.parseExpression();if(!n)return e.restorePosition(t),null;if("binaryExpression"===n.type&&n.operator===E){const e=n.left,t=n.right;return yr(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(g)?n:(e.restorePosition(t),null)}(e),r||(r=e.parseExpression())}catch{e.restorePosition(n),r=null}if(!r){const t=function(e){if(e.match(":")){const t=e.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const t=[];for(;!(e.isAtEnd()||e.check(g)||e.check(a)||e.check(u)||e.check(c)||e.check(l));)t.push(e.parsePrimary());if(0===t.length)return{expression:null,tokens:[]};if(t.length>=4){const e=(e,t)=>e[t];if(e(t[0],"value")===A&&e(t[2],"value")===E){const n=t[1],r=t[3];return{expression:yr(ur(e(n,"value")||e(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:e(r,"value")||e(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:t[0].start??0,end:r.end??0,line:t[0].line??1,column:t[0].column??1}),tokens:[]}}}return 1===t.length?{expression:t[0],tokens:[]}:{expression:null,tokens:t}}(e);r=t.expression,i=t.tokens}if(r&&(r=function(e){const t=e=>{if(!e||"selector"!==e.type)return null;const t=e.value;return"string"==typeof t&&t.startsWith("*")?ur(t,{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}):null},n={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},r=t(e);if(r)return r;if("binaryExpression"===e.type&&e.operator===E){const r=t(e.left);if(r)return yr(r,e.right,n)}if("propertyOfExpression"===e.type){const r=t(e.property);if(r)return yr(r,e.target,n)}return e}(r)),!e.check(g)){const t=e.isAtEnd()?"end of input":e.peek().value;throw Error("Expected 'to' in set command, found: "+t)}e.advance();const o=e.parseExpression()??e.parsePrimary();let s;var f;e.check(x)&&(f=e.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||_r.has(f.value))&&(e.advance(),s=Er(e));const d=[];r?d.push(r):i.length>0&&d.push(...i);const h=Sr.fromIdentifier(t).withArgs(...d);return o&&h.withModifier("to",o),s&&h.withModifier("on",s),h.endingAt(e.getPosition()).build()}const _r=new Set(["me","my","it","its","you","your","yourself"]),zr=new Set(["top","middle","bottom","left","center","right","nearest"]);function Wr(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Zr(e){if(e.isAtEnd())return;const t=e.current,n=e.parsePrimary();return e.current===t?void 0:n}const Jr=new Set(["then","and","else","end","when","where","catch","finally"]);const Kr=new Set(["top","middle","bottom","left","center","right","nearest"]),Gr=new Set(["up","down","left","right"]),Xr=["of","smoothly","instantly","by","up","down","left","right"];function Yr(e,t){const n=e.peek(),r=e.resolveKeyword(n.value).toLowerCase();return("smoothly"===r||"instantly"===r)&&(e.advance(),t.behavior=Wr("smoothly"===r?"smooth":"instant",n),!0)}function Qr(e,t){const n=[],r={};if(xr(e,"url"),!e.isAtEnd()&&ai(e)){const t=li(e);t&&n.push(t)}else{const t=Er(e,["with"]);t&&n.push(t)}if(xr(e,"with")){xr(e,"title");const t=Er(e);t&&(r.title=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}function ei(e,t){if(e.isAtEnd())return!0;const n=e.peek();return(!e.checkIsCommand()||"("!==e.peekAt(1)?.value)&&(!!wr(e,["catch","finally","on"])||gr(n,[...t.markers]))}function ti(e,t,n,r){const i=[],o={};if("none"!==r.positional){const t=r.continuation??[];for(;!ei(e,r);){const n="expression"===r.positional?e.parseExpression():e.parsePrimary();if(!n)break;if(i.push(n),e.match(","))continue;if("primary"===r.positional)continue;const o=n.name;if("identifier"===n.type&&o&&t.includes(o.toLowerCase()))continue;const s=e.peek();if(!s||!t.includes(s.value.toLowerCase()))break;e.advance(),i.push(e.createIdentifier(s.value))}}const s=new Set(r.commaList??[]);for(;!e.isAtEnd()&&gr(e.peek(),[...r.markers]);){const t=e.advance().value,n=e.resolveKeyword(t).toLowerCase();let r=e.parseExpression();if(r&&s.has(n)&&e.check(",")){const t=[r];for(;e.match(",");){const n=e.parseExpression();if(!n)break;t.push(n)}const n=t[0];r={type:"arrayLiteral",elements:t,start:n.start,end:t[t.length-1].end,line:n.line,column:n.column}}r&&(o[n]=r)}const a=Sr.from(t).withName(n).withArgs(...i);return Object.keys(o).length>0&&a.withModifiers(o),a.endingAt(e.getPosition()).build()}const ni=new Map([["put",Br],["trigger",Tr],["send",Tr],["remove",Ir],["take",function(e,t){const n=[],r={},i=Er(e,[v,f]);if(i&&n.push(i),xr(e,v)){const t=Er(e,[f]);t&&(r.from=t)}if(xr(e,f)){const t=Er(e);t&&(r.for=t)}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}],["toggle",qr],["set",Ur],["add",(e,t)=>Pr(e,ii(t))],["halt",Ar],["measure",Nr],["js",function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const r=e.peek().start,i=function(e,t){const n=e.getInputSlice(t);if(!n)return t;let r=0;for(;n.length>r;){const e=n[r];if("'"!==e&&"\u2019"!==e&&"\u2018"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===e&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==e&&"E"!==e||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return t+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==e;)"\\"===n[r]&&r++,r++;r++}}return t+n.length}(e,r);for(;!e.isAtEnd()&&!e.check(l)&&e.peek().start<i;)e.advance();e.consume(l,"Expected end after js code body");const o={type:"literal",value:e.getInputSlice(r,i).trim(),start:t.start,end:e.getPosition().end},s={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Sr.fromIdentifier(t).withArgs(o,s).endingAt(e.getPosition()).build()}],["go",function(e,n){const r=[],i={};for(;!wr(e,["when","where","catch","finally"]);){const n=e.peek(),o=e.resolveKeyword(n.value).toLowerCase();if("to"!==o&&"the"!==o)if("back"!==o&&"forward"!==o||0!==r.length||i.url){if("url"===o){e.advance();const t=ai(e)?li(e):Zr(e);t&&(i.url=t);continue}if("in"===o){e.advance();const t=e.peek(),n=[];for(;!e.isAtEnd()&&["new","window"].includes(e.peek().value.toLowerCase());)n.push(e.advance().value.toLowerCase());i.in=Wr(n.join(" ")||t.value,t);continue}if(!zr.has(o)||i.position){if("of"===o){e.advance(),"the"===e.resolveKeyword(e.peek().value).toLowerCase()&&e.advance();const t=Zr(e);t&&(i.of=t);continue}if("smoothly"!==o&&"instantly"!==o){if("+"===n.value||"-"===n.value||"number"===n.kind){let r=1;"+"!==n.value&&"-"!==n.value||(e.advance(),"-"===n.value&&(r=-1));const o=e.peek();if("number"!==o.kind)break;e.advance();let s=o.end;const a=e.peek();e.isAtEnd()||"px"!==a.value||a.start!==o.end||(s=e.advance().end),i.by=t({type:"literal",value:r*Number(o.value),raw:o.value,start:n.start,end:s,line:n.line,column:n.column});continue}if(0===r.length&&!i.of&&!i.url){if(ai(e)){const t=li(e);if(t){r.push(t);continue}}const t=Zr(e);if(t){r.push(t);continue}}break}e.advance(),i.behavior=Wr("smoothly"===o?"smooth":"instant",n)}else e.advance(),i.position=Wr(o,n)}else e.advance(),i[o]=Wr(o,n);else e.advance()}return Sr.fromIdentifier(n).withArgs(...r).withModifiers(i).endingAt(e.getPosition()).build()}],["push",Qr],["replace",Qr],["scroll",(e,n)=>function(e,n){return e.isAtEnd()?null:"to"===e.resolveKeyword(e.peek().value).toLowerCase()?function(e,t){const n=[],r={};for(e.advance();!wr(e,["when","where","catch","finally"]);){const t=e.peek(),i=e.resolveKeyword(t.value).toLowerCase();if("the"!==i)if(!Kr.has(i)||r.position){if("of"===i){e.advance();const t=Er(e,Xr);t&&(r.of=t);continue}if(!Yr(e,r)){if(0===n.length&&!r.of){const t=Er(e,Xr);if(t){n.push(t);continue}}break}}else e.advance(),r.position=Wr(i,t);else e.advance()}return Sr.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(e,n):function(e){for(let t=0;12>t;t++){const n=e.peekAt(t);if(!n)return!1;const r=e.resolveKeyword(n.value).toLowerCase();if("by"===r)return!0;if(Jr.has(r))return!1}return!1}(e)?function(e,n){const r=[],i={};for(;!wr(e,["when","where","catch","finally"]);){const n=e.peek(),o=e.resolveKeyword(n.value).toLowerCase();if(Gr.has(o))e.advance(),i.direction=Wr(o,n);else{if("by"===o){e.advance();let n=1;const r=e.peek();"+"!==r.value&&"-"!==r.value||(e.advance(),"-"===r.value&&(n=-1));const o=e.peek();if("number"===o.kind){e.advance();const r=e.peek();let s=o.end;e.isAtEnd()||"px"!==r.value||r.start!==o.end||(s=e.advance().end),i.by=t({type:"literal",value:n*Number(o.value),raw:o.value,start:o.start,end:s,line:o.line,column:o.column})}else{const t=Er(e,Xr);t&&(i.by=t)}continue}if(!Yr(e,i)){if(0===r.length){const t=Er(e,Xr);if(t){r.push(t);continue}}break}}}return Sr.fromIdentifier(n).withArgs(...r).withModifiers(i).endingAt(e.getPosition()).build()}(e,n):null}(e,n)??si(e,n)],["tell",function(e,t){const n=e.parseExpression();if(!n)throw Error("tell command requires a target expression");e.check(g)&&e.advance();const r=[];for(;!e.isAtEnd();){if(e.checkIsCommand()){try{e.advance();const t=e.parseCommand();if(!t)break;r.push(t)}catch{break}if(e.match(u)||e.match(a))continue;if(e.check(c))break;if(e.check(l)){e.advance();break}if(e.checkIsCommand())continue;break}break}if(0===r.length)throw Error("tell command requires at least one command after the target");return Sr.fromIdentifier(t).withArgs(n,...r).endingAt(e.getPosition()).build()}],["pick",function(e,t){const n=Sr.fromIdentifier(t);xr(e,A);const r=e.peek().value,i=e=>({type:"literal",value:e,start:t.start,end:t.end}),o=()=>{if(!e.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return e.parseExpression()};if("first"===r){e.advance();const t=e.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===r){e.advance();const t=e.parsePrimary(),r=o();return n.withArgs(r).withModifier("variant",i("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===r){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const r=o(),s=n.withArgs(r).withModifier("variant",i("random"));return t&&s.withModifier("count",t),s.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?i("start"):e.parsePrimary();let s=!1;(e.match("to")||e.match(".."))&&(e.match("end")?s=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=o(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",t).withModifier("rangeMode",i(a));return s?l.withModifier("rangeEnd",i("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(e.getPosition()).build()}if("match"===r||"matches"===r){e.advance(),e.match("of");const t=e.parsePrimary();let s;e.matchOperator("|")&&(s=e.advance().value);const a=o(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",t);return s&&c.withModifier("flags",i(s)),c.endingAt(e.getPosition()).build()}return si(e,t)}],["start",function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd("start view transition");return Sr.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}],["swap",Fr],["morph",Fr],["show",Dr],["hide",Dr],["process",(e,t)=>function(e,t){if(!e.check("partials"))return null;const n=[];if(e.advance(),xr(e,b)){const t=Er(e,["using"]);t&&n.push(t)}const r=Hr(e),i=Sr.fromIdentifier(t).withArgs(...n);return Object.keys(r).length>0&&i.withModifiers(r),i.endingAt(e.getPosition()).build()}(e,t)??si(e,t)]]),ri=new Set(ni.keys());function ii(e){return{kind:"identifier",value:e.name,start:e.start??0,end:e.end??0,line:e.line??0,column:e.column??0}}const oi={positional:"primary",markers:[]};function si(e,t){return ti(e,ii(t),t.name.toLowerCase(),oi)}function ai(e){const t=e.peek();if("/"===t.value)return!0;if(e.checkIdentifierLike()){const n=e.peekAt(1);return!!n&&":"===n.value&&n.start===t.end}return!1}const ci=new Set(["{",")"]);function li(e){const t=e.savePosition(),n=e.peek();let r="",i=null;for(;!e.isAtEnd();){const t=e.peek();if(i&&t.start!==i.end)break;if("$"===t.value&&"{"===e.peekAt(1)?.value){e.advance();let n=e.advance(),o=1;for(;!e.isAtEnd()&&o>0;)n=e.advance(),"{"===n.value?o++:"}"===n.value&&o--;r+=e.getInputSlice(t.start,n.end),i=n;continue}if(ci.has(t.value))break;i=e.advance(),r+=i.value}if(!r||"/"===r)return e.restorePosition(t),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 ui(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function fi(e){const t=[],n=e.getPosition();do{if(!e.checkIdentifierLike())break;const n=e.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};e.consume(":","Expected ':' after property name in fetch named arguments");const i=e.parsePrimary();i&&t.push({key:r,value:i})}while(e.match(",")&&!e.isAtEnd());const r=e.getPosition();return{type:"objectLiteral",properties:t,start:n.start,end:r.end,line:n.line,column:n.column}}const di={positional:"none",markers:[],syntax:""},hi=e=>({positional:"expression",markers:[],syntax:e}),mi=hi("beep! [<expression>, \u2026]"),pi={append:{positional:"expression",markers:["to"],syntax:"append <value> [to <target>]"},prepend:{positional:"expression",markers:["to"],syntax:"prepend <value> [to <target>]"},make:{positional:"primary",markers:["a","an","from","called"],commaList:["from"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},throw:{positional:"primary",markers:[],syntax:"throw <error>"},"beep!":mi,beep:mi,blur:hi("blur [<target>]"),break:di,breakpoint:di,call:hi("call <expression>"),clear:hi("clear <target>"),close:hi("close [<target>]"),continue:di,copy:{positional:"expression",markers:["to"],syntax:"copy <source> [to clipboard]"},default:{positional:"expression",markers:["to"],syntax:"default <target> to <value>"},empty:hi("empty [<target>]"),exit:di,focus:hi("focus [<target>]"),get:hi("get <expression>"),log:hi("log <expression>[, <expression>\u2026]"),open:hi("open [<dialog>] [as modal|non-modal]"),"pseudo-command":hi("<method>(\u2026) [on|from|\u2026] <target>"),render:{positional:"expression",markers:["with"],syntax:"render <template> [with <variables>]"},reset:hi("reset [<form>]"),return:hi("return [<value>]"),select:hi("select [<target>]"),settle:{positional:"expression",markers:["for"],syntax:"settle [<target>] [for <timeout>]"}},yi={positional:"expression",markers:[],continuation:["into","from","to","with","by","at","before","after","over"]};function bi(e){return pi[e.toLowerCase()]??null}const gi=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]),vi=new Set(["s","seconds","ms","milliseconds"]);class wi{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors],e.recovered=!0),e}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}const e=this.peek(),t=e&&ae(e.value)?e.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==t){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const e=this.peekAt(1);if(null!==e&&("init"===e.value||"on"===e.value||"def"===e.value||void 0!==ae(e.value))){this.advance();continue}}if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def")){const t=this.peek(),n=t?ae(t.value):void 0;if(n){const t=this.advance(),r=n(this.getContext(),t);r&&e.push(r);continue}break}{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){Hn("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const t=[e];Hn(`\u2705 PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){Hn(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(Hn("\u2705 PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,Hn(`\u2705 PARSER: Added event handler, now have ${t.length} statements total`)),Hn(`\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 Hn("\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(t),tokens:this.tokens,error:this.error};Hn("\u2705 PARSER: No more event handlers, at end of input");break}}return Hn(`\u2705 PARSER: Finished parsing, creating Program node with ${t.length} statements`),this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return n&&["number","string","identifier"].includes(e.kind)?this.addError(`Unexpected token: ${e.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+e.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,warnings:this.warnings}}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,n=this.prattCache.get(t);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),i=wi.PRATT_TABLE.get(r.value);let o;if(i?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();o=i.prefix.handler(e,this.makePrattContext())}else o=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(o,t);if(e){o=e;continue}}const n=wi.PRATT_TABLE.get(t.value);if(!n?.infix){if(D.has(t.value)||U.has(t.value))break;break}const[r]=n.infix.bp;if(e>r)break;if("="===t.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch(e){Hn("arrow body discarded after error:",e instanceof Error?e.message:e+"")}return this.createErrorNode()}if("+"===t.value||"-"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("+"===e.value||"-"===e.value))return this.addError(`Invalid operator combination: ${t.value}${e.value}`),o}if("*"===t.value||"/"===t.value||"%"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("*"===e.value||"/"===e.value||"%"===e.value||"+"===e.value||"-"===e.value))return this.addError("*"===t.value&&"*"===e.value?"Unexpected token: "+e.value:`Invalid operator combination: ${t.value}${e.value}`),o}const i=this.advance();if(this.isAtEnd()&&!wi.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(t,{node:o,endPos:this.current}),o}tryParseStringPostfix(e,t){const n=t.value;let r=null;if(gi.has(n)||vi.has(n)&&this.isNumericPostfixRoot(e)?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:e,unit:r,start:e.start,end:i.end,line:e.line,column:e.column}}isNumericPostfixRoot(e){const t=e;return"literal"===t.type&&"number"==typeof t.value||("unaryExpression"!==t.type||"-"!==t.operator&&"+"!==t.operator?!("binaryExpression"!==t.type||!["+","-","*","/"].includes(t.operator??"")):void 0!==t.argument&&this.isNumericPostfixRoot(t.argument))}canStartOperand(e){if(!e)return!1;const t=e.value;return!D.has(t)&&!U.has(t)&&("number"===e.kind||"string"===e.kind||"identifier"===e.kind||"symbol"===e.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(t))}makePrattContext(){const e=this;return{peek:()=>e.tokens.length>e.current?e.tokens[e.current]:void 0,advance:()=>{const t=e.tokens[e.current];return e.current++,t},parseExpr:t=>e.parseExpressionPratt(t),isStopToken:()=>{const t=e.tokens[e.current];return!t||D.has(t.value)||U.has(t.value)},atEnd:()=>e.current>=e.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else if("wait"===e.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):L(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):M(e)}createCommandFromIdentifier(e){const t=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(t))return this.parseCompoundCommand(e);const n={kind:"identifier",value:e.name,start:e.start??0,end:e.end??0,line:e.line??0,column:e.column??0};return ti(this.getContext(),n,t,bi(t)??yi)}isCompoundCommand(e){return ri.has(e.toLowerCase())}parseCompoundCommand(e){return function(e,t){const n=ni.get(t.name.toLowerCase());return n?n(e,t):null}(this.getContext(),e)}parsePutCommand(e){return Br(this.getContext(),e)}parseSetCommand(e){return Ur(this.getContext(),e)}parseHaltCommand(e){return Ar(this.getContext(),e)}parseMeasureCommand(e){return Nr(this.getContext(),e)}parseTriggerCommand(e){return Tr(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(Hn("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){Hn("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){Hn(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&&(Hn("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(Hn("\u2705 Parsed command:",r.name),t.push(r),e=!0)}catch(e){Hn("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n,this.recordDropped("Discarded a command that failed to parse: "+(e instanceof Error?e.message:e+""))}}else this.checkIdentifier()&&Hn("\u274c IDENTIFIER is not a command:",this.peek().value);if(!e){Hn("\u274c No command parsed, breaking. Current token:",this.peek().value),this.isAtEnd()||n()||this.recordDropped(`Not a command, and the rest of the body was discarded: '${this.peek().value}'`);break}Hn("\ud83d\udccd After parsing command, current token:",this.peek().value);const o=this.current;for(;!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)Hn("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.recordDroppedRange(o,this.current),this.match("then","and",","))Hn("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){Hn("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}Hn("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const t of e)if(this.check(t)){r=t;break}return this.check("end")||e.some(e=>this.check(e))||(r=""),Hn("\u2705 parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(e="repeat"){const{commands:t}=this.parseCommandListUntilTerminator([]);if(Hn('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw Hn('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${e} block`);return Hn('\u2705 Found "end", consuming it'),this.advance(),t}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",i=null,o=null,s=null,a=null,c=null,l=null;if(e.check(f)){e.advance(),r=f;const t=e.peek();_n(t)&&(c=t.value,e.advance()),e.check(b)&&(e.advance(),a=e.parseExpression())}else if(e.check(b))e.advance(),r=f,c="it",a=e.parseExpression();else if(e.check(d))e.advance(),r=d,s=e.parseExpression();else if(e.check(h))if(e.advance(),r=h,e.check(k)){e.advance(),r="until-event";const t=e.peek();if(Hn("\ud83d\udccd Parsing event name, current token:",{value:t.value,kind:t.kind}),!_n(t)&&!Fn(t))throw Error('Expected event name after "event"');if(i=t.value,e.advance(),Hn("\u2705 Got event name:",i,"Next token:",e.peek().value),Hn('\ud83d\udd0d Checking for "from", current token:',e.peek().value),e.check(v)){Hn('\u2705 Found "from", advancing...'),e.advance(),Hn('\ud83d\udccd After consuming "from", current token:',e.peek().value),xr(e,A)&&Hn('\u2705 Found "the", advancing...');const t=e.peek();Hn("\ud83d\udd0d Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),o=e.parsePrimary(),Hn("\u2705 After parsePrimary, eventTarget:",o)}else Hn('\u274c No "from" found, skipping target parsing')}else s=e.parseExpression();else e.check(m)?(e.advance(),r=m):(l=e.parseExpression(),e.check(p)&&(e.advance(),r=p));let u,g=null;if(e.check(w)){const t=e.peekAt(1);t&&t.value.toLowerCase()===y&&(e.advance(),e.advance(),g=y)}else if(e.check(y)){e.advance();const t=e.peek();_n(t)?(g=t.value,e.advance()):g=y}let E=null,x=!1;if(r===m){const t=e.parseRepeatBody();if(u=t.commands,"else"===t.terminator)e.advance(),E=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(x=!0,r=t.terminator,e.advance(),s=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();u=t.commands,t.hasElse&&(e.advance(),E=e.parseCommandListUntilEnd())}const S={start:t.start,end:t.end,line:t.line,column:t.column},T={loopType:hr(r,S)};c&&(T.for=hr(c,S)),a&&(T.in=a),l&&(T.times=l),s&&(T["while"===r?"while":"until"]=s),i&&(T.event=hr(i,S)),o&&(T.from=o),g&&(T.index=hr(g,S)),n.push(dr(u,{...S,end:S.end||0})),null!==E&&n.push(dr(E,{...S,end:S.end||0}));const C=Sr.from(t).withArgs(...n).withModifiers(T);return x&&C.withModifier("bottomTested",{type:"literal",value:!0,...S}),C.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const n=[];let r=null,i=null;e.check("each")&&e.advance();const o=e.peek();if(!_n(o))throw Error('Expected variable name after "for"');if(r=o.value,e.advance(),!e.check(b))throw Error('Expected "in" after variable name in for loop');if(e.advance(),i=e.parseExpression(),!i)throw Error('Expected collection expression after "in"');let s=null;if(e.check(w)){const t=e.peekAt(1);t&&t.value.toLowerCase()===y&&(e.advance(),e.advance(),s=y)}else if(e.check(y)){e.advance();const t=e.peek();_n(t)?(s=t.value,e.advance()):s=y}const a=e.parseCommandListUntilEnd("for");n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(hr(r,c)),n.push(i),s&&n.push(hr(s,c)),n.push(dr(a,{...c,end:c.end||0})),Sr.from({...t,value:"repeat"}).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const n=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!wr(e)){const r=e.parseExpression();return n.push(r),Sr.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{if(e.checkTimeExpression()||e.checkLiteral()||e.check("(")){if(r.push({kind:"duration",expr:e.parseExpression()}),e.check("or")){e.advance();continue}break}const t=e.peek();if(!_n(t))throw Error('Expected event name or duration after "for"');const n=t.value;e.advance();const i=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!_n(t))break;i.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(r.push({kind:"event",name:n,params:i}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let i=null;e.check(v)&&(e.advance(),xr(e,A),i=e.parsePrimary());const o={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(pr(r.map(e=>mr("duration"===e.kind?[{key:ur("duration",o),value:e.expr}]:[{key:ur("name",o),value:lr(e.name,`"${e.name}"`,o)},{key:ur("args",o),value:pr(e.params.map(e=>lr(e,`"${e}"`,o)),o)}],o)),o)),i&&n.push(i)}return Sr.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const n=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=e.advance().value,i=e.previous();if(n.push(ur(r,{start:i.start,end:i.end,line:i.line,column:i.column})),e.check("(")){e.advance();const r=[];for(;!e.isAtEnd()&&!e.check(")");)if(r.push(kr(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),r.length>0){const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(mr(r.map(e=>({key:e.name?ur(e.name,i):lr("_positional","_positional",i),value:e.value})),i))}}return Sr.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let i=null,o=null;const s=e.peek();if(e.checkAnySelector()||e.checkContextVar()||e.check("<")||_n(s)&&Rr.has(s.value)){const t=e.parsePrimary();("possessiveExpression"===t.type||"memberExpression"===t.type&&!t.computed)&&t.object&&t.property?.name?(o=t.object,i={type:"string",value:t.property.name,start:s.start||0,end:e.getPosition().end,line:s.line,column:s.column}):(o=t,e.check("'s")&&e.advance())}const a=e.peek();if(!i&&(_n(a)||"*"===a.value)){let t="";e.check("*")&&(t="*",e.advance());const n=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);n&&(t+=n,i={type:"string",value:t,start:a.start||0,end:e.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),!e.check(g))throw Error('Expected "to" keyword after property in transition command');e.advance();const c=e.parseExpression();if(r.to=c,e.check("over")){e.advance();const t=e.parseExpression();r.over=t}if(e.check(w)){e.advance();const t=e.parsePrimary();r.with=t}return Sr.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return Pr(this.getContext(),e)}parseIfCommand(e){return Or(this.getContext(),e)}parseRemoveCommand(e){return Ir(this.getContext(),e)}parseToggleCommand(e){return qr(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("?.")){const t=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(e,this.createIdentifier(t.value),!1);n.optional=!0,e=n}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}else{if(!this.check("'s"))break;{let t;this.advance(),this.check("*")?(this.advance(),t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):Gn(this.peek())&&this.peek().value.startsWith("@")?t=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),t=this.advance().value,this.consume("]","Expected ']' after attribute reference")):t=this.consumeIdentifierLike("Expected property name after possessive").value,e=this.createPossessiveExpression(e,this.createIdentifier(t))}}return e}parsePrimary(){if(this.check("*")){const e=this.current;if(this.advance(),!this.isAtEnd()&&_n(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),n=this.processEscapeSequences(t);return this.createLiteral(n,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value,t=e.slice(1,-2).trim(),n=this.createSelector(t);return n.fromQuery=!0,n.raw=e,n}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column-2}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end,line:e.line,column:e.column-1}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if((!e||"end"!==e.value&&"else"!==e.value&&"then"!==e.value)&&(this.matchPredicate(Yn)||this.matchPredicate(Vn)||this.matchPredicate(Dn)||this.matchPredicate(Bn)||this.matchPredicate(Fn))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,n=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[n])}this.current=t}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(e.value):this.parseNavigationFunction(e.value)}const t=this.check(".")||this.check("?.");return"my"!==e.value||t?"its"!==e.value||t?"your"!==e.value||t?"the"===e.value?this.parseTheXofY():"values"===e.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:e.line,column:e.column}):this.createIdentifier(e.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Gn(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const e=this.peek().start;this.advance();const t=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}t.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:t,body:this.parseExpression(),start:e,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),this.createErrorNode())}parseDollarExpression(){if(this.checkNumber()){const e=this.advance().value;return this.createLiteral(e,"$"+e)}if(this.checkIdentifier()){const e=this.advance();let t=this.createIdentifier(e.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const e=this.advance();t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}}return t}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.check("["))this.advance(),t=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const e=this.previous().value,n=e.slice(1,-1);t=this.createLiteral(n,e)}else{if(!this.check("-")&&!this.checkPredicate(Yn))return this.addError("Expected property name in object literal"),this.createErrorNode();{let e="",n=!1;for(;this.check("-");)this.advance(),e+="-",n=!0;for(this.checkPredicate(Yn)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",n=!0,this.checkPredicate(Yn)&&(e+=this.advance().value);if(""===e||"-"===e)return this.addError("Expected property name in object literal"),this.createErrorNode();t=n?this.createLiteral(e,e):this.createIdentifier(e)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(e.push({key:t,value:n}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let n;if(this.matchPredicate(Yn))n=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);n=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,o=0,s=-1,a=-1;for(;!this.isAtEnd()&&(0!==o||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),0>s&&"number"==typeof e.start&&(s=e.start),"number"==typeof e.end&&(a=e.end),"$"===e.value&&this.check("{")&&(i=!0),"{"===e.value&&o++,"}"===e.value&&o--}const c=this.originalInput&&s>=0&&a>s?this.originalInput.slice(s,a):r.join(""),l=i?{type:"templateLiteral",value:c,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(c,c);if(t.push({key:n,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),n=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:t.start,end:t.end,line:t.line,column:t.column},arguments:r,isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:i,errorHandler:o,finallyHandler:s}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==o&&{errorHandler:o},...void 0!==s&&{finallyHandler:s},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseErrorAndFinallyBlocks(){let e,t,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(e=this.advance().value),t=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==e&&{errorSymbol:e},...void 0!==t&&{errorHandler:t},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,i){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==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(e,t){const n=e.callee.name,r=this.peek();if(!(wi.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Yn(r)&&!this.isCommand(r.value)||Dn(r)))return{node:this.callExprToCommandNode(e,t),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!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),wi.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{o=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,i,o,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(Hn("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return Hn("\u26a0\ufe0f Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=e,null}}parseTemporalKeywordModifiers(e){if(!this.check("debounced")&&!this.check("throttled"))return;const t=this.advance().value.toLowerCase(),n="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const i=this.advance(),o=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):r.endsWith("s")?1e3*parseFloat(r):parseInt(r,10);e[n]=o,Hn(`\ud83d\udd27 parseEventHandler: Parsed '${t} at ${i.value}' (${o}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);e[n]=r,Hn(`\ud83d\udd27 parseEventHandler: Parsed '${t} at ${r}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`);var r}parseEventHandler(){Hn("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const e=[];let t=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const e=this.tokens[this.current+1],n=e?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),t=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),Hn("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),Hn("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),Hn("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+t)}let r;if(Hn("\ud83d\udd27 parseEventHandler: Total events parsed: "+e.join(", ")),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);r=e?.name,Hn(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${t}'`)}}const i=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();i.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),Hn("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const o={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)o.once=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)o.prevent=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)o.stop=!0,Hn("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),n=parseInt(t.value,10);if(isNaN(n))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?(o.debounce=n,Hn(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(o.throttle=n,Hn(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else Hn(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${e}'`)}let s,a,c,l;if(this.parseTemporalKeywordModifiers(o),t&&(o.once=!0),Object.keys(o).length>0&&Hn("\ud83d\udd27 parseEventHandler: Parsed modifiers:",o),this.match("[")&&(s=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();a=e.value,Hn(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${e.kind})`),this.parseTemporalKeywordModifiers(o)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value,Hn("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(Hn("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),Hn("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(Hn(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(Hn(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){Hn("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment()){Hn("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();continue}if(this.check("end")){Hn("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){Hn(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const n=this.parseCommand();u.push(n);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.peek().value,t=this.parseCommandWithErrorRecovery();t?(u.push(t),Hn("\u2705 parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value))):this.recordDropped(`Command '${e}' failed to parse and was discarded`)}}else{if(!this.checkIdentifier()){this.isAtEnd()||this.check("end")||this.check("catch")||this.check("finally")||this.recordDropped(`Not a command, and the rest of the handler body was discarded: '${this.peek().value}'`);break}{const e=this.peek();if(this.isCommand(e.value)){const t=this.parseCommandWithErrorRecovery();t?u.push(t):this.recordDropped(`Command '${e.value}' failed to parse and was discarded`)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){Hn("\u26a0\ufe0f Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator){this.recordDroppedExpression(e);break}{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name)){this.recordDroppedExpression(e);break}{const n={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};u.push(n)}}}}}}const e=this.current;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.recordDroppedRange(e,this.current),!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===e.length?e[0]:e.join("|"),events:e,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 Hn(`\ud83d\udd27 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),p}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const i=new Set(r),o=[];let s;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();Yn(e)?(r.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let s;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),n=i.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),s=t.value,this.advance())}}const{commands:a,terminator:c}=this.parseCommandListUntilTerminator(["catch","finally"]);let l,u,f;if("catch"!==c&&"finally"!==c||({errorSymbol:l,errorHandler:u,finallyHandler:f}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const d={type:"eventHandler",event:t,commands:n(a),...void 0!==l&&{errorSymbol:l},...void 0!==u&&{errorHandler:n(u)},...void 0!==f&&{finallyHandler:n(f)},...void 0!==s&&{target:s},...r.length>0&&{args:r},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};o.push(d)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}s={type:"initBlock",commands:n(this.parseCommandBlock(["end"])),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:r,eventHandlers:o,...void 0!==s?{initBlock:s}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,n=this.parseCommand();for(this.error&&this.error!==t&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(Hn("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=t)),e.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)Hn("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){Hn('\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 t=this.peek(),n=this.getPosition(),r="Expected command, got: "+t.value;this.addError(r);const i=br(n,r,t.value);if(e.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===e.length?e[0]:function(e){return{type:"CommandSequence",commands:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1}}(e)}isTokenKeyword(e,t){return gr(e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();if(t.push(e),this.match("then","and",","))continue}}return t}parseCommand(){const e=this.parseCommandCore();if(e&&"command"===e.type&&!e.body&&(this.check("when")||this.check("where"))){const t=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(e.modifiers={...e.modifiers??{},[t]:n})}return e}parseCommandCore(){const e=this.previous();let n=e.value;if("beep"===n&&this.check("!")&&(this.advance(),n="beep!"),"fetch"===n)return function(e,n){const r={};let i=null;if(!e.isAtEnd()&&ai(e)&&(i=li(e)),i||(i=e.parsePrimary()),!i)return e.addError("fetch requires a URL"),Sr.from(n).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(r.with=e.parsePrimary());for(let n=0;3>n&&!e.isAtEnd();n++)if(!e.check("as")||r.as){if(!e.check("with")||r.with){if(e.check("do")&&!r.doNotThrow){const n=e.peekAt(1),i=e.peekAt(2);if("not"===n?.value&&"throw"===i?.value){const n=e.advance();e.advance();const i=e.advance();r.doNotThrow=t({type:"literal",value:!0,start:n.start,end:i.end,line:n.line,column:n.column});continue}}break}e.advance(),r.with=ui(e)?fi(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||xr(e,"a")||xr(e,"an"),r.as=e.parsePrimary();const o=Sr.from(n).withArgs(i).endingAt(e.getPosition());return Object.keys(r).length>0&&o.withModifiers(r),o.build()}(this.getContext(),e);const r=n.toLowerCase();return"repeat"===r?this.parseRepeatCommand(e):"for"===r?this.parseForCommand(e):"if"===r||"unless"===r?this.parseIfCommand(e):"wait"===r?this.parseWaitCommand(e):"install"===r?this.parseInstallCommand(e):"transition"===r?this.parseTransitionCommand(e):"add"===r?this.parseAddCommand(e):this.isCompoundCommand(r)?this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||{type:"command",name:r,args:[],partial:!0,start:(i=this.getPosition()).start,end:i.end,line:i.line,column:i.column}:"increment"!==n&&"decrement"!==n||this.isAtEnd()?ti(this.getContext(),e,n,bi(n)??yi):function(e,t){const n=t.value,r="increment"===n?"+":"-";let i=!1;e.check(T)&&(i=!0,e.advance());const o=e.parseExpression();if(!o)throw Error("Expected variable or expression after "+n);let s;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);s=t}else s=lr(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let a=o;i&&"identifier"===o.type&&(a={...o,scope:"global"});const c=fr(r,o,s,{start:t.start,end:e.previous().end,line:t.line,column:t.column});return c.coerceNumeric=!0,Sr.from(t).withName("set").withArgs(a).withModifier("to",c).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(this.getContext(),e);var i}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=this.getPosition(),n=[];if(this.match("of"))n.push(this.parseExpression());else{if(this.check("("))return this.finishCall(ur(e,t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||n.push(this.parsePrimary())}const r=this.createCallExpression(ur(e,t),n);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(r.relativePositional=e)}return r}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let e,t,n,r=!1,i=!1;return this.match("from")&&(e=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(t=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=!0),{from:e,within:t,inElt:n,inSearch:r,wrapping:i}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;return["first","last","next","previous","random","closest"].includes(t)?(this.advance(),this.parseNavigationFunction(t)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parseCall(),line:e.line,column:e.column}):this.createIdentifier(t))}parseContextPropertyAccess(e){const t=this.getPosition(),n=()=>ur(e,t);if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(n(),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 t="*"+e;return this.createMemberExpression(n(),this.createIdentifier(t),!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(n(),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Gn(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(n(),this.createIdentifier(e.value),!1)}const t=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(n(),this.createIdentifier(t.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;I(t)&&Hn(`\ud83d\udca1 Tip: CSS functions like ${t}() should be quoted for clean parsing. Use '${t}(...)' or \`${t}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return lr(e,t,this.getPosition())}createIdentifier(e){return ur(e,this.getPosition())}createBinaryExpression(e,t,n){return fr(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}spanFromLeftmost(e){const t=this.getPosition(),n=e?.start;return"number"==typeof n&&t.start>n?this.originalInput?{...wt(this.originalInput,n),start:n,end:t.end}:{...t,start:n}:t}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.spanFromLeftmost(e))}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.spanFromLeftmost(e))}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.spanFromLeftmost(e))}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(Hn(`\u2705 createProgramNode: Called with ${e.length} statements`),0===e.length)return Hn("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return Hn(`\u2705 createProgramNode: Returning single statement (type=${e[0].type})`),e[0];const t={type:"Program",statements:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1};return Hn(`\u2705 createProgramNode: Returning Program node with ${e.length} statements, type=${t.type}`),t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!ar(t)||t.value!==e||(this.advance(),0))}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Wn)}matchSelector(){return this.matchPredicate(Wn)}checkAnySelector(){return this.checkPredicate(zn)}checkLiteral(){return this.checkPredicate(Zn)}checkIdentifierLike(){return this.checkPredicate(_n)}checkIsCommand(){return this.checkPredicate(Bn)}checkCommandTerminator(){return this.checkPredicate(cr)}checkReference(){return this.checkPredicate(Jn)}checkTimeExpression(){return this.checkPredicate(Kn)}checkEvent(){return this.checkPredicate(Fn)}checkContextVar(){return this.checkPredicate(Dn)}checkComment(){return this.checkPredicate(Xn)}checkIdentifier(){return this.checkPredicate(Yn)}checkKeyword(){return this.checkPredicate(Vn)}checkString(){return this.checkPredicate(Qn)}matchString(){return this.matchPredicate(Qn)}checkNumber(){return this.checkPredicate(er)}matchNumber(){return this.matchPredicate(er)}checkBoolean(){return this.checkPredicate(tr)}matchBoolean(){return this.matchPredicate(tr)}checkTemplateLiteral(){return this.checkPredicate(nr)}matchTemplateLiteral(){return this.matchPredicate(nr)}checkQueryReference(){return this.checkPredicate(rr)}matchQueryReference(){return this.matchPredicate(rr)}checkIdSelector(){return this.checkPredicate(ir)}checkClassSelector(){return this.checkPredicate(or)}checkCssSelector(){return this.checkPredicate(sr)}checkBasicOperator(){return this.checkPredicate(ar)}matchBasicOperator(){return this.matchPredicate(ar)}matchTimeExpression(){return this.matchPredicate(Kn)}matchIdentifierLike(){return this.matchPredicate(_n)}matchComparisonOperator(){return this.matchPredicate(Un)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(Yn,e)}consumeIdentifierLike(e){return this.consumePredicate(_n,e)}consumeEvent(e){return this.consumePredicate(Fn,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(e){const t=this.current+e;return t>=0&&this.tokens.length>t?this.tokens[t]:null}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let n=t.start||0,r=t.line||1,i=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,i=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;n=e.end||e.start||0,r=e.line||1,i=e.column||1,0===n&&this.current>0&&(n=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;n=e.start||0,r=e.line||1,i=e.column||1,0===n&&(n=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const n=this.tokens[t];if(n&&("+"===n.value||"-"===n.value)){e=n;break}}n=e.start||0,r=e.line||1,i=e.column||1}this.error={message:e,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)},this.errors.push(this.error)}recordDroppedRange(e,t){const n=this.tokens.slice(e,t).filter(e=>!Xn(e)&&"end"!==e.value);0!==n.length&&this.recordDropped(`Discarded input the parser could not place: '${n.map(e=>e.value).join(" ")}'`)}recordDropped(e){const t=this.peek();this.errors.push({message:e,line:Math.max(1,t.line||1),column:Math.max(1,t.column||1),position:Math.max(0,t.start||0)})}recordDroppedExpression(e){this.recordDropped("Not a command, and the rest of the handler body was discarded: "+(e&&"string"==typeof e.name?`'${e.name}'`:"a "+(e?.type??"expression")))}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const e=this.peek();if("then"===e.value||"end"===e.value||"on"===e.value)return;if(this.checkIsCommand()||this.isCommand(e.value)&&!this.isKeyword(e.value))return;Hn("\u26a0\ufe0f synchronize: Skipping token:",e.value),this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();r.push(e.value)}this.consume("]","Expected ']' after attribute literal");const i=r.join("");if(!i.includes("="))return{type:"attributeAccess",attributeName:i.replace(/^@/,""),start:e,end:this.previous().end,line:t,column:n};const o="["+i+"]";return{type:"literal",value:o,raw:o,start:e,end:this.previous().end,line:t,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 e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const 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:e,end:this.previous().end,line:t,column:n}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isKeyword:this.isKeyword.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>e.peekAt(t),getInputSlice:(e,t)=>this.originalInput?0>e||e>=this.originalInput.length?"":void 0!==t?this.originalInput.slice(e,t):this.originalInput.slice(e):""};return Object.defineProperty(t,"current",{get:()=>e.current,set:t=>{e.current=t},enumerable:!0,configurable:!0}),t}}function Ei(e,t){const n=function(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const n=e.length;for(;n>t.position&&(gt(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==yt(t,1))if('"'!==n){if("'"===n||"'"===n){const e=yt(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||/\s/.test(t.input[t.position-1]??" ")||n.kind!==ht.IDENTIFIER&&n.kind!==ht.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)kt(t);else{const e=t.position;bt(t),bt(t),vt(t,ht.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===yt(t,1)){const e=t.position;bt(t),bt(t),vt(t,ht.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=e&&e.kind===ht.IDENTIFIER&&$.has(e.value.toLowerCase()),i=e&&e.kind===ht.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===ht.OPERATOR&&")"!==e.value&&"]"!==e.value||r||i||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(Rt(yt(t))||"{"===yt(t)||"-"===yt(t))){Tt(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===ht.IDENTIFIER&&V.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==ht.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(bt(t),vt(t,ht.SYMBOL,"[")):(bt(t),vt(t,ht.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const e=yt(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){Nt(t);continue}}qt(n)?$t(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(vt(t,ht.UNKNOWN,n),bt(t)):Ot(t):jt(t)}else bt(t),vt(t,ht.OPERATOR,"]")}else bt(t),vt(t,ht.OPERATOR,"}");else bt(t),vt(t,ht.OPERATOR,"{");else Ct(t)}else Tt(t);else It(t)?At(t):$t(t);else St(t)}else kt(t);else xt(t)}return t.tokens}(e);return new wi(n,t,e).parse()}function xi(e,t){const n=e.registry?.get(t);if(!n)throw Error(`Expression '${t}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function ki(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}wi.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),wi.PRATT_TABLE=J,wi.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];const Si=new Set(["literal","string","identifier","selector","attributeAccess","binaryExpression","unaryExpression","callExpression","memberExpression","possessiveExpression","propertyOfExpression","arrayLiteral","objectLiteral","templateLiteral","asExpression","betweenExpression","typeCheckExpression","collectionExpression","conditionalExpression","stringPostfix","blockLiteral","propertyAccess","contextReference","eventHandler"]);async function Ti(e,t){switch(e.type){case"literal":return function(e){return e.value}(e);case"identifier":return Mi(e,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,i=e.left;if("="===n){const n=await Ai(e.right,t);if("identifier"===i?.type&&"string"==typeof i.name){const e=i.name;return e.startsWith("$")?re(t,e.slice(1),n):"global"===i.scope?re(t,e,n):"element"===i.scope?me(t,e,n):(t.locals||(t.locals=new Map),t.locals.set(e,n)),n}throw Error(`Assignment target must be a variable identifier (got '${i?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await Ai(e.left,t);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===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 Ai(e.right,t);if(i&&"function"==typeof i.querySelectorAll){const e=Array.from(i.querySelectorAll(r.value));return 0===e.length?null:"first"===n?e[0]:e[e.length-1]}}}if("selector"===i?.type&&i.fromQuery&&"string"==typeof i.value){const n=await Ai(e.right,t),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 Ai(e.right,t);return xi(t,"styleRef").evaluate(t,i.value.slice(1),n)}if("of"===n){const n=Ii(e.left);if(n){const r=await Ai(e.right,t);let i=r;for(const e of n){if(null==i)return;i=Me(i)?Be(i,e):i[e]}return"function"==typeof i?i.bind(r):i}}const o=await Ai(e.left,t);if("and"===n){if(!o)return o;const n=await Ai(e.right,t);return xi(t,"and").evaluate(t,o,n)}if("or"===n){if(o)return o;const n=await Ai(e.right,t);return xi(t,"or").evaluate(t,o,n)}const s=await Ai(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(o):o,l=e.ignoringCase?a(s):s;switch(n){case"+":{let n=o,r=s;return e.coerceNumeric&&("string"==typeof n&&(n=we(n)),"string"==typeof r&&(r=we(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:ki(await xi(t,"addition").evaluate(t,{left:n,right:r}))}case"-":return ki(await xi(t,"subtraction").evaluate(t,{left:o,right:s}));case"*":return ki(await xi(t,"multiplication").evaluate(t,{left:o,right:s}));case"/":return ki(await xi(t,"division").evaluate(t,{left:o,right:s}));case"%":case"mod":return ki(await xi(t,"modulo").evaluate(t,{left:o,right:s}));case"^":case"**":return ki(await xi(t,"power").evaluate(t,{left:o,right:s}));case">":case"is greater than":return xi(t,"greaterThan").evaluate(t,o,s);case"<":case"is less than":return xi(t,"lessThan").evaluate(t,o,s);case">=":case"is greater than or equal to":return xi(t,"greaterThanOrEqual").evaluate(t,o,s);case"<=":case"is less than or equal to":return xi(t,"lessThanOrEqual").evaluate(t,o,s);case"==":return xi(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=Pi(e,o,s);return void 0!==n?n:xi(t,"equals").evaluate(t,c,l)}case"!=":return xi(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const n=Pi(e,o,s);return void 0!==n?!n:xi(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return xi(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return xi(t,"strictNotEquals").evaluate(t,c,l);case"as":return xi(t,"as").evaluate(t,o,Vi(s));case"contains":case"contain":case"includes":case"include":return xi(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return xi(t,"doesNotContain").evaluate(t,c,l);case"starts with":return xi(t,"startsWith").evaluate(t,c,l);case"ends with":return xi(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await xi(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await xi(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return xi(t,"matches").evaluate(t,c,Hi(e.right,l));case"does not match":case"do not match":return!await xi(t,"matches").evaluate(t,c,Hi(e.right,l));case"in":case"is in":case"am in":return qi(o,s);case"is not in":case"am not in":return!qi(o,s);case"of":return s&&"object"==typeof s?s[o]:void 0;case"precedes":return Bi(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!Bi(o,s,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return Bi(o,s,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!Bi(o,s,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(e,t);case"asExpression":return async function(e,t){const n=await Ai(e.expression,t),r=Vi(e.targetType);return xi(t,"as").evaluate(t,n,r)}(e,t);case"betweenExpression":return async function(e,t){const n=await Ai(e.value,t),r=await Ai(e.min,t),i=await Ai(e.max,t),o=e=>"string"==typeof e?e.toLowerCase():e,[s,a,c]=e.ignoringCase?[o(n),o(r),o(i)]:[n,r,i],l=await Sn.between.evaluate(t,s,a,c);return e.negated?!l:l}(e,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await Ai(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(e,t);case"collectionExpression":return async function(e,t){const n=await Ai(e.collection,t);if(null==n)return n;const r=async(e,n)=>Ai(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=jn(e),i=[];for(const e of r)await n(t,e)&&i.push(e);return i}(n,e.right,r);case"sorted by":return async function(e,t,n,r){const i=[...jn(e)],o=await Promise.all(i.map(e=>r(t,e))),s=i.map((e,t)=>t);s.sort((e,t)=>{const n=o[e],r=o[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=s.map(e=>i[e]);return"desc"===n?a.reverse():a}(n,e.right,e.order??"asc",r);case"mapped to":return async function(e,t,n){const r=jn(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return o=await Ai(e.right,t),null==(i=n)?[]:(i+"").split(null==o?"":o+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return jn(e).map(e=>null==e?"":e+"").join(n)}(n,await Ai(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var i,o}(e,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await Ai(n,t);switch(e.operator){case"not":case"!":return Sn.not.evaluate(t,r);case"no":return Sn.no.evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return Sn.exists.evaluate(t,r);case"does not exist":return Sn.doesNotExist.evaluate(t,r);case"is empty":return Sn.isEmpty.evaluate(t,r);case"is not empty":return Sn.isNotEmpty.evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(e,t);case"memberExpression":return async function(e,t){const n=await Ai(e.object,t);if(e.computed){const r=await Ai(e.property,t);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return _i(n,e.property.name,t)}(e,t);case"propertyAccess":return async function(e,t){let n=await Ai(e.object,t);for(const r of(e.property+"").split(".")){if(null==n)return;n=await _i(n,r,t)}return n}(e,t);case"callExpression":return async function(e,t){const n=await Ai(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>Ai(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,i=await async function(e,t,n){return zi.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:Ai(e,n))):Promise.all(e.map(e=>Ai(e,n)))}(e.arguments,r,t);switch(r){case"closest":return tt.closest.evaluate(t,...i);case"previous":case"next":{const n=e.relativePositional;if(n){const e=n.from?Wi(await Ai(n.from,t)):t.me,o=n.within?Wi(await Ai(n.within,t)):void 0,s=n.inElt?await Ai(n.inElt,t):void 0;return xi(t,r).evaluate(t,i[0],e,{within:o,inElt:s,inSearch:n.inSearch,wrapping:n.wrapping})}return xi(t,r).evaluate(t,...i)}case"first":return xi(t,"first").evaluate(t,...i);case"last":return xi(t,"last").evaluate(t,...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(e.arguments.map(e=>Ai(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const i=await Ai(e.callee.object,t);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(e,t);case"selector":return async function(e,t){let n=e.value;if("string"==typeof n&&!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return tt.styleRef.evaluate(t,n.slice(1));if("string"==typeof n&&e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=await async function(e,t){const n=Xi(e),r=await Promise.all(n.filter(e=>"expr"in e).map(e=>Ni(e.expr,t)));return Yi(n,r)}(n,t),o=Ki(e,r);i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await tt.elementWithSelector.evaluate(t,o)}finally{i.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!e.fromQuery&&n.includes("{")&&(n=await function(e,t){return Ui(e,/\{([^}]*)\}/g,async(e,n)=>(await Ni(n.trim(),t)??"")+"")}(n,t));const r="string"==typeof n?Ki(e,n):n;return Se(await tt.elementWithSelector.evaluate(t,r),n,e.fromQuery)}(e,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return xi(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return tt.me.evaluate(t);case"your":case"yourself":return tt.you.evaluate(t);case"its":return tt.it.evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??tt.me.evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return tt.document.evaluate(t);case"window":return tt.window.evaluate(t);default:return}}(e,t);case"possessiveExpression":return async function(e,t){const n=await Ai(e.object,t),r=e.property.name;return xi(t,"possessive").evaluate(t,n,r)}(e,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await Ai(t,r)}}}(e,t);case"conditionalExpression":return async function(e,t){return await Ai(e.test,t)?Ai(e.consequent,t):e.alternate?Ai(e.alternate,t):void 0}(e,t);case"string":return e.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await Ai(r,t));return n}(e,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let i;i="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await Ai(e,t)+"",n[i]=await Ai(r.value,t)}return n}(e,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(e,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await Ai(e.target,t);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return xi(t,"possessive").evaluate(t,i,r)}(e,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await Ui(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const e=n.split(".");let r=Di(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(Di(n,t)??"")+""}catch{return""}}),n=await Ui(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const i=n||r;try{return await Ni(i,t)+""}catch{return"undefined"}}),n}(e,t);case"stringPostfix":return async function(e,t){return`${await Ai(e.expression,t)}${e.unit}`}(e,t);case"blockLiteral":return Fi(e,t);default:throw Error("Unhandled evaluable AST node type: "+e.type)}}async function Ai(e,t){if(!e)throw Error("Cannot evaluate null or undefined AST node");if("literal"===e.type)return e.value;if("identifier"===e.type)return Mi(e,t);if(Si.has(e.type))return Ti(e,t);const n=oe.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}class Ci extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}const $i=new Set(["literal","string","selector","identifier","contextReference","arrayLiteral","objectLiteral","asExpression","stringPostfix","blockLiteral","memberExpression"]);function ji(e,t){const n=e?.type;if("string"==typeof n&&$i.has(n))return function(e,t){switch(e.type){case"literal":case"string":return e.value;case"selector":return function(e,t){const n=e.value;if("string"!=typeof n)throw new Ci("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new Ci("selector");if(e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(e,t){const n=Xi(e),r=n.filter(e=>"expr"in e).map(e=>Oi(e.expr,t));return Yi(n,r)}(n,t),o=Ki(e,r),s=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new Ci("selector");i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(s.querySelectorAll(o))}finally{i.forEach(e=>e.removeAttribute("data-hs-query-id"))}}const r=!e.fromQuery&&n.includes("{")?function(e,t){return e.replace(/\{([^}]*)\}/g,(e,n)=>(Oi(n.trim(),t)??"")+"")}(n,t):n,i=Ki(e,r),o=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new Ci("selector");return Se(Array.from(o.querySelectorAll(i)),r,e.fromQuery)}(e,t);case"identifier":return function(e,t,n){return"me"===e||"my"===e||"I"===e?t.me:"you"===e||"your"===e||"yourself"===e?t.you:"it"===e||"its"===e?t.it??t.result:"result"===e?t.result??t.it:"window"===e?"undefined"!=typeof window?window:globalThis:"document"===e?"undefined"!=typeof document?document:void 0:"element"===n?he(t,e):t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):e.startsWith("$")&&t.globals?.has(e.slice(1))?t.globals.get(e.slice(1)):"body"===e&&"undefined"!=typeof document?document.body:"detail"===e?t.event?.detail??null:"sender"===e?t.event?.detail?.sender??null:void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(e.name,t,e.scope);case"contextReference":return function(e,t){switch(e){case"me":return t.me;case"you":return t.you;case"it":return t.it??t.result;case"event":return t.event;case"target":return t.target??t.event?.target??t.me;default:throw new Ci("contextReference")}}(e.contextType,t);case"arrayLiteral":return e.elements.map(e=>ji(e,t));case"objectLiteral":return function(e,t){const n={};for(const r of e.properties){const e=r.key;let i;i="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value+"":ji(e,t)+"",n[i]=ji(r.value,t)}return n}(e,t);case"asExpression":return Ye(ji(e.expression,t),Vi(e.targetType),t);case"stringPostfix":return`${ji(e.expression,t)}${e.unit}`;case"blockLiteral":return Fi(e,t);case"memberExpression":{const n=ji(e.object,t);if(null==n)return;if(n instanceof Element||Array.isArray(n)||"undefined"!=typeof Node&&n instanceof Node)throw new Ci("memberExpression");const r=n[e.computed?ji(e.property,t)+"":e.property.name];return"function"==typeof r?r.bind(n):r}default:throw new Ci((e.type??"unknown")+"")}}(e,t);throw new Ci("string"==typeof n?n:"unknown")}function Oi(e,t){const n=Ei(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return ji(n.node,t)}async function Ni(e,t){const n=Ei(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const r=t.registry?t:{...t,registry:await Li()};return Ai(n.node,r)}let Ri=null;async function Li(){if(!Ri){const e=await Promise.resolve().then(function(){return Ro});Ri=e.createFullExpressionRegistry()}return Ri}async function Mi(e,t){const n=e.name;return n.startsWith("$")?ee(n.slice(1),t):"global"===e.scope&&ee(n,t),"me"===n||"my"===n||"I"===n?tt.me.evaluate(t):"you"===n||"your"===n||"yourself"===n?tt.you.evaluate(t):"it"===n||"its"===n?tt.it.evaluate(t):"result"===n?tt.result.evaluate(t):"window"===n?tt.window.evaluate(t):"document"===n?tt.document.evaluate(t):"global"===e.scope&&t.globals?.has(n)?t.globals.get(n):"element"===e.scope?he(t,n):t.locals&&t.locals.has(n)?(ne(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?t.globals.get(n):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?t.globals.get(n.slice(1)):"body"===n&&"undefined"!=typeof document?document.body:"detail"===n?t.event?.detail??null:"sender"===n?t.event?.detail?.sender??null:void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function Ii(e){const t=e;if(!t)return null;if("identifier"===t.type&&"string"==typeof t.name)return[t.name];if("memberExpression"===t.type&&!t.computed){const e=Ii(t.object);if(!e)return null;const n=t.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...e,r]}return null}function qi(e,t){return Array.isArray(t)?t.includes(e):"string"==typeof t?t.includes(e+""):e instanceof Node&&t instanceof Node?e===t||t.contains(e):null!=t&&"object"==typeof t&&e in t}function Hi(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function Pi(e,t,n){if(void 0!==n)return;const r=e.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==t||"object"!=typeof t)return;const i=t[r.name];return"boolean"==typeof i?!0===i:void 0}function Bi(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function Vi(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e+""}function Fi(e,t){const n=e.parameters??[];return(...r)=>{const i=new Map(t.locals??new Map);n.forEach((e,t)=>i.set(e,r[t]));const o={...t,locals:i};try{return ji(e.body,o)}catch(t){if(t instanceof Ci)return Ai(e.body,o);throw t}}}function Di(e,t){if(t.locals?.has(e))return ne(e,t),t.locals.get(e);if("me"===e&&t.me)return t.me;if("you"===e&&t.you)return t.you;if("it"===e){const e=t.it??t.result;if(e)return e}if("result"===e){const e=t.result??t.it;if(e)return e}return"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function Ui(e,t,n){const r=[];let i;for(;null!==(i=t.exec(e));)r.push({index:i.index,length:i[0].length,replacement:await n(i[0],...i.slice(1))});let o=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:i}=r[e];o=o.substring(0,t)+i+o.substring(t+n)}return o}function _i(e,t,n){if("string"==typeof t&&t.startsWith("@")){const n=t.substring(1);return e&&"function"==typeof e.getAttribute?e.getAttribute(n):void 0}return e instanceof Element&&"string"==typeof t?Be(e,t):Cn(e)&&!(t in e)?xi(n,"possessive").evaluate(n,e,t):e?.[t]}const zi=new Set(["closest","previous","next"]);function Wi(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const Zi=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"),Ji=/[:&()[\]/]/g;function Ki(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace(Zi,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(Ji,"\\$&")}(t)}const Gi=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Xi(e){const t=[];let n,r=0;for(Gi.lastIndex=0;null!==(n=Gi.exec(e));)n.index>r&&t.push({lit:e.slice(r,n.index)}),t.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return e.length>r&&t.push({lit:e.slice(r)}),t}function Yi(e,t){let n="";const r=[];let i=0;for(const o of e){if("lit"in o){n+=o.lit;continue}const e=t[i++];Me(e)?(n+=`[data-hs-query-id='${r.length}']`,r.push(e)):n+=(e??"")+""}return{selector:n,elements:r}}class Qi{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,n,r,i){this.addCleanup(e,{type:"listener",target:t,eventName:n,cleanup:()=>{t.removeEventListener(n,r,i),this.debugMode&&Pn(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&Pn("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&Pn("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&Pn("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,n){this.addCleanup(e,{type:"custom",cleanup:t,description:n||"Custom cleanup"})}registerGlobal(e,t="custom",n){this.globalCleanups.push({type:t,cleanup:e,description:n||"Global cleanup"}),this.debugMode&&Pn("CleanupRegistry: Registered global cleanup: "+(n||t))}addCleanup(e,t){const n=this.elementCleanups.get(e);n?n.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&Pn(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let n=0;for(const e of t){try{e.cleanup(),n++}catch(e){this.debugMode&&Pn("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&Pn(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(e){let t=this.cleanupElement(e);const n=e.querySelectorAll("*");for(const e of n)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&Pn("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&Pn(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,n=0,r=0,i=0;for(const o of this.globalCleanups)switch(o.type){case"listener":e++;break;case"observer":t++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}class eo{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&Pn("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(n,t)}unregister(e){const t=e.toLowerCase(),n=this.sources.get(t);if(n){for(const[e,n]of this.subscriptions.entries())n.source===t&&(n.unsubscribe(),this.subscriptions.delete(e));return n.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,n){const r=this.get(e);if(!r)return void Pn("[EventSourceRegistry] Unknown event source: "+e);r.initialize?.();const i=r.subscribe(t,n);return this.subscriptions.set(i.id,i),i}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,n]of this.sources.entries())if(n.supports?.(e)??n.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}const to={evaluate:(e,t)=>Ai(e,t)};class no{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:"string"==typeof e?e:e?e.join(" | "):""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(In(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void In(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.variables||(e.variables=new Map);const i=e;let o,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(In(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!this.impl.ownsConditionalModifier&&!await Ai(r,e))return void In(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);o=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName,bodies:n.bodies},to,e)}else o=t;else In(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),o=t;if(In("CommandAdapterV2: Calling execute with parsed input:",o),2===this.impl.execute.length)s=await this.impl.execute(o,i);else{const e=Array.isArray(o)?o:[o];s=await this.impl.execute(i,...e)}return In("CommandAdapterV2: Command result:",s),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,s),s}catch(e){if(In(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return{isValid:!this.impl.validate||this.impl.validate(e),errors:[],suggestions:[]}}}class ro{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);Pn(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const n=t.toLowerCase();Pn(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new no(e,void 0,this.hookRegistry);this.adapters.set(n,r),$.add(n);const i=e.metadata?.aliases;if(i&&Array.isArray(i))for(const t of i){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,r),$.add(n)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const n=this.getAdapter(e);return n?n.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let io=null;function oo(){return io||(io=function(e){const t=e?.commands??new ro,n=e?.eventSources??new eo,r=new Set,i={commands:t,eventSources:n,use(e){if(r.has(e.name))Pn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);e.setup?.(i),r.add(e.name)}},reset(){r.clear()}};return i}()),io}class so{constructor(e={}){const t=oo();this.options={enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,Pn(`[RegistryIntegration] Initialized (events=${this.options.enableEventSources})`)}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return Pn(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return Pn(`[RegistryIntegration] Found event source '${n}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(e,t,n);if(!r)throw Error(`Failed to subscribe to event source '${e}'`);return Pn(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}destroy(){this.eventSourceRegistry.destroy(),Pn("[RegistryIntegration] Destroyed")}}class ao extends Error{constructor(e){super(`'${e.type}' used outside of a loop`),this.signal=e,this.name="StrayControlFlowError"}}function co(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const lo=new WeakMap;function uo(e,t=new Set){if(null===e||"object"!=typeof e)return t;if(Array.isArray(e)){for(const n of e)uo(n,t);return t}const n=e;"identifier"===n.type&&"string"==typeof n.name&&t.add(n.name);for(const e of Object.keys(n))"start"!==e&&"end"!==e&&"line"!==e&&"column"!==e&&uo(n[e],t);return t}class fo{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.ops=new WeakMap,this.options={commandTimeout:1e4,enableErrorReporting:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=le,this.hookRegistry=new r,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Qi,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new so("object"==typeof e.registryIntegration?e.registryIntegration:{}),Pn("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,n)=>await this.installBehaviorOnElement(e,t,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const n of e)for(const e of n.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&Pn(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}trackListener(e,t,n,r,i){this.cleanupRegistry.registerListener(e,t,n,r,i)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),Pn("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){const n=await this.executeNode(e,t);if(s(n))return n.value;const r=n.error;if("return"===r.type){const e=r.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}if("halt"!==r.type&&"exit"!==r.type)throw new ao(r)}async executeNode(e,t){return this.prepareContext(t),this.compile(e)(t)}prepareContext(e){e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI)}compile(e){const t=this.ops.get(e);if(t)return t;const n=this.compileNode(e);return this.ops.set(e,n),n}compileSequence(e){const t=e.map(e=>this.compile(e));return async e=>{let n;for(const r of t){const t=await r(e);if(!s(t))return t;n=t.value}return i(n)}}compileNode(e){if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0],n=t?.message||"Skipped error node";return async()=>(Pn("\u26a0\ufe0f RUNTIME: Skipping error node: "+n),this.runtimeWarnings.push(n),i(void 0))}switch(e.type){case"command":{const t=e,n=(t.args??[]).map(e=>function(e){const t=e?.type;return"block"===t||"command"===t}(e)?this.compile(e):void 0),r=n.some(Boolean);return e=>this.processCommandWithResult(t,e,r?n:void 0)}case"initBlock":case"block":{const t=e,n=(Array.isArray(t.commands)?t.commands:[]).map(e=>this.compile(e)),r="initBlock"===e.type;return async e=>{for(const t of n){const n=await t(e);if(!s(n)){if(r&&"halt"===n.error.type)break;return n}}return i(void 0)}}case"sequence":case"CommandSequence":{const t=e;return e=>this.executeCommandSequenceWithResult(t.commands||[],e)}case"Program":return t=>this.executeProgram(e,t);default:return t=>this.dispatch(e,t)}}async dispatch(e,t){switch(Pn(`RUNTIME BASE: dispatch node type: '${e.type}'`),e.type){case"eventHandler":return i(await this.executeEventHandler(e,t));case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return i(await this.executeEventHandler(n,t))}case"behavior":return i(await this.executeBehaviorDefinition(e,t));case"def":return i(this.installFunction(e,t));case"objectLiteral":return i(await this.executeObjectLiteral(e,t));default:return await this.evaluateExpressionWithResult(e,t)}}async processCommandWithResult(e,t,n){const{name:r,args:s,modifiers:a}=e,c=r.toLowerCase();if(In(`RUNTIME BASE (Result): Processing command '${c}'`),!this.registry.has(c)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const l=await this.registry.getAdapter(c);if(!l)throw Error(`Command '${c}' is registered but failed to load adapter.`);try{const e=await l.execute(t,{args:s||[],modifiers:a||{},bodies:n,commandName:c,runtime:this});return"object"==typeof(u=e)&&null!==u&&"type"in u&&"string"==typeof u.type&&["halt","exit","break","continue","return"].includes(u.type)?o(e):i(e)}catch(e){throw this.logError(`Error executing command '${c}':`,e),e}var u}async executeCommandSequenceWithResult(e,t){let n;for(const r of e){if(this.hasErrorDiagnostics(r)){const e=r.diagnostics?.[0];Pn("\u26a0\ufe0f RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===r.type){const e=await this.compile(r)(t);if(!s(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),i(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(r,t);if(!s(e))return e;n=e.value}}return i(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await Ai(e,n);if(co(r)){const e={type:"command",name:r.command,args:[{type:"literal",value:r.selector}],isBlocking:!1},n=await this.processCommandWithResult(e,t);if(!s(n))throw new ao(n.error);return n.value}return r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await async function(e,t){try{return i(await Ai(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt)return o({type:"halt"});if(t.isExit)return o({type:"exit",returnValue:t.returnValue});if(t.isBreak)return o({type:"break"});if(t.isContinue)return o({type:"continue"});if(t.isReturn)return o({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!s(r))return r;const a=r.value;return co(a)?this.processCommandWithResult({type:"command",name:a.command,args:[{type:"literal",value:a.selector}],isBlocking:!1},t):i(a)}installFunction(e,t){const n=e.params??[],r=e.errorHandler,i=e.finallyHandler,o=e.errorSymbol,a=this.compileSequence(e.body??[]),c=r?this.compileSequence(r):void 0,l=i?this.compileSequence(i):void 0;t.globals.set(e.name,async(...e)=>{const r={...t,locals:new Map(t.locals)};n.forEach((t,n)=>{t&&r.locals.set(t,e[n])});const i=async e=>{const t=await e(r);if(!s(t)){const e=t.error;if("break"===e.type||"continue"===e.type)throw new ao(e);return"return"===e.type?e.returnValue:void 0}return t.value};if(!c&&!l)return await i(a);try{return await i(a)}catch(e){if(!c||e instanceof ao)throw e;return o&&r.locals.set(o,e),await i(c)}finally{l&&await i(l)}})}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return i(void 0);let n;const r=[],o=[],a=[],c=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"def"===t.type?o.push(t):"initBlock"===t.type?a.push(t):c.push(t);for(const e of o)this.executeNode(e,t);for(const e of r){const n=await this.executeNode(e,t);if(!s(n)){if("halt"===n.error.type||"exit"===n.error.type)break;return n}}for(const e of a){const r=await this.executeNode(e,t);if(!s(r)){if("halt"===r.error.type||"exit"===r.error.type)break;if("return"===r.error.type){n=r.error.returnValue;break}return r}n=r.value}for(const e of c){const r=await this.executeNode(e,t);if(!s(r)){if("halt"===r.error.type||"exit"===r.error.type)break;if("return"===r.error.type){n=r.error.returnValue;break}return r}n=r.value}return i(n)}async executeBlock(e,t){return this.compile(e)(t)}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const i=await this.execute(r.value,t);n[e]=i}return n}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:o}=e,s=e.imperativeInstaller;"function"==typeof s?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:s}),Pn(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:o&&o}),Pn(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){Pn("BEHAVIOR: installBehaviorOnElement called: "+e);let r=this.behaviorRegistry.get(e);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(r=this.behaviorRegistry.get(e)),!r))throw Error(`Behavior "${e}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(Pn(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),Pn(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));Pn("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const i={me:t,owner:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry};if(r.parameters)for(const e of r.parameters)i.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||i.locals.set(e,t);if(r.initBlock){Pn("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),Pn("BEHAVIOR: Init block completed for "+e)}catch(t){throw Pn(`BEHAVIOR: Init block error for ${e}:`,t),t}}if(Pn(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${e}`),r.eventHandlers){const t=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,i),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}Pn("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){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}=e,p=r&&r.length>0?r:[n];Pn(`BEHAVIOR: executeEventHandler: event='${n}', target='${o}'`);let y=[],b=null;if(o){const e="string"==typeof o?o.toLowerCase():"";if("window"===e||"the window"===e)b=window;else if("document"===e||"the document"===e||"body"===e)b=document;else if("me"===e||"myself"===e)y=t.me?[t.me]:[];else if("string"==typeof o&&t.locals.has(o)){const e=t.locals.get(o);Pn(`BEHAVIOR: Target resolution: found local '${o}', isElement: ${this.isElement(e)}`),this.isElement(e)?y=[e]:Array.isArray(e)?y=e.filter(e=>this.isElement(e)):"string"==typeof e&&(y=this.queryElements(e,t))}else Pn(`BEHAVIOR: Target resolution: querying for '${o}'`),y=this.queryElements(o,t)}else y=t.me?[t.me]:[];if(0===y.length&&!b)return void Pn(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(y,l,i,t);if("change"===n&&u)return void this.setupChangeObserver(u,i,t);const g=e.customEventSource;if(g&&this.registryIntegration){Pn(`BEHAVIOR: executeEventHandler - Using custom event source '${g}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),o={...t,locals:r,it:e,event:e};Pn(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},o)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,e)}};try{const r=this.registryIntegration.subscribeToEventSource(g,{event:n,handler:e,target:o,selector:a},t);Pn(`BEHAVIOR: Subscribed to custom event source '${g}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${g}' subscription ${r.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${g}':`,e)}return}const v=fo.createEventHandler(this,i,t,a,s,{errorSymbol:d,errorHandler:h,finallyHandler:m},1===p.length?c:void 0);let w,E=null;if(f){let e=v;if(f.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(f.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(f.debounce){const t=f.debounce;let n;w=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},E=()=>{n&&(clearTimeout(n),n=void 0)}}else if(f.throttle){const t=f.throttle;let n=0;w=r=>{const i=Date.now();t>i-n||(n=i,e(r))}}else w=e}else w=v;const x=f?.once?{once:!0}:void 0;if(b){for(const e of p)b.addEventListener(e,w,x),y.length>0?this.cleanupRegistry.registerListener(y[0],b,e,w):this.cleanupRegistry.registerGlobal(()=>b.removeEventListener(e,w),"listener",`Global ${e} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const e of y){for(const t of p){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const n of e){const e=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(e.synthetic=!0,w(e),x?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,w,x),this.cleanupRegistry.registerListener(e,e,t,w)}E&&this.cleanupRegistry.registerCustom(e,E,"debounce-timeout")}}static createEventHandler(e,t,n,r,i,o,a){const c=e.compileSequence(t),l=o?.errorHandler?e.compileSequence(o.errorHandler):void 0,u=o?.finallyHandler?e.compileSequence(o.finallyHandler):void 0;return async t=>{e.options.logAll?.()&&console.log("[hyperfixi]",t.type,n.me,t);const f=lo.get(t)??0;if(f>=100)return;if(lo.set(t,f+1),r&&t.target instanceof Element)try{if(!t.target.matches(r)&&!t.target.closest(r))return}catch{Pn(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const d=new Map(n.locals),h={...n,locals:d,it:t,event:t};if(d.has("target")||h.locals.set("target",t.target),i&&i.length>0){const e=t,n=e.detail;for(const t of i)h.locals.set(t,e[t]??n?.[t]??null)}if(a){const n=t;for(const e of uo(a))!h.locals.has(e)&&e in n&&h.locals.set(e,n[e]);let r;try{r=await e.evaluateExpression(a,h)}catch(e){return void Pn("Event filter threw; skipping handler body:",e)}if(!r)return}e.prepareContext(h);const m=async t=>{let n;try{n=await t(h)}catch(t){throw e.logError("COMMAND FAILED:",t),t}if(s(n))return;const r=n.error;if("return"===r.type&&void 0!==r.returnValue&&Object.assign(h,{it:r.returnValue,result:r.returnValue}),"break"===r.type||"continue"===r.type)throw new ao(r)};if(l||u)try{await m(c)}catch(e){if(!l||e instanceof ao)throw e;o?.errorSymbol&&h.locals.set(o.errorSymbol,e),await m(l)}finally{u&&await m(u)}else await m(c)}}setupMutationObserver(e,t,n,r){Pn(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const i of e){const e=new MutationObserver(async e=>{for(const o of e)if("attributes"===o.type&&o.attributeName===t){qn(`MUTATION DETECTED: attribute '${t}' changed on`,i);const e={...r,me:i,it:o,locals:new Map(r.locals)},a=o.oldValue,c=i.getAttribute(t);e.locals.set("oldValue",a),e.locals.set("newValue",c);for(const t of n){let n;try{n=await this.executeNode(t,e)}catch(e){this.logError("Error executing mutation handler command:",e)}if(n&&!s(n)){const e=n.error.type;if("halt"===e||"exit"===e||"return"===e)break}}}});e.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(i,e),Pn("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){Pn("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(e,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(e=>this.isElement(e))),Pn(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const e of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){qn("CONTENT CHANGE DETECTED on",e,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",e);const o=i.oldValue,a=e.textContent;null!==o&&r.locals.set("oldValue",o),r.locals.set("newValue",a);for(const e of t){let t;try{t=await this.executeNode(e,r)}catch(e){this.logError("Error executing change handler command:",e)}if(t&&!s(t)){const e=t.error.type;if("halt"===e||"exit"===e||"return"===e)break}}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),Pn("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const n=t.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=e;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return Pn(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function ho(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}class mo{trackPerformance(e,t,n,r){}trackSimple(e,t,n,r=(n?"success":"error")){}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||je(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,n,r,i=[]){return{success:!1,error:{name:e,type:t,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,n=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:n}],suggestions:n}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":Ne(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":$e(e)?"String":je(e)?"Number":Oe(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):$e(e)?e.split(""):null==e?[]:Ne(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(je(e)&&Number.isFinite(e))return e;if($e(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Oe(e)?e?1:0:null}}const po=ct({value:at().describe("String literal value")}).strict(),yo=ct({value:function(e={}){return rt?ot():it({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:nt("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:nt("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:nt("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(vo||{}).describe("Number literal value")}).strict(),bo=ct({value:(rt?ot():it({validate:e=>"boolean"!=typeof e?{success:!1,error:nt("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}})).describe("Boolean literal value")}).strict(),go=ct({left:ut().describe("Left operand"),right:ut().describe("Right operand")}).strict();var vo;const wo={stringLiteral:new class extends mo{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=po,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid){const t=this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(e,n,!1),t}let i=t.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,e));const o=this.success(i,"string");return this.trackSimple(e,n,!0,i),o}catch(t){return this.trackSimple(e,n,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let n=e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=this.resolveExpression(n.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,n)=>{try{const e=this.resolveVariable(n,t);return void 0!==e?e+"":""}catch(e){return""}}),n}resolveExpression(e,t){if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++)r=r[n[e]];return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?(ne(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends mo{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=yo,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?Number.isFinite(t.value)?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends mo{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=bo,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends mo{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=go,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,n,!0,i),this.success(i,"string")}catch(t){return this.trackSimple(e,n,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=go.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if($e(e))return e;if(je(e))return""+e;if(Oe(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}};class Eo{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand");return{success:!0,value:Dt(r+Vt(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){const t=function(e){if(null==e)return Wt([Zt("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return Wt([Zt("type-mismatch","Expected object, got "+typeof e)],["Provide an object with left and right operands"]);const t=e;if(!("left"in t)||!("right"in t)){const e=[];return"left"in t||e.push("left"),"right"in t||e.push("right"),Wt([Zt("missing-argument",`Missing ${e.join(" and ")} operand${e.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(e);if(!t.isValid)return t;const{left:n,right:r}=e;return Ut(n)?Ut(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[Zt("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[Zt("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const xo={addition:new Eo,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand");return{success:!0,value:Dt(r-Vt(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand");return{success:!0,value:Dt(r*Vt(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t,n=!0){if(0===t){if(n)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(Vt(e,"left operand"),Vt(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(Vt(e,"left operand"),Vt(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Modulo failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(e){return(new Eo).validate(e)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=this.validate(t);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:e,right:n}=t,r=Vt(e,"left operand"),i=Vt(n,"right operand");return{success:!0,value:Dt(Math.pow(r,i),"power"),type:"number"}}catch(e){return{success:!1,errors:[Zt("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Eo).validate(e)}}},ko={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const n=void 0!==t?t:e.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:$e(n)?n.length>0?n[0]:null:Ne(n)&&"length"in n&&je(n.length)&&n.length>0?n[0]:null},validate:e=>We(e,1,"first","collection")},So={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const n=void 0!==t?t:e.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const e=n.children;return e.length>0?e[e.length-1]:null}return $e(n)?n.length>0?n[n.length-1]:null:Ne(n)&&"length"in n&&je(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>We(e,1,"last","collection")},To={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!je(n))throw Error("Index must be a number");const i=n,o=void 0!==r?r:e.it;if(null==o)return null;if(Array.isArray(o)){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}if(o instanceof NodeList||o instanceof HTMLCollection){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}if(o instanceof Element){const e=o.children,t=0>i?e.length+i:i;return t>=0&&e.length>t?e[t]:null}if($e(o)){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}if(Ne(o)&&"length"in o&&je(o.length)){const e=0>i?o.length+i:i;return e>=0&&o.length>e?o[e]:null}return null},validate:e=>Ze(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function Ao(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;const e=n.querySelector(t);if(e)return e;n=n.nextElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Ao(r,t):null}function Co(e,t){let n=e.previousElementSibling;for(;n;){const e=Array.from(n.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(n.matches(t))return n;n=n.previousElementSibling}const r=e.parentElement;return r&&r!==document.documentElement?Co(r,t):null}function $o(e,t,n,r){if(n.inSearch){if(null==n.inElt)return;return function(e,t,n,r){const i=Array.from(t??[]),o=[];for(const t of i)(t.matches&&t.matches(n)||t===e)&&o.push(t);for(let t=0;o.length-1>t;t++)if(o[t]===e)return o[t+1];if(r){const e=o[0];if(e&&e.matches&&e.matches(n))return e}}(e,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),t,!!n.wrapping)}const i=n.within??("undefined"!=typeof document?document.body:null);if(i)return r?function(e,t,n,r){const i=t.querySelectorAll(n);for(let t=0;i.length>t;t++){const n=i[t];if(2===n.compareDocumentPosition(e))return n}return r?i[0]:void 0}(e,i,t,!!n.wrapping):function(e,t,n,r){const i=t.querySelectorAll(n);for(let t=i.length-1;t>=0;t--){const n=i[t];if(4===n.compareDocumentPosition(e))return n}return r?i[i.length-1]:void 0}(e,i,t,!!n.wrapping)}function jo(e){let t=0,n=e;for(;n&&n.parentElement;)t+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,t+=1e3;return t}const Oo={first:ko,last:So,at:To,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r,i]=t,o=r||e.me;return o&&o instanceof Element?n?i?$o(o,n,i,!0):Ao(o,n):o.nextElementSibling:null},validate:e=>We(e,3,"next","optional selector, optional fromElement, optional modifiers")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[n,r,i]=t,o=r||e.me;return o&&o instanceof Element?n?i?$o(o,n,i,!1):Co(o,n):o.previousElementSibling:null},validate:e=>We(e,3,"previous","optional selector, optional fromElement, optional modifiers")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[n,r,i]=t,o=i||e.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=jo(e);for(const e of r)if(jo(e)>i)return e;return null}(o,n,s):null},validate:e=>Ze(e,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[n,r,i]=t,o=i||e.me;if(!(o&&o instanceof Element))return null;const s=o.closest(r);return s?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=jo(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(i>jo(t))return t}return null}(o,n,s):null},validate:e=>Ze(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}};function No(){return ho(tt,Sn,Qe,Oo,$n,wo,xo)}var Ro=Object.freeze({__proto__:null,conversion:Qe,conversionExpressions:Qe,createCommonRegistry:function(){return ho(tt,Sn,wo,xo,Qe,Oo)},createCoreRegistry:function(){return ho(tt,Sn,wo,xo)},createExpressionRegistry:ho,createFullExpressionRegistry:No,createFullRegistry:function(){return ho(tt,Sn,wo,xo,Qe,Oo,$n)},logical:Sn,logicalExpressions:Sn,mathematical:xo,positional:Oo,positionalExpressions:Oo,properties:$n,propertiesExpressions:$n,references:tt,referencesExpressions:tt,special:wo,specialExpressions:wo});function Lo(e,t,n,r,i,o){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),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(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(e||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(e,t,n){for(var r=arguments.length>2,i=0;t.length>i;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function Io(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function qo(e){return function(t,n){Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Ho(e){return{...e}}function Po(e){return()=>new e}function Bo(e,t){return e?`[${e}] ${t}`:t}function Vo(e,t,n){if(be(e))return e;if(!e){const e=t.me;if(!e)throw Error(Bo(n,"No target element \u2014 provide explicit target or ensure context.me is set"));return Do(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error(Bo(n,'Context reference "me" is not available'));return Do(t.me)}if("it"===r){if(!be(t.it))throw Error(Bo(n,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===r){if(!t.you)throw Error(Bo(n,'Context reference "you" is not available'));return Do(t.you)}const i=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw Error(Bo(n,"DOM not available \u2014 cannot resolve element selector"));const o=i.querySelector(r);if(!o)throw Error(Bo(n,"Element not found with selector: "+r));if(!be(o))throw Error(Bo(n,"Element found but is not an HTMLElement: "+r));return o}throw Error(Bo(n,"Invalid target type: "+typeof e))}function Fo(e,t){if(Array.isArray(e))return e.filter(be);if(ve(e))return Array.from(e).filter(be);if(be(e))return[e];if(!e){const e=t.me;return e&&be(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&be(t.me)?[t.me]:[];if("it"===n)return be(t.it)?[t.it]:[];if("you"===n)return t.you&&be(t.you)?[t.you]:[];const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let e=n;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.querySelectorAll(e);return Array.from(t).filter(be)}}return[]}function Do(e){if(be(e))return e;throw Error("Value is not an HTMLElement")}function Uo(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(Bo(n,'No "me" element in context'));if(!be(t.me))throw Error(Bo(n,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(Bo(n,'No "it" value in context'));if(!be(t.it))throw Error(Bo(n,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(Bo(n,'No "you" element in context'));if(!be(t.you))throw Error(Bo(n,"context.you is not an HTMLElement"));return t.you;default:throw Error(Bo(n,"Unknown possessive: "+e))}}async function _o(e,t,n,r,i={},o){let s=e;if((!s||0===s.length)&&i.fallbackModifierKey&&o){const e=o[i.fallbackModifierKey];e&&(s=[e])}if(!s||0===s.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!be(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of s){const i=await t.evaluate(e,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(be(i))a.push(i);else if(ve(i)){const e=Array.from(i).filter(be);a.push(...e)}else if(Array.isArray(i)){const e=i.filter(be);a.push(...e)}else{if("string"!=typeof i){if(null==i)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`)}try{let e=i;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const r=t.querySelectorAll(e),o=Array.from(r).filter(be);a.push(...o)}catch(e){throw Error(`Invalid CSS selector: "${i}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!be(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}"function"==typeof SuppressedError&&SuppressedError;class zo{constructor(){this.ownsConditionalModifier=!0}async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await _o(e.args,t,n,r)}}(e,t,n,this.mode),i=e.modifiers?.when??e.modifiers?.where,{matched:o,unmatched:s}=i?await async function(e,t,n,r){const i=[],o=[],s=r.it;try{for(const s of e)r.it=s,(await n.evaluate(t,r)?i:o).push(s)}finally{r.it=s}return{matched:i,unmatched:o}}(r,i,t,n):{matched:r,unmatched:void 0};return{targets:o,...void 0!==s&&{inverse:s},mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>be(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const n=e.dataset.originalDisplay;void 0!==n?(e.style.display=n||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let Wo=(()=>{let e,t,n=[qo({name:"hide"})],r=[],i=zo;var o=t=class extends i{constructor(){super(...arguments),this.mode="hide"}get metadata(){return o.metadata}async execute(e,t){for(const t of e.targets)this.hideElement(t);for(const t of e.inverse??[])this.showElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>be(e))}};return Io(t,"HideCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({description:"Hide elements by setting display to none",syntax:"hide [<target>] [when <condition>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>","hide <li/> when its textContent is empty"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Mo(t,r),o=t})();const Zo=Po(Wo);let Jo=(()=>{let e,t,n=[qo({name:"show"})],r=[],i=zo;var o=t=class extends i{constructor(){super(...arguments),this.mode="show"}get metadata(){return o.metadata}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n);for(const t of e.inverse??[])this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>be(e))&&"string"==typeof t.defaultDisplay}};return Io(t,"ShowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({description:"Show elements by restoring display property",syntax:"show [<target>] [when <condition>]",examples:["show me","show #modal","show .hidden","show <button/>","show <li/> when its textContent contains my value"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Mo(t,r),o=t})();const Ko=Po(Jo);function Go(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function Xo(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),n=e.indexOf("=");if(-1===n)return{name:e.trim()};const r=e.slice(0,n).trim();let i=e.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function Yo(e,t){for(const n of e)t(n);return e}function Qo(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function es(e,t,n){const r=e.hasAttribute(t);void 0!==n?r&&e.getAttribute(t)===n?e.removeAttribute(t):e.setAttribute(t,n):r?e.removeAttribute(t):e.setAttribute(t,"")}function ts(e){if(!e)return[];if("string"==typeof e)return e.trim().split(/[\s,]+/).map(e=>{const t=e.trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&rs(e));if(Array.isArray(e))return e.map(e=>{const t=(e+"").trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&rs(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&rs(n)?[n]:[]}function ns(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function rs(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!ns(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function is(e,t){return e.map(e=>{if(ns(e)){const n=function(e){const t=e.trim(),n=t.match(/^\{(.+)\}$/);return n?n[1].trim():t}(e),r=t.locals.get(n)??t.globals.get(n);return null!=r?r+"":(In(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}function os(e){return"string"==typeof e&&e.trim().startsWith("*")}function ss(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const n=t.substring(1).trim();return n?{property:n}:null}(e);if(!t)return null;const n=t.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function as(e,t,n){e.style.setProperty(t,n)}const cs=["dialog","details","summary","select"];function ls(e){return e&&"object"==typeof e?"string"==typeof e.selector?e.selector:"string"==typeof e.value?e.value:"string"==typeof e.name?e.name:null:null}async function us(e,t,n){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const n=ls(e);return"string"==typeof n&&n.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const n=ls(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:ls(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;if("attributeAccess"===e.type)return!0;if("selector"===e.type||"cssSelector"===e.type){const t=ls(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:ls(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class fs{async resolveTargets(e,t,n){const r=n?.[this.preposition];return _o(r?[r]:[],e,t,this.mode)}async evaluateFirst(e,t,n){return us(e,t,n)}parseClassNames(e){return ts(e)}isAttribute(e){return Go(e.trim())}isCSSProperty(e){return os(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>be(e))}(e)}validateType(e,t){return function(e,t){return"string"==typeof e&&t.includes(e)}(e,t)}validateStringArray(e,t=1){return Array.isArray(e)&&function(e,t=1){return Array.isArray(e)&&e.length>=t&&e.every(e=>"string"==typeof e&&e.length>0)}(e,t)}}let ds=(()=>{let e,t,n=[qo({name:"add"})],r=[],i=fs;var o=t=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return o.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t,n,e.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:o}=function(e){const t=Xo(e);return{name:t.name,value:t.value??""}}(i);return{type:"attribute",name:r,value:o,targets:await this.resolveTargets(t,n,e.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim(),o=e.args[1];if(!o)throw Error("add *property requires a value argument");const s=await t.evaluate(o,n);return{type:"styles",styles:{[r]:s+""},targets:await this.resolveTargets(t,n,e.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,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=is(e.classes,t);n.length>0&&Qo(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,Yo(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){Qo(e,Object.entries(t),(e,[t,n])=>{e.style.setProperty(t,n)})}(e.targets,e.styles)}var n,r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const n=t.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(e=>"string"==typeof e))return!1}return!0}};return Io(t,"AddCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const hs=Po(ds),ms={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function ps(e){const t=ms[e];if(void 0===t)throw Error(`Unknown semantic position '${e}'. Valid positions: ${Object.keys(ms).join(", ")}.`);return t}function ys(e){return e.includes("<")&&e.includes(">")}function bs(e,t,n){!function(e,t,n){"replace"!==n?ge(t)?function(e,t,n){switch(n){case"beforebegin":e.parentElement?.insertBefore(t,e);break;case"afterbegin":e.insertBefore(t,e.firstChild);break;case"beforeend":e.appendChild(t);break;case"afterend":e.parentElement?.insertBefore(t,e.nextSibling)}}(e,t,n):function(e,t,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').`);ys(t)?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t)}(e,t,n):function(e,t){ge(t)?(e.innerHTML="",e.appendChild(t)):ys(t)?e.innerHTML=t:e.textContent=t}(e,t)}(e,t,ps(n))}function gs(e,t,n){const r=e;if("function"==typeof r.moveBefore&&t.isConnected&&e.isConnected)try{return void r.moveBefore(t,n)}catch{}e.insertBefore(t,n)}function vs(e,t,n){switch(n){case"beforeend":for(const n of t)gs(e,n,null);break;case"afterbegin":for(let n=t.length-1;n>=0;n--)gs(e,t[n],e.firstChild);break;case"beforebegin":{const n=e.parentElement;if(!n)return;for(const r of t)gs(n,r,e);break}case"afterend":{const n=e.parentElement;if(!n)return;for(let r=t.length-1;r>=0;r--)gs(n,t[r],e.nextSibling);break}case"replace":e.innerHTML="";for(const n of t)gs(e,n,null)}}function ws(e){return!!e.parentNode&&(e.remove(),!0)}let Es=(()=>{let e,t,n=[qo({name:"remove"})],r=[],i=fs;var o=t=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return o.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(be(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&be(r[0]))return{type:"element",targets:r.filter(e=>be(e))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:Xo(i).name,targets:await this.resolveTargets(t,n,e.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(t,n,e.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,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=is(e.classes,t);n.length>0&&Qo(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,Yo(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){Qo(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)ws(t)}var n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}};return Io(t,"RemoveCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const xs=Po(Es);function ks(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Ss(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const n=ks(e);return n?n.milliseconds:t}return t}function Ts(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=ks(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function As(e){return e&&"none"!==e?e.split(",").map(e=>{const t=parseFloat(e.trim());return isNaN(t)?0:e.includes("s")&&!e.includes("ms")?1e3*t:t}):[0]}function Cs(e,t){let n=0;for(let r=0;e.length>r;r++)n=Math.max(n,(e[r]||0)+(t[r]||0));return n}function $s(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function js(e){return"DIALOG"===e.tagName}function Os(e){return"DETAILS"===e.tagName}function Ns(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&es(e,n)}}function Rs(e,t,n,r){const i=Ns(e,t,n),o=setTimeout(i,r);return()=>{clearTimeout(o)}}function Ls(e,t,n,r){const i=Ns(e,t,n),o=()=>{i(),e.removeEventListener(r,o)};return e.addEventListener(r,o,{once:!0}),()=>{e.removeEventListener(r,o)}}function Ms(e,t,n){if(t.startsWith("@")){const r=t.substring(1);return void(!1===n?e.removeAttribute(r):e.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(t){case"textContent":return void(e.textContent=r);case"innerHTML":return void(e.innerHTML=r);case"innerText":return void(e.innerText=r);case"id":return void(e.id=r);case"className":return void(e.className=r);case"value":return void("value"in e&&(e.value=r));case"checked":return void("checked"in e&&(e.checked=!!n))}if(t.includes(".")){const r=t.split(".");let i=e;for(let e=0;r.length-1>e;e++)if(i=i[r[e]],null==i)return;return void(i[r[r.length-1]]=n)}if(t.includes("-")||t in e.style)e.style.setProperty(t,r);else try{e[t]=n}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function Is(e){return null==e||""===e}function qs(e,t){return function(e){return!!e&&"object"==typeof e&&"string"==typeof e.type}(e)&&e.type===t}function Hs(e){return qs(e,"literal")}const Ps=/^the\s+(.+?)\s+of\s+(.+)$/i,Bs=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 Vs(e){return"string"==typeof e&&Ps.test(e)}function Fs(e,t){const n=e.match(Ps);if(!n)return null;try{return{element:Vo(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function Ds(e,t,n){if(function(e){if(!qs(e,"propertyOfExpression"))return!1;const t=e.property;return"object"==typeof t&&null!==t}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let i=await t.evaluate(e.target,n);return Array.isArray(i)&&(i=i[0]),be(i)?{element:i,property:r}:null}(e,t,n);if(function(e){if(!qs(e,"propertyAccess"))return!1;const t=e.property;return"string"==typeof t||"object"==typeof t&&null!==t&&"string"==typeof t.name}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let i=await t.evaluate(e.object,n);return Array.isArray(i)&&(i=i[0]),be(i)?{element:i,property:r}:null}(e,t,n);const r=e;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const e=r.object,i=r.property;let o=await t.evaluate(e,n);if(Array.isArray(o)&&(o=o[0]),!be(o))return null;const s=i?.name||i?.value;return s?{element:o,property:s}:null}return null}function Us(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):Be(t,n)}function _s(e,t){const{element:n,property:r}=e;r.startsWith("*")?as(n,r.substring(1),t+""):Ms(n,r,t)}async function zs(e,t,n){let r,i;if(e?.for){const i=await t.evaluate(e.for,n);r="number"==typeof i?i:"string"==typeof i?Ss(i):void 0}if(e?.until){const r=await t.evaluate(e.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function Ws(e,t){const n=t?.name,r=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return cs.includes(t)}(t)}(t);if(be(e)||Array.isArray(e)&&e.every(e=>be(e)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return cs.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const Zs=Po((()=>{let e,t,n=[qo({name:"toggle"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers?.between;if(qs(r,"arrayLiteral")&&r.elements.length>=2){const{duration:i,untilEvent:o}=await zs(e.modifiers,t,n),s=async e=>qs(e,"selector")?e.value:t.evaluate(e,n);return{type:"classes-between",classA:(await s(r.elements[0])+"").replace(/^\./,""),classB:(await s(r.elements[1])+"").replace(/^\./,""),targets:await _o([],t,n,"toggle",{fallbackModifierKey:"on"},e.modifiers),duration:i,untilEvent:o}}if(!e.args?.length)throw Error("toggle command requires an argument");const i=e.args[0],o=await Ds(i,t,n);if(o)return{type:"property",target:o};if("selector"===i.type&&"string"==typeof i.value&&i.value.startsWith("*")){let r=i.value,o=1;if("*"===r&&"identifier"===e.args[1]?.type&&(r="*"+e.args[1].name,o=2),"*"===r&&e.modifiers?.on){const i=e.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:o,untilEvent:s}=await zs(e.modifiers,t,n),a=ss(r);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:o,untilEvent:s}}}}const s=ss(r);if(s){const{duration:r,untilEvent:i}=await zs(e.modifiers,t,n),a={fallbackModifierKey:"on"};return{type:"css-property",property:s,targets:await _o(e.args.slice(o),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:i}}}const{duration:s,untilEvent:a}=await zs(e.modifiers,t,n),{value:c}=await us(i,t,n);if(Vs(c)){const e=Fs(c,n);if(e)return{type:"property",target:e}}const{type:l,expression:u}=Ws(c,i),f={fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:i}=Xo(u);return{type:"attribute",name:r,value:i,targets:await _o(e.args.slice(1),t,n,"toggle",f,e.modifiers),duration:s,untilEvent:a}}case"css-property":{const r=ss(u);if(!r)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:r,targets:await _o(e.args.slice(1),t,n,"toggle",f,e.modifiers)}}case"element":{let r;if(be(c))r=[c];else if(Array.isArray(c)&&c.every(e=>be(e)))r=c;else if(u){const e=document.querySelectorAll(u);r=Array.from(e).filter(e=>be(e))}else r=await _o([i],t,n,"toggle",f,e.modifiers);const o=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(r);if("dialog"===o){const i=await async function(e,t,n){if(!e?.as)return"non-modal";const r=await t.evaluate(e.as,n);return"string"==typeof r&&"modal"===r.toLowerCase()?"modal":"non-modal"}(e.modifiers,t,n);return{type:"dialog",mode:i,targets:r}}return"details"===o?{type:"details",targets:$s(r)}:"select"===o?{type:"select",targets:r}:{type:"classes",classes:ts(u),targets:r,duration:s,untilEvent:a}}default:{const r=ts(u||c);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await _o(e.args.slice(1),t,n,"toggle",f,e.modifiers),duration:s,untilEvent:a}}}}async execute(e,t){switch(e.type){case"classes":{const n=is(e.classes,t);if(0===n.length)return[...e.targets];if(Qo(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&Rs(t,"class",n[0],e.duration),e.untilEvent&&Ls(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,Yo(e.targets,e=>{es(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Rs(t,"attribute",e.name,e.duration),e.untilEvent&&Ls(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return Yo(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=Us(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||Bs.has(r)||Bs.has(r.toLowerCase())){const n=!t;return _s(e,n),n}if("number"==typeof t){const n=0===t?1:0;return _s(e,n),n}if("string"==typeof t){const r="__ht_"+n,i=e.element[r];return""===t&&void 0!==i?(_s(e,i),i):(e.element[r]=t,_s(e,""),"")}_s(e,!t)}(e.target),[e.target.element];case"dialog":return Yo(e.targets,t=>{return r=e.mode,void((n=t).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return Yo(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return Yo(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const n=t.classList.contains(e.classA),r=t.classList.contains(e.classB);n?(t.classList.remove(e.classA),t.classList.add(e.classB)):r?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Rs(t,"class",e.classA,e.duration),e.untilEvent&&Ls(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}};return Io(t,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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","toggle between .expanded and .collapsed","toggle .loading until click from #done"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Mo(t,r),i=t})());const Js=Po((()=>{let e,t,n=[qo({name:"put"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=["into","before","after","at","at start of","at end of"].find(t=>e.modifiers?.[t]);let i=e.args[0]??null,o=null,s=null;if(r)o=r,s=e.modifiers[r];else{if(!e.args[1])throw Error("put requires content and position");o="into",s=e.args[1]}if(!i)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const a=await t.evaluate(i,n),c=this.mapPosition(o);let l,u,f=null;if(s){const e=(d=s,d?.type||"unknown"),r=await Ds(s,t,n);if(r)return{value:a,targets:[r.element],position:"into",memberPath:r.property};if("memberExpression"===e){const e=s.object,r=s.property;if("selector"===e?.type)f=e.value;else if("identifier"===e?.type){const i=e.name;if("my"===i||"me"===i||"I"===i){if(n.me&&r?.name)return{value:a,targets:[n.me],position:"into",memberPath:r.name}}else if("its"===i||"it"===i){const e=await t.evaluate(s,n);"string"==typeof e&&(f=e)}else f=i}if(f&&r?.name)l=r.name;else if(!f&&!l){const e=await t.evaluate(s,n);"string"==typeof e&&(f=e)}}else if("identifier"===e&&"me"===s.name)f=null;else if("selector"===e||"cssSelector"===e)f=s.value||s.selector;else if("literal"===e){const e=s.value;if("string"==typeof e&&Vs(e)){const t=Fs(e,n);if(t)return{value:a,targets:[t.element],position:"into",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?f=e:u=e+""}else if("identifier"===e){const e=s.name;if(this.looksLikeCss(e))f=e;else{const r=Ae(await t.evaluate(s,n));if(r)return{value:a,targets:r,position:c,memberPath:l};u=e}}else{const e=await t.evaluate(s,n),r=Ae(e);if(r)return{value:a,targets:r,position:c,memberPath:l};"string"==typeof e&&(this.looksLikeCss(e)?f=e:u=e)}}var d;return u?{value:a,targets:[],position:c,memberPath:l,variableName:u}:{value:a,targets:await this.resolveTargets(f,n),position:c,memberPath:l}}async execute(e,t){const{value:n,targets:r,position:i,memberPath:o,variableName:s}=e;if(s)return t.locals&&t.locals.set(s,n),t[s]=n,void Object.assign(t,{it:n});if(o)for(const e of r)this.setProperty(e,o,n);else for(const e of r){const t=this.parseValue(n);Array.isArray(t)?vs(e,t,ps(i)):bs(e,t,i)}return r}mapPosition(e){switch(e){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: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!be(t.me))throw Error("put: no target and context.me is null");return[t.me]}return Te(e)}parseValue(e){return be(e)||Array.isArray(e)&&e.length>0&&e.every(be)||ge(e)?e:null==e?"":e+""}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,n){const r=t.split(".");let i=e;for(let e=0;r.length-1>e;e++){if(!i[r[e]])throw Error(`Property path "${t}" does not exist`);i=i[r[e]]}i[r[r.length-1]]=n}};return Io(t,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Ks={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function Gs(e){return e.replace(/[&<>"']/g,e=>Ks[e])}let Xs=(()=>{let e,t,n=[qo({name:"make"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers.an??e.modifiers.a??e.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const i=r.raw;let o="string"==typeof i&&i.startsWith("<")?i:await t.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(e,t){if(!e.includes("{"))return e;const n=/\{([^{}]+)\}/g,r=[];let i;for(;null!==(i=n.exec(e));){let e=i[0];try{const n=await Ni(i[1].trim(),t);null!=n&&(e=Gs(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:e})}let o=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,text:i}=r[e];o=o.slice(0,t)+i+o.slice(t+n)}return o}(o,n));const s=void 0!==e.modifiers.an?"an":"a",a=await async function(e,t,n){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const r=[];for(const i of e.args)r.push(await t.evaluate(i,n));return r}const r=await t.evaluate(e,n);return Array.isArray(r)?r:[r]}(e.modifiers.from,t,n),c=await async function(e,t,n){if(!e)return;if(("symbol"===e.type||"identifier"===e.type)&&"string"==typeof e.name)return e.name;const r=await t.evaluate(e,n);return"string"==typeof r?r:void 0}(e.modifiers.called,t,n);return{article:s,expression:o,constructorArgs:a,variableName:c}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:i}=e,o="string"==typeof n&&n.startsWith("<"),s=o&&n.endsWith("/>")?function(e){const t=e.slice(1,-2);let n="div",r=t;const i=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=t.slice(i[0].length));const o=document.createElement(n),s=r.split(/(?=[.#])/);for(const e of s)if(e.startsWith("#")){const t=e.slice(1);t&&(o.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&o.classList.add(t)}return o}(n):o&&/<\/[a-zA-Z]/.test(n)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstElementChild;if(n&&be(n))return n;const r=document.createElement("div");r.innerHTML=e.trim();const i=r.firstElementChild;return i&&be(i)?i:r}(n):function(e,t,n){if(be(e))return e;if("function"==typeof e){const n=e;return 0===t.length?new n:new n(...t)}const r=e+"";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===t.length?new i:new i(...t)}(n,r,t);return Object.assign(t,{it:s}),i&&xe(i,s,t),s}};return Io(t,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})();const Ys=Po(Xs),Qs=Po((()=>{let e,t,n=[qo({name:"empty"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"empty",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"EmptyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function ea(e){if("string"!=typeof e)return;const t=e.toLowerCase().trim();return"non-modal"===t||"nonmodal"===t?"non-modal":"modal"===t?"modal":void 0}function ta(e){return e.hasAttribute("popover")}const na=Po((()=>{let e,t,n=[qo({name:"open"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=$s(await _o(r,t,n,"open",{fallbackModifierKey:"on"},e.modifiers)),o=await async function(e,t,n,r){if(t?.as){const e=ea(await n.evaluate(t.as,r));if(e)return e}for(const t of e){const e=t;if("asExpression"!==e?.type)continue;const n=e.targetType,r=ea(n?.name??n?.value);if(r)return r}for(let t=0;e.length-1>t;t++){const i=e[t];if("identifier"===i?.type&&"as"===i.name?.toLowerCase()){const i=await n.evaluate(e[t+1],r);if("string"==typeof i){const e=i.toLowerCase().trim();if("non-modal"===e||"nonmodal"===e)return"non-modal";if("modal"===e)return"modal"}}}return"modal"}(e.args??[],e.modifiers??{},t,n);return{targets:i,dialogMode:o}}async execute(e,t){for(const t of e.targets)if(js(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(Os(t))t.open=!0;else if(ta(t)){const e=t;if("function"==typeof e.showPopover)try{e.showPopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>be(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}};return Io(t,"OpenCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function ra(e){return e.hasAttribute("popover")}const ia=Po((()=>{let e,t,n=[qo({name:"close"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:$s(await _o(e.args,t,n,"close",{fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(js(t))t.open&&t.close();else if(Os(t))t.open=!1;else if(ra(t)){const e=t;if("function"==typeof e.hidePopover)try{e.hidePopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"CloseCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function oa(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const sa=Po((()=>{let e,t,n=[qo({name:"select"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"select",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(oa(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),n=e?.defaultView;if(!e||!n)continue;const r=n.getSelection?.();if(r)try{const n=e.createRange();n.selectNodeContents(t),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"SelectCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function aa(e){return"FORM"===e.tagName}const ca=Po((()=>{let e,t,n=[qo({name:"reset"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"reset",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)aa(t)&&t.reset()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"ResetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function la(e,t,n,r){return e?new Promise(n=>{const i=()=>{o({event:null,timedOut:!1,cancelled:!0})},o=fa(()=>{e.removeEventListener(t,s),r&&r.removeEventListener("abort",i)},n),s=e=>{o({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,s),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function ua(e){return new Promise(t=>setTimeout(t,e))}function fa(e,t){let n=!1;return r=>{n||(n=!0,e(),t(r))}}const da=Po((()=>{let e,t,n=[qo({name:"wait"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await ua(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,i=(await la(r,e.eventName)).event;if(Object.assign(t,{it:i}),e.destructure)for(const n of e.destructure)n in i&&t.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const e of i.destructure)e in r&&t.locals.set(e,r[e]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(e,t,n){return{type:"time",milliseconds:Ts(await t.evaluate(e,n))}}async parseEventArrayWait(e,t,n,r){let i;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");i=e}i||(i=r.me??void 0);const o=[];for(const t of e){const e=t;if("objectLiteral"!==e.type||!e.properties)continue;let s,a="",c=[];for(const t of e.properties){const e=t.key?.name||t.key?.value;if("name"===e&&t.value){if("string"!=typeof t.value.value)throw Error("wait for: event name must be a string");a=t.value.value}else"args"===e&&t.value?.elements?c=t.value.elements.map(e=>e.value||e.name||""):"duration"===e&&t.value&&(s=t.value)}if(s){const e=await n.evaluate(s,r);o.push({type:"time",milliseconds:Ts(e)})}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 executeRace(e,t){const n=new AbortController,r=n.signal,i=e.map(e=>"time"===e.type?ua(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):la(e.target??t.me??document,e.eventName,0,r).then(t=>({result:t.event,winningCondition:e})));try{return await Promise.race(i)}finally{n.abort()}}};return Io(t,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),ha=new Map;let ma=[/^4\d{2}$/,/^5\d{2}$/],pa=(()=>{let e,t,n=[qo({name:"fetch"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),i=this.parseResponseType(e.modifiers.as);return{url:r,responseType:i,options:await this.parseRequestOptions(e.modifiers.with,t,n),throwOnError:!e.modifiers.doNotThrow&&"response"!==i}}async execute(e,t){const n=Date.now(),{url:r,responseType:i,options:o}=e,s=new AbortController;let a;t.me&&(a=()=>s.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...o,signal:s.signal},l=ha.get(i);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;o.timeout&&(u=setTimeout(()=>s.abort(),o.timeout));try{let o=await fetch(r,c);if(t.me){const e={response:o};this.dispatchEvent(t.me,"fetch:afterResponse",e),o=e.response}if(e.throwOnError&&function(e){const t=e+"";return ma.some(e=>e.test(t))}(o.status)){const e=Error(`Fetch failed for ${r}: HTTP ${o.status} ${o.statusText}`.trim());throw e.response=o,e.isFetchStatusError=!0,e}const s=await this.handleResponse(o,i,t);t.me&&this.dispatchEvent(t.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(t,{it:s}),a}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r){const t=e;if(null==r&&"identifier"===t?.type&&t.name)throw Error(`fetch: URL expression "${t.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(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(ha.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,n){if(!e)return{};const r=await t.evaluate(e,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const 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(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[n,r]of Object.entries(e))t.set(n,r+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,n){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const r=ha.get(t);return r?r.handler(e,n):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),1===n.childNodes.length&&be(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}};return Io(t,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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" }','fetch "/api/optional" as json do not throw'],sideEffects:["network","event-dispatching"],category:"async",compatibility:"standard"}),Mo(t,r),i=t})();const ya=Po(pa);async function ba(e,t,n){const r=await t.evaluate(e,n),i=Array.isArray(r)?r[0]:r;return be(i)?i:null}async function ga(e,t,n,r){if(!e)return null;const i=e,o=i.type;if(r.nodeWriters&&o){const t=ce(o);if(t)return{kind:"node-write",node:e,writer:t}}if(r.selectorSource&&"selector"===o&&"string"==typeof i.value)return{kind:"selector",selector:i.value};const s=await async function(e,t,n,r){const i=e;if("attributeAccess"===i?.type)return{elements:await r(),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const e=await ba(i.right,t,n);if(e)return{elements:[e],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const e=await ba(i.object,t,n);if(e)return{elements:[e],name:i.property.attributeName}}return null}(e,t,n,r.scopeElements);if(s)return{kind:"attribute",elements:s.elements,name:s.name};const a=await Ds(e,t,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 e=i.scope;return{kind:"variable",name:i.name,scope:"element"===e||"global"===e?e:void 0}}return null}const va=Po((()=>{let e,t,n=[qo({name:"set"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],i=r?.name||r?.value,o=r?.scope,s=await ga(r,t,n,{scopeElements:()=>this.resolveTargets(e.modifiers.on,t,n),nodeWriters:!0,styleSplit:!0});if(s)return function(e,t){switch(e.kind){case"node-write":return{type:"node-write",node:e.node,value:t,writer:e.writer};case"attribute":return{type:"attribute",elements:e.elements,name:e.name,value:t};case"style":return{type:"style",element:e.element,property:e.property,value:t+""};case"property":return{type:"property",element:e.target.element,property:e.target.property,value:t};default:throw Error(`set: unrequested write-target rung '${e.kind}'`)}}(s,await this.extractValue(e,t,n));if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,e,t,n);if(i)return i}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await t.evaluate(r,n):i,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(be(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(Vs(a)){const r=Fs(a,n);if(r){const i=await this.extractValue(e,t,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(a,e,t,n)}if("string"==typeof a&&os(a)){const r=a.substring(1).trim(),i=await this.extractValue(e,t,n);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,n),property:r,value:i+""}}if("string"==typeof a&&Go(a)){const r=a.substring(1).trim(),i=await this.extractValue(e,t,n);return{type:"attribute",elements:await this.resolveTargets(e.modifiers.on,t,n),name:r,value:i}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=Uo(r[1],n),o=await this.extractValue(e,t,n);return{type:"property",element:i,property:r[2],value:o}}}if(be(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(a)&&a.length>0&&be(a[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(e,t,n),scope:"element"===o||"global"===o?o:void 0}}async execute(e,t){switch(e.type){case"variable":return"element"===e.scope?me(t,e.name,e.value):"global"===e.scope?xe(e.name,e.value,t,"global"):xe(e.name,e.value,t),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":for(const t of e.elements)t.setAttribute(e.name,e.value+"");return Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return Ms(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return as(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[n,r]of Object.entries(e.properties))Ms(t,n,r);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};case"node-write":return await e.writer(e.node,e.value,t),Object.assign(t,{it:e.value}),{target:e.node.name??"",value:e.value,targetType:"variable"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,n,r){const i=e.object,o=e.property;if(i?.name&&o?.name){const e=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const i=Uo(e,r),s=await this.extractValue(t,n,r);return{type:"property",element:i,property:o.name,value:s}}}const s=e.object,a=e.computed;if(s){const i=s;let c;if("memberExpression"===i.type&&!i.computed&&"style"===i.property?.name&&i.object){const e=await n.evaluate(i.object,r);c=(e&&"object"==typeof e&&"style"in e?e.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(e.property,r)+"":o?.name||"";if(i)return{type:"member-assignment",container:c,property:i,value:await this.extractValue(t,n,r)}}}return null}async extractValue(e,t,n){if(e.modifiers.to)return t.evaluate(e.modifiers.to,n);const r=e.args[1];if(r)return t.evaluate(r,n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return Vo(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return Fo(e?await t.evaluate(e,n):void 0,n)}async parseTheXofY(e,t,n,r){const i=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw Error('Invalid "the X of Y" syntax');const[,o,s]=i,a=Vo(s,r),c=await this.extractValue(t,n,r);return{type:"property",element:a,property:o.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&Array.isArray(t.elements)&&t.elements.every(be)&&"value"in t;case"property":return"string"==typeof t.property&&be(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&be(t.element)&&"string"==typeof t.value;case"object-literal":return null!==t.properties&&"object"==typeof t.properties&&Array.isArray(t.targets)&&t.targets.length>0;default:return!1}}};return Io(t,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),wa=Po((()=>{let e,t,n=[qo({name:"get"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const r=e.args[0],i=await t.evaluate(r,n);return i instanceof NodeList&&1===i.length||Array.isArray(i)&&1===i.length?{value:i[0]}:{value:i}}execute(e,t){return t.it=e.value,Object.assign(t,{result:e.value}),{value:e.value}}validate(e){return"object"==typeof e&&null!==e&&"value"in e}};return Io(t,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function Ea(e){return e&&"object"==typeof e&&e.type||"unknown"}let xa=(()=>{let e,t,n=[qo({name:"increment"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",i=await async function(e,t,n,r){if(!e.args||0===e.args.length)throw Error(r+" command requires a target");const i=e.args[0];let o,s,a;const c=Ea(i);if("identifier"===c)o=i.name,i.scope&&(s=i.scope);else if("literal"===c)o=i.value;else{const e=ce(c);if(e){const r=await t.evaluate(i,n),s="number"==typeof r?r:null==r?0:Number(r)||0;o=s,a={node:i,writer:e,currentValue:s}}else{const e=await t.evaluate(i,n);o=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=s;for(let r=1;e.args.length>r;r++){const i=e.args[r];if(Hs(i)){const e=i.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(i){const e=await t.evaluate(i,n);"number"==typeof e&&(l=e)}}const f=e.modifiers?.by;if(f){const e=f.value;if("literal"===Ea(f)&&"number"==typeof e)l=e;else if("literal"!==Ea(f)){const e=await t.evaluate(f,n);"number"==typeof e&&(l=e)}}return{target:o,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(e,t,n,r);return{...i,operation:r}}async execute(e,t){const{target:n,property:r,scope:i,amount:o=1,operation:s="increment",customWrite:a}=e;if(a){const e=isFinite(o)?o:1,n="increment"===s?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(be(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?we(n.getAttribute(t)):we(n[t]):we(n.value||n.textContent)}return"string"==typeof e?"element"===n?we(Ee(e,r,"element")):"global"===n?we(Ee(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],i=ke(n[0],t);return i?we(i[r]):0}(e,r):we("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:Ee(e,r)):we(e)}(n,r,i,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(o)?o:1;l="increment"===s?c+e:c-e}return function(e,t,n,r,i){if(be(e)){const n=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?n.setAttribute(t,r+""):n[t]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof e){if("element"===n)return void xe(e,r,i,"element");if("global"===n)return void xe(e,r,i,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),i=r[1],o=ke(r[0],n);o&&(o[i]=t)}(e,r,i);if("me"===e&&i.me)return void(i.me.value=r);if("it"===e)return void Object.assign(i,{it:r});if("you"===e&&i.you)return void(i.you.value=r);xe(e,r,i)}}(n,r,i,l,t),Object.assign(t,{it:l}),l}};return Io(t,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})();const ka=Po(xa),Sa=Po(xa),Ta=Po((()=>{let e,t,n=[qo({name:"default"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(1>e.args.length)throw Error("default command requires a target");const r=await this.extractValue(e,t,n),i=e.args[0],o=function(e){if("contextReference"!==e?.type)return null;const t=e.name;return"string"!=typeof t?null:t.startsWith(":")?{name:t.slice(1),scope:"element"}:t.startsWith("$")?{name:t.slice(1),scope:"global"}:null}(i);if(o)return{type:"variable",name:o.name,value:r,scope:o.scope};const s=await ga(i,t,n,{scopeElements:async()=>n.me?[n.me]:[],bareReference:!0});if(s)return function(e,t){switch(e.kind){case"attribute":return{type:"attribute",elements:e.elements,name:e.name,value:t};case"property":return{type:"property",element:e.target.element,property:e.target.property,value:t};case"variable":{const n=e.name.startsWith("$"),r=n?e.name.slice(1):e.name,i=n?"global":e.scope;return{type:"variable",name:r,value:t,...i?{scope:i}:{}}}default:throw Error(`default: unrequested write-target rung '${e.kind}'`)}}(s,r);const a=await t.evaluate(e.args[0],n);if(be(a))return{type:"element",element:a,value:r};if(Array.isArray(a)&&be(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(e,t,n){if(e.modifiers?.to)return t.evaluate(e.modifiers.to,n);const r=e.args[1];if(r)return t.evaluate(r,n);throw Error('default command requires a value (use "to <value>")')}async execute(e,t){switch(e.type){case"variable":return this.defaultVariable(t,e.name,e.value,e.scope);case"attribute":return this.defaultAttribute(t,e.elements,e.name,e.value);case"property":return this.defaultElementProperty(t,e.element,e.property,e.value);case"element":return this.defaultElementValue(t,e.element,e.value)}}defaultVariable(e,t,n,r){const i=Ee(t,e,r);return null!=i?{target:t,value:n,wasSet:!1,existingValue:i,targetType:"variable"}:(xe(t,n,e,r),Object.assign(e,{it:n}),{target:t,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,n,r){if(0===t.length)throw Error("No element context available for attribute default");const i=t.filter(e=>null===e.getAttribute(n));if(0===i.length)return{target:"@"+n,value:r,wasSet:!1,existingValue:t[0].getAttribute(n),targetType:"attribute"};for(const e of i)e.setAttribute(n,r+"");return Object.assign(e,{it:r}),{target:"@"+n,value:r,wasSet:!0,targetType:"attribute"}}defaultElementProperty(e,t,n,r){const i=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const n=t.split(".");let r=e;for(const e of n){if(null==r)break;r=r[e]}return r}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(t,n);return Is(i)?(Ms(t,n,r),Object.assign(e,{it:r}),{target:n,value:r,wasSet:!0,targetType:"property"}):{target:n,value:r,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(e,t,n){const r=function(e){return"value"in e?e.value:e.textContent}(t);return Is(r)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,n),Object.assign(e,{it:n}),{target:"element",value:n,wasSet:!0,targetType:"element"}):{target:"element",value:n,wasSet:!1,existingValue:r,targetType:"element"}}};return Io(t,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function Aa(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const Ca=Po((()=>{let e,t,n=[qo({name:"clear"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.args?.[0],i=function(e){if(!e)return null;const t=e.type,n=e.name;if("string"!=typeof n||""===n)return null;if("variable"===t||"identifier"===t)return{name:n,scope:e.scope};if("contextReference"===t){if(n.startsWith(":"))return{name:n.slice(1),scope:"element"};if(n.startsWith("$"))return{name:n.slice(1),scope:"global"}}return null}(r);if(i)try{const e=await t.evaluate(r,n);if(!be(e)&&!Array.isArray(e))return{type:"variable",...i}}catch{return{type:"variable",...i}}return{type:"form-fields",targets:await _o(e.args,t,n,"clear",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return xe(e.name,null,t,e.scope),void Object.assign(t,{it:null});for(const t of e.targets)Aa(t)&&("SELECT"===t.tagName?t.selectedIndex=-1:t.value="")}validate(e){if("object"!=typeof e||null===e)return!1;if("variable"===e.type)return"string"==typeof e.name;if("form-fields"===e.type){const t=e.targets;return Array.isArray(t)&&t.every(e=>be(e))}return!1}};return Io(t,"ClearCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function $a(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}let ja=(()=>{let e,t,n=[qo({name:"trigger"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r="send"===e.commandName?.toLowerCase()?"send":"trigger",i=r;if(!e.args?.length)throw Error(i+" command requires an event name");const o=e=>e?.type||"unknown",s=e.args[0];let a,c,l;if("functionCall"===o(s)||"callExpression"===o(s)){a=s.name||s.callee?.name;const e=s.args||s.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===o(s)||"keyword"===o(s))a=s.name;else{const e=await t.evaluate(s,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,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(e.modifiers?.with,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const i=[];for(const r of e){const e=await t.evaluate(r,n);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&n.me)i.push(n.me);else if("you"===e&&n.you)i.push(n.you);else if("it"===e&&n.it)i.push(n.it);else if(be(e))i.push(e);else if(e instanceof NodeList)i.push(...Array.from(e).filter(be));else if(Array.isArray(e))i.push(...e.filter(be));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);i.push(...Array.from(t).filter(be));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);i.push(e)}else i.push(document);else i.push(window)}if(!i.length)throw Error(r+": no valid targets");return i}async parseEventDetail(e,t,n){if(!e?.length)return;if(1===e.length){const r=e[0];if("objectLiteral"!==r?.type)return await t.evaluate(r,n)}const r={};for(const i of e){const e=await t.evaluate(i,n);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,n]=e.split(":",2);r[t.trim()]=$a(n.trim())}}else Object.assign(r,e)}return Object.keys(r).length?r:void 0}async parseEventOptions(e,t,n){const r={bubbles:!0,cancelable:!0,composed:!1};if(!e)return r;const i=e,o=qs(i,"arrayLiteral")?i.elements:[e];for(const e of o){const i=await t.evaluate(e,n);if("string"==typeof i){const e=i.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 Io(t,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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","send saved to #form with bubbles cancelable"],sideEffects:["event-dispatch"],aliases:["send"],category:"event",compatibility:"standard"}),Mo(t,r),i=t})();const Oa=Po(ja),Na=Po(ja),Ra=Po((()=>{let e,t,n=[qo({name:"go"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers;if(r.back)return{kind:"back"};if(r.forward)return{kind:"forward"};const i=void 0!==r.in;if(void 0!==r.url){const e=await t.evaluate(r.url,n)+"";if(!this.isValidUrl(e))throw Error(`Invalid URL: "${e}"`);return{kind:"url",url:e,newWindow:i}}const o=r.of??e.args[0];if(!o&&!r.position)throw Error("Go command requires arguments");const s=o?await t.evaluate(o,n):"body";if("string"==typeof s&&this.isBareUrl(s)&&!r.of&&!r.position)return{kind:"url",url:s,newWindow:i};const a=this.resolveScrollTarget(s,n);if(!a)throw Error("Target element not found: "+s);const c=r.position?await t.evaluate(r.position,n)+"":void 0,l={vertical:"top",horizontal:"nearest"};"top"===c||"middle"===c||"bottom"===c?l.vertical=c:"left"!==c&&"center"!==c&&"right"!==c||(l.horizontal=c,l.vertical="nearest");const u="instant"===(r.behavior?await t.evaluate(r.behavior,n):void 0)?"instant":"smooth";let f=0;if(void 0!==r.by){const e=Number((await t.evaluate(r.by,n)+"").replace(/px$/,""));Number.isNaN(e)||(f=e)}return{kind:"scroll",target:a,position:l,offset:f,behavior:u}}async execute(e,t){if("back"===e.kind||"forward"===e.kind)return await this.goHistory(e.kind),{result:e.kind,type:"back"};if("url"===e.kind)return this.navigate(e.url,e.newWindow),{result:e.url,type:"url"};const{target:n,position:r,offset:i,behavior:o}=e;if("undefined"!=typeof window){const e=this.mapVerticalPosition(r.vertical),t=this.mapHorizontalPosition(r.horizontal);if(n.scrollIntoView?.({behavior:o,block:e,inline:t}),0!==i){const{x:e,y:t}=this.calculateScrollPosition(n,r,i);window.scrollTo?.({left:e,top:t,behavior:o})}}return{result:n,type:"scroll"}}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}navigate(e,t){if(t){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e))}async goHistory(e){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");"back"===e?window.history.back():window.history.forward()}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=e.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(t.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(t.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)}}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&be(t.me))return t.me;if("it"===n&&be(t.it))return t.it;if("you"===n&&be(t.you))return t.you;const r=Ee(n,t);if(be(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}};return Io(t,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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 url "https://example.com" in new window',"go to top of #header","go to bottom of #footer smoothly"],sideEffects:["navigation","scrolling"],category:"navigation",compatibility:"standard"}),Mo(t,r),i=t})());function La(e,t){const n=e.bodies?.[t];if(!n)throw Error(`${e.commandName??"command"}: argument ${t} is a body but was not compiled \u2014 run it through the runtime`);return n}function Ma(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const n=Ee(e,t);return void 0!==n?!!n:!!e}return!!e}const Ia=Po((()=>{let e,t,n=[qo({name:"if"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(r+" command requires a condition to evaluate");let i,o;if("unless"===r){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");i=La(e,1)}else if(e.args.length>=2&&e.args[1]&&(i=La(e,1),o=3>e.args.length?void 0:La(e,2)),!i)throw Error('if command requires "then" branch with commands');return{mode:r,condition:await t.evaluate(e.args[0],n),thenCommands:i,elseCommands:o}}async execute(e,t){const{mode:n,condition:r,thenCommands:i,elseCommands:o}=e,a=Ma(r,t);let c,l,u;if(("unless"===n?!a:a)?(c="then",u=i):o&&"if"===n?(c="else",u=o):c="none",u){const e=await u(t);if(!s(e))return e.error;l=e.value}return{mode:n,conditionResult:a,executedBranch:c,result:l}}};return Io(t,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),qa=Ia,Ha=Ia;let Pa=(()=>{let e,t,n=[qo({name:"repeat"})],r=[];var o=t=class{get metadata(){return o.metadata}async parseInput(e,t,n){let r,i,o;if(e.modifiers?.index){const i=await t.evaluate(e.modifiers.index,n);"string"==typeof i&&(r=i)}{const t=[];for(let n=e.args.length-1;n>=0;n--){const r=e.args[n];if("block"===r?.type&&r.commands&&(t.unshift(n),2===t.length))break}2===t.length?(i=La(e,t[0]),o=La(e,t[1])):1===t.length&&(i=La(e,t[0]))}const s=e.modifiers??{},a=e=>async function(e,t,n){if(!e)return;const r=e;if(qs(r,"string"))return r.value;if(qs(r,"literal")&&"string"==typeof r.value)return r.value;if(qs(r,"identifier"))return r.name;const i=await t.evaluate(e,n);return"string"==typeof i?i:void 0}(e,t,n),c=await a(s.loopType)??null,l=!!s.bottomTested&&await t.evaluate(s.bottomTested,n);if("for"===c||s.for){const e=await a(s.for),c=s.in&&await t.evaluate(s.in,n);if(!e||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:e,collection:Array.isArray(c)?c:[c],indexVariable:r,commands:i,elseCommands:o}}if("times"===c||s.times){const e=s.times&&await t.evaluate(s.times,n),a="number"==typeof e?e:parseInt(e+"",10);if(isNaN(a))throw Error("times loops require a count number");return{type:"times",count:a,indexVariable:r,commands:i,elseCommands:o}}if("while"===c||s.while){const e=s.while;if(!e)throw Error("while loops require a condition");return{type:"while",condition:e,indexVariable:r,commands:i,elseCommands:o,bottomTested:l}}if("until-event"===c||s.event){const e=await a(s.event);if(!e)throw Error("until-event loops require an event name");let c=n.me;if(s.from){const e=s.from,r=qs(e,"identifier")?e.name:void 0;if("document"===r)c=document;else if("window"===r&&"undefined"!=typeof window)c=window;else{const e=await t.evaluate(s.from,n);e instanceof EventTarget?c=e:"document"===e?c=document:"undefined"!=typeof window&&e===window&&(c=window)}}return{type:"until-event",eventName:e,eventTarget:c,indexVariable:r,commands:i,elseCommands:o}}if("until"===c||s.until){const e=s.until;if(!e)throw Error("until loops require a condition");return{type:"until",condition:e,indexVariable:r,commands:i,elseCommands:o,bottomTested:l}}if("forever"===c)return{type:"forever",indexVariable:r,commands:i,elseCommands:o};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:n,variable:r,collection:o,condition:a,count:c,indexVariable:l,commands:u,elseCommands:f,bottomTested:d,eventName:h,eventTarget:m}=e;let p,y;switch(n){case"for":({config:p,iterCtx:y}=function(e,t,n){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:n}}}(o,r,l));break;case"times":({config:p,iterCtx:y}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(c,l));break;case"while":({config:p,iterCtx:y}=function(e,t,n,r){return{config:{type:"while",shouldContinue:()=>t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(a,Ma,t,l));break;case"until":({config:p,iterCtx:y}=function(e,t,n,r){return{config:{type:"until",shouldContinue:()=>!t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(a,Ma,t,l));break;case"until-event":({config:p,iterCtx:y}=function(e,t,n){const r={index:0,eventFired:!1,indexVariable:n};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{r.eventFired=!0}}},iterCtx:r}}(h,m,l));break;case"forever":({config:p,iterCtx:y}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(l));break;default:throw Error("Unknown repeat type: "+n)}if(d){const e=p.shouldContinue;p.shouldContinue=async t=>0===t.index||await e(t)}const b=await async function(e,t,n,r){const i=e.maxIterations??1e4;let o,a=0,c=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>a&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,t),n.indexVariable&&t.locals&&t.locals.set(n.indexVariable,a);const i=await r(t);if(!s(i)){const t=i.error;if("break"===t.type){c=!0;break}if("continue"===t.type){a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}return{iterations:a,lastResult:o,interrupted:c,signal:t}}o=i.value,a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:a,lastResult:o,interrupted:c}}(p,t,y,u??(async()=>i(void 0)));if(b.signal)return b.signal;if(0===b.iterations&&!b.interrupted&&f){const e=await f(t);if(!s(e))return e.error;const r=e.value;return Object.assign(t,{it:r}),{type:n,iterations:0,completed:!0,lastResult:r}}return Object.assign(t,{it:b.lastResult}),{type:n,iterations:b.iterations,completed:!b.interrupted,lastResult:b.lastResult,interrupted:b.interrupted}}};return Io(t,"RepeatCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),o=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=Ho({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" }',"repeat for item in items index i log i end"],sideEffects:["iteration","conditional-execution"],category:"control-flow",compatibility:"standard"}),Mo(t,r),o=t})();const Ba=Po(Pa);class Va{async parseInput(e,t,n){return{signalType:this.signalType}}async execute(e,t){return"exit"===this.signalType?{type:"exit",returnValue:void 0}:{type:this.signalType}}}let Fa=(()=>{let e,t,n=[qo({name:"break"})],r=[],i=Va;var o=t=class extends i{constructor(){super(...arguments),this.signalType="break"}get metadata(){return o.metadata}};return Io(t,"BreakCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const Da=Po(Fa);let Ua=(()=>{let e,t,n=[qo({name:"continue"})],r=[],i=Va;var o=t=class extends i{constructor(){super(...arguments),this.signalType="continue"}get metadata(){return o.metadata}};return Io(t,"ContinueCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const _a=Po(Ua),za=Po((()=>{let e,t,n=[qo({name:"halt"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(e.modifiers.the)return{target:n.event};const[r]=e.args;return r?{target:await t.evaluate(r,n)}:{}}async execute(e,t){let n=e.target;if(("the"===n&&t.event||"object"==typeof n&&null!==n&&"the"===n.target&&t.event)&&(n=t.event),this.isEvent(n)){const e=n;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}return"halted"in t&&(t.halted=!0),{type:"halt"}}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}};return Io(t,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Wa=Po((()=>{let e,t,n=[qo({name:"return"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return e.args&&0!==e.args.length?{value:await t.evaluate(e.args[0],n)}:{value:void 0}}async execute(e,t){const{value:n}=e;return"returnValue"in t&&(t.returnValue=n),Object.assign(t,{it:n}),{type:"return",returnValue:n}}};return Io(t,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());let Za=(()=>{let e,t,n=[qo({name:"exit"})],r=[],i=Va;var o=t=class extends i{constructor(){super(...arguments),this.signalType="exit"}get metadata(){return o.metadata}};return Io(t,"ExitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})();const Ja=Po(Za),Ka=Po((()=>{let e,t,n=[qo({name:"throw"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const[r]=e.args;if(!r)throw Error("throw command requires a message or error object");return{message:await t.evaluate(r,n)}}async execute(e,t){const{message:n}=e;let r;throw r=n instanceof Error?n:Error("string"==typeof n?n:n+""),r}};return Io(t,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Ga=Po((()=>{let e,t,n=[qo({name:"call"})],r=[];var i=t=class{get metadata(){return i.metadata}parseInput(e,t,n){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:n}=e,r=t.locals?.get("__evaluator"),i=r?await r.evaluate(n,t):await Ai(n,t);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(t,{it:o,result:o}),{result:o,wasAsync:a,expressionType:s}}};return Io(t,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());class Xa{constructor(){this.name="pseudo-command"}get metadata(){return Xa.metadata}async parseInput(e,t,n){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const r=e.args[0].properties||[];let i,o,s="",a=[];for(const e of r){const r=e.value;switch(e.key?.name||e.key?.value){case"methodName":s=r?.value||await t.evaluate(r,n)+"";break;case"methodArgs":"arrayLiteral"===r?.type&&r.elements?a=await Promise.all(r.elements.map(e=>t.evaluate(e,n))):"literal"===r?.type&&Array.isArray(r.value)&&(a=await Promise.all(r.value.map(e=>t.evaluate(e,n))));break;case"preposition":const e=r?.value;e&&"null"!==e&&(i=e);break;case"target":case"targetExpression":o=await t.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>e.args.length)throw Error("pseudo-command requires method name and target expression");const r=await t.evaluate(e.args[0],n)+"",i=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,n))):[];let o,s;const a=["from","on","with","into","at","to"];for(const r of a)if(e.modifiers?.[r]){s=r,o=await t.evaluate(e.modifiers[r],n);break}if(!o&&e.args[2]&&(o=await t.evaluate(e.args[2],n)),!o)throw Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:s,targetExpression:o}}async execute(e,t){const{methodName:n,methodArgs:r,targetExpression:i}=e;try{const e=await this.resolveTarget(i,t);if(null==e)throw Error("Target expression resolved to "+e);const o=this.resolveMethod(e,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,e,r);return t.locals.set("result",s),Object.assign(t,{it:s}),{result:s,methodName:n,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const n=e.split(".");let r="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(n[0])?(r=t.locals.get(n[0]),n.shift()):t.variables?.has(n[0])?(r=t.variables.get(n[0]),n.shift()):t.globals.has(n[0])&&(r=t.globals.get(n[0]),n.shift());for(const e of n){if(null==r)return null;r=r[e]}return r}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const n=t.split(".");let r=e;for(let e=0;n.length>e;e++){const t=n[e];if(null==r)return null;if(!(t in r))return null;if(r=r[t],e===n.length-1&&"function"==typeof r)return r}return null}async executeMethod(e,t,n){try{const r=e.apply(t,n);return r&&"object"==typeof r&&"then"in r?await r:r}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}Xa.metadata=Ho({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 Ya=Po((()=>{let e,t,n=[qo({name:"focus"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"focus",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"FocusCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),Qa=Po((()=>{let e,t,n=[qo({name:"blur"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{targets:await _o(e.args,t,n,"blur",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>be(e))}};return Io(t,"BlurCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function ec(e){return be(e)?e:e+""}class tc{constructor(e){this.position=e}concat(e,t){const n=null==e?"":e+"",r=t+"";return"append"===this.position?n+r:r+n}pushInto(e,t){return"append"===this.position?e.push(t):e.unshift(t),e}async parseInput(e,t,n){if(!e.args?.length)throw Error(this.name+" requires content");const r=await t.evaluate(e.args[0],n),i=e.modifiers?.to??e.target;if(!i)return{kind:"implicit",content:r};const o=await ga(i,t,n,{scopeElements:async()=>be(n.me)?[n.me]:[],selectorSource:!0,bareReference:!0});if(o)return function(e,t){switch(e.kind){case"selector":return{kind:"selector",selector:e.selector,content:t};case"attribute":return{kind:"attribute",elements:e.elements,name:e.name,content:t};case"property":return{kind:"property",property:e.target,content:t};case"variable":return{kind:"variable",name:e.name,scope:e.scope,content:t};default:throw Error(`unrequested write-target rung '${e.kind}'`)}}(o,r);const s=await t.evaluate(i,n),a=function(e){if(be(e))return[e];if(Array.isArray(e)&&e.length>0&&e.every(e=>be(e)))return e;if(e&&"object"==typeof e&&"number"==typeof e.length&&"function"==typeof e.item){const t=Array.from(e).filter(e=>be(e));return t.length?t:null}return null}(s);return a?{kind:"elements",elements:a,content:r}:{kind:"value",target:s,content:r}}async execute(e,t){switch(e.kind){case"selector":return this.done(t,this.insertIntoSelector(e.selector,e.content));case"elements":return this.done(t,this.insertIntoEach(e.elements,e.content));case"attribute":{for(const t of e.elements)t.setAttribute(e.name,this.concat(t.getAttribute(e.name),e.content));const n=e.elements[0]?.getAttribute(e.name)??this.concat(null,e.content);return Object.assign(t,{it:n}),{target:"@"+e.name,value:n,targetType:"attribute"}}case"property":{const n=Us(e.property),r=this.combineValue(n,e.content);return be(n)||_s(e.property,r),Object.assign(t,{it:r}),{target:e.property.element,value:r,targetType:"property"}}case"variable":return this.executeVariable(e,t);case"value":{const n=this.combineValue(e.target,e.content,!0);return Object.assign(t,{it:n}),{target:e.target,value:n,targetType:this.targetTypeOf(e.target)}}case"implicit":return this.execImplicit(t,e.content)}}insertIntoSelector(e,t){return this.insertIntoEach(Te(e),t)}insertIntoEach(e,t){const n=ec(t);for(const t of e)bs(t,n,this.position);return e}combineValue(e,t,n=!1){if(Array.isArray(e))return this.pushInto(e,t);if(e instanceof Set)return e.add(t),e;if(be(e))return bs(e,ec(t),this.position),e;if(n&&null!=e&&"string"!=typeof e&&"number"!=typeof e)throw Error(`Unable to ${this.name} a value!`);return this.concat(e,t)}targetTypeOf(e){return Array.isArray(e)?"array":e instanceof Set?"set":be(e)?"element":"result"}executeVariable(e,t){if("me"===e.name||"you"===e.name){const n="me"===e.name?t.me:t.you;if(be(n))return bs(n,ec(e.content),this.position),Object.assign(t,{it:n}),{target:n,value:n,targetType:"element"}}if("it"===e.name||"result"===e.name)return this.execImplicit(t,e.content);const n=Ee(e.name,t,e.scope),r=this.combineValue(n,e.content);return Array.isArray(n)||n instanceof Set||be(n)||xe(e.name,r,t,e.scope),Object.assign(t,{it:r}),{target:e.name,value:r,targetType:this.targetTypeOf(n)}}execImplicit(e,t){const n=e.it??e.result,r=this.combineValue(n,t);return Object.assign(e,{it:r,result:r}),{target:"result",value:r,targetType:this.targetTypeOf(n)}}done(e,t){const n=1===t.length?t[0]:t;return Object.assign(e,{it:n}),{target:n,value:n,targetType:"element"}}}const nc=Po((()=>{let e,t,n=[qo({name:"append"})],r=[],i=tc;var o=t=class extends i{get metadata(){return o.metadata}constructor(){super("append")}};return Io(t,"AppendCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})()),rc=Po((()=>{let e,t,n=[qo({name:"prepend"})],r=[],i=tc;var o=t=class extends i{get metadata(){return o.metadata}constructor(){super("prepend")}};return Io(t,"PrependCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),o=t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),t.metadata=Ho({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(t,r),o=t})()),ic=Po((()=>{let e,t,n=[qo({name:"transition"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args?.length)throw Error("transition requires property and value");let r,i;const o=await t.evaluate(e.args[0],n),s=e=>Array.isArray(e)||ve(e)?e[0]:e,a=s(o);if(be(a)||"string"==typeof o&&/^[#.]|^(?:me|it|you)$/.test(o))i=a,r=await t.evaluate(e.args[1],n)+"";else{if(e.args.length>=2)throw Error("transition: target element not found");if(null==o){const o=function(e){if(!e||"object"!=typeof e)return null;const t=e;if("identifier"===t.type&&"string"==typeof t.name&&t.name)return{property:t.name};if("propertyAccess"===t.type||"memberExpression"===t.type){const e=t.property,n="string"==typeof e?e:"string"==typeof e?.name?e.name:void 0;if(n)return{property:n,objectNode:t.object}}return null}(e.args[0]);if(!o)throw Error("transition requires a CSS property");if(r=o.property,void 0!==o.objectNode){const e=s(await t.evaluate(o.objectNode,n));be(e)&&(i=e)}}else r=o+""}if(!r||"undefined"===r||"null"===r)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let c=await t.evaluate(e.modifiers.to,n);void 0===c&&"identifier"===e.modifiers.to.type&&(c=e.modifiers.to.name);const l={property:r,value:c};return void 0!==i&&(l.target=i),e.modifiers?.over&&(l.duration=await t.evaluate(e.modifiers.over,n)),e.modifiers?.with&&(l.timingFunction=await t.evaluate(e.modifiers.with,n)+""),l}async execute(e,t){let{property:n}=e;const{target:r,value:i,duration:o,timingFunction:s}=e;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const a=Vo(r,t,"transition"),c=Ss(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 e=a.style.getPropertyValue(n);a.style.removeProperty(n),d=getComputedStyle(a).getPropertyValue(n),e&&a.style.setProperty(n,e),h=!0}a.style.setProperty(n,d);const m=await function(e,t,n){return new Promise(r=>{const i=n=>{n.target===e&&n.propertyName===t&&s({completed:!0,cancelled:!1})},o=n=>{n.target===e&&n.propertyName===t&&s({completed:!1,cancelled:!0})},s=fa(()=>{e.removeEventListener("transitionend",i),e.removeEventListener("transitioncancel",o),clearTimeout(a)},r);e.addEventListener("transitionend",i),e.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 Io(t,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),oc=Po((()=>{let e,t,n=[qo({name:"measure"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){let r,i,o;if(e.args?.length){const o=e.args[0];if("identifier"===o.type&&o.name){const s=o.name.toLowerCase();if("me"===s||"it"===s||"you"===s){const s=await t.evaluate(o,n);if(be(s)&&(r=s,e.args.length>1)){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else i=o.name}else{const s=await t.evaluate(o,n);if(be(s)||"string"==typeof s&&/^[#.]/.test(s)){if(r=s,e.args.length>1){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else"string"==typeof s&&(i=s)}}e.modifiers?.set&&(o=await t.evaluate(e.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(e,t){const n=Vo(e.target,t,"measure"),r=e.property||"width",i=this.getMeasurement(n,r);return e.variable&&t.locals&&t.locals.set(e.variable,i.value),Object.assign(t,{it:i.value}),{result:i.value,wasAsync:!1,element:n,property:r,value:i.value,unit:i.unit,stored:!!e.variable}}getMeasurement(e,t){const n=getComputedStyle(e);if(t.startsWith("*")){const e=n.getPropertyValue(t.substring(1)),r=parseFloat(e);if(!isNaN(r)){const t=e.match(/([a-zA-Z%]+)$/);return{value:r,unit:t?t[1]:""}}return{value:e,unit:""}}const r=t.toLowerCase(),i=e.getBoundingClientRect(),o={width:()=>i.width,height:()=>i.height,top:()=>i.top,left:()=>i.left,right:()=>i.right,bottom:()=>i.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(o[r])return{value:o[r](),unit:"px"};const s=n.getPropertyValue(t),a=parseFloat(s);if(!isNaN(a)){const e=s.match(/([a-zA-Z%]+)$/);return{value:a,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}};return Io(t,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),sc=Po((()=>{let e,t,n=[qo({name:"settle"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){let r,i;const[o]=e.args;if(o){const e=await t.evaluate(o,n);(be(e)||"string"==typeof e&&(e.startsWith("#")||e.startsWith(".")||"me"===e||"it"===e||"you"===e))&&(r=e)}e.modifiers?.for&&(i=await t.evaluate(e.modifiers.for,n));const s={};return void 0!==r&&(s.target=r),void 0!==i&&(s.timeout=i),s}async execute(e,t){const{target:n,timeout:r}=e,i=Vo(n,t,"settle"),o=Ss(r,5e3),s=Date.now(),a=getComputedStyle(i),c=As(a.transitionDuration),l=As(a.transitionDelay),u=As(a.animationDuration),f=As(a.animationDelay),d=Cs(c,l),h=Cs(u,f),m=Math.max(d,h);var p,y,b;return{element:i,settled:(await(p=i,y=m,b=o,y>0?new Promise(e=>{const t=e=>{e.target===p&&r({completed:!0,type:"transition"})},n=e=>{e.target===p&&r({completed:!0,type:"animation"})},r=fa(()=>{p.removeEventListener("transitionend",t),p.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(o)},e);p.addEventListener("transitionend",t),p.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},y+50),o=setTimeout(()=>{r({completed:!1,type:"timeout"})},b)}):Promise.resolve({completed:!0,type:"timeout"}))).completed,timeout:o,duration:Date.now()-s}}};return Io(t,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());const ac=Po((()=>{let e,t,n=[qo({name:"take"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error('take requires property, "from", and source');const{value:r}=await us(e.args[0],t,n),i=r+"",o=e.modifiers?.from?await t.evaluate(e.modifiers.from,n):void 0;let s;if(!s&&e.modifiers?.for&&(s=await t.evaluate(e.modifiers.for,n)),void 0===o&&!i.startsWith("."))throw Error('take requires property, "from", and source');return{property:i,source:o,target:s}}async execute(e,t){const n=e.property.trim();if(n.startsWith(".")){const r=n.substring(1);let i;if(null!=e.source)i=Fo(e.source,t);else{const e=t.me?.ownerDocument??("undefined"!=typeof document?document:null);i=e?Array.from(e.querySelectorAll("."+r)):[]}for(const e of i)e.classList.remove(r);const o=Fo(e.target,t);if(0===o.length)throw Error("take: no recipient element found");for(const e of o)e.classList.add(r);return{targetElement:o[0],property:e.property,value:r}}const r=Vo(this.firstOf(e.source),t,"take"),i=Vo(e.target?this.firstOf(e.target):void 0,t,"take"),o=this.takeProperty(r,e.property);return this.putProperty(i,e.property,o),{targetElement:i,property:e.property,value:o}}firstOf(e){const t=null!==e&&"object"==typeof e&&"number"==typeof e.length&&"function"==typeof e.item;if(Array.isArray(e)||t){const t=e[0];if(void 0===t)throw Error("take: no matching elements");return t}return e}takeProperty(e,t){const n=t.trim(),r=n.toLowerCase();if("class"===r||"classes"===r){const t=Array.from(e.classList);return e.className="",t}if(n.startsWith(".")){const t=n.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(n.startsWith("@")){const t=n.substring(1),r=e.getAttribute(t);return e.removeAttribute(t),r}if(n.startsWith("data-")){const t=e.getAttribute(n);return e.removeAttribute(n),t}if("id"===r){const t=e.id;return e.id="",t}if("title"===r){const t=e.title;return e.title="",t}if("value"===r&&"value"in e){const t=e.value;return e.value="",t}const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(n.includes("-")||i in e.style||n in e.style){let t;return i in e.style?(t=e.style[i],e.style[i]=""):n in e.style?(t=e.style[n],e.style[n]=""):(t=e.style.getPropertyValue(n),e.style.removeProperty(n)),t}const o=e.getAttribute(t);return null!==o?(e.removeAttribute(t),o):null}putProperty(e,t,n){if(null==n)return;const r=t.trim(),i=r.toLowerCase();if("class"===i||"classes"===i)return void(Array.isArray(n)?n.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof n&&(e.className=n));if(r.startsWith("."))return void(n&&e.classList.add(r.substring(1)));if(r.startsWith("@"))return void e.setAttribute(r.substring(1),n+"");if(r.startsWith("data-"))return void e.setAttribute(r,n+"");if("id"===i)return void(e.id=n+"");if("title"===i)return void(e.title=n+"");if("value"===i&&"value"in e)return void(e.value=n+"");const o=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());r.includes("-")||o in e.style||r in e.style?o in e.style?e.style[o]=n+"":r in e.style?e.style[r]=n+"":e.style.setProperty(r,n+""):e.setAttribute(t,n+"")}};return Io(t,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),cc=Po((()=>{let e,t,n=[qo({name:"js"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){let r,i;if(0===e.args.length)throw Error("js command requires JavaScript code");const o=e.args[0],s=e.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(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const a={code:r};return i&&i.length>0&&(a.parameters=i),a}async execute(e,t){const{code:n,parameters:r=[]}=e;if(!n.trim())return{result:void 0,executed:!1,codeLength:n.length,parameters:r,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,r),i=Function(...Object.keys(e),n),o=await i(...Object.values(e));return void 0!==o&&Object.assign(t,{it:o}),{result:o,executed:!0,codeLength:n.length,parameters:r,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,n)=>{let r=e.locals?.get(n);return void 0===r&&(r=e.variables?.get(n)),void 0===r&&(r=e[n]),t[n]=r,t},{})}}};return Io(t,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),lc=Po((()=>{let e,t,n=[qo({name:"log"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}};return Io(t,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),uc=Po((()=>{let e,t,n=[qo({name:"tell"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){if(2>e.args.length)throw Error("tell command requires a target and at least one command");const r=await t.evaluate(e.args[0],n),i=function(e){const t=[];for(let n=1;e.args.length>n;n++)t.push(La(e,n));return t}(e);return{target:r,commands:i}}async execute(e,t){const{target:n,commands:r}=e,i=Fo(n,t);if(0===i.length)throw Error("tell command found no target elements");const o=[];for(const e of i){const n={...t,me:e,you:e};for(const e of r){let t;try{t=await e(n)}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}if(!s(t))return t.error;const r=t.value;o.push(r),Object.assign(n,{it:r})}}return{targetElements:i,commandResults:o,executionCount:i.length*r.length}}};return Io(t,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),fc=Po((()=>{let e,t,n=[qo({name:"copy"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const[r]=e.args;if(!r)throw Error("copy command requires a source (text or element)");return{source:await t.evaluate(r,n),format:"text"}}async execute(e,t){const{source:n,format:r="text"}=e,i=this.extractText(n,r,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(i),this.dispatchCopyEvent(t,"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(t,"copy:success",{text:i,method:"execCommand"}),{success:!0,text:i,format:r,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:i,error:"All copy methods failed"}),{success:!1,text:i,format:r,method:"fallback"}}extractText(e,t,n){if("string"==typeof e)return e;if(be(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===n.me&&be(n.me)){const e=n.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,n){if(be(e.me)){const r=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!1});e.me.dispatchEvent(r)}}};return Io(t,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());function dc(e,t,n,r){return e.evaluate(function(e,t){if(!e)throw Error(t+" is required");return e}(n,r),t)}const hc=Po((()=>{let e,t,n=[qo({name:"pick"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){const r=e.modifiers?.variant,i=r?.value;if("first"===i||"last"===i){const r=await t.evaluate(e.args[0],n),o=await dc(t,n,e.modifiers.count,"pick: count");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 t.evaluate(e.args[0],n);if(!Array.isArray(r))throw Error("pick random: source must be an array");let i;if(e.modifiers.count){const r=await t.evaluate(e.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 t.evaluate(e.args[0],n);if(!Array.isArray(r)&&"string"!=typeof r)throw Error("pick items: source must be an array or string");const i=e.modifiers.rangeStart,o="start"===i?.value?"start":await dc(t,n,e.modifiers.rangeStart,"pick: start"),s="start"===o?"start":Number(o);let a;if(e.modifiers.rangeEnd)if("end"===e.modifiers.rangeEnd.value)a="end";else{const r=await t.evaluate(e.modifiers.rangeEnd,n);a=Number(r)}const c=e.modifiers.rangeMode;return{variant:"range",array:r,rangeStart:s,rangeEnd:a,rangeMode:c?.value??"default"}}if("match"===i||"matches"===i){const r=await t.evaluate(e.args[0],n);if("string"!=typeof r)throw Error(`pick ${i}: source must be a string, got ${typeof r}`);const o=await dc(t,n,e.modifiers.regex,"pick: regex"),s="string"==typeof o?o:o+"",a=e.modifiers.flags,c=a?.value;return{variant:i,source:r,regex:s,flags:c}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{variant:"random",items:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const n=e.variant??"random";if("first"===n){const n=e.array??[],r=n.slice(0,e.count??0);return Object.assign(t,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"array",variant:"first"}}if("last"===n){const n=e.array??[],r=e.count??0,i=r>0?n.slice(-r):[];return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:n.length,sourceType:"array",variant:"last"}}if("range"===n){const n=e.array??[];let r="start"===e.rangeStart?0:e.rangeStart??0,i=void 0===e.rangeEnd?r+1:"end"===e.rangeEnd?n.length:e.rangeEnd;"inclusive"===e.rangeMode?i++:"exclusive"===e.rangeMode&&r++;const o=n.slice(r,i);return Object.assign(t,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"array",variant:"range"}}if("match"===n){const n=e.source??"",r=RegExp(e.regex??"",e.flags).exec(n);return Object.assign(t,{it:r}),{selectedItem:r,sourceLength:n.length,sourceType:"string",variant:"match"}}if("matches"===n){const n=e.source??"",r=e.flags??"g",i=RegExp(e.regex??"",r.includes("g")?r:"g"+r),o=Array.from(n.matchAll(i));return Object.assign(t,{it:o}),{selectedItem:o,sourceLength:n.length,sourceType:"string",variant:"matches"}}const r=e.items??e.array??[];if(0===r.length)throw Error("Cannot pick from empty collection");if(void 0===e.count){const n=Math.floor(Math.random()*r.length),i=r[n];return Object.assign(t,{it:i}),{selectedItem:i,selectedIndex:n,sourceLength:r.length,sourceType:e.items?"items":"array",variant:"random"}}const i=r.slice(),o=[];for(let t=0;e.count>t&&i.length>0;t++){const e=Math.floor(Math.random()*i.length);o.push(i.splice(e,1)[0])}return Object.assign(t,{it:o}),{selectedItem:o,sourceLength:r.length,sourceType:e.items?"items":"array",variant:"random"}}};return Io(t,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})());const mc=Po((()=>{let e,t,n=[qo({name:"beep"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return 0===e.args.length?{expressions:[]}:{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}}async execute(e,t){const n=e.expressions||[];if(0===n.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const r=[];console.group("\ud83d\udd14 beep! Debug Output");for(const e of n){const t=this.debugExpression(e);r.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:n.length,debugged:!0,outputs:r}}debugContext(e){console.group("\ud83d\udd14 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":be(e)?"HTMLElement":e instanceof Element?"Element":e instanceof Node?"Node":e instanceof Error?"Error":e instanceof Date?"Date":e instanceof RegExp?"RegExp":typeof e}getRepresentation(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Array.isArray(e))return`Array(${e.length}) [${e.slice(0,3).map(e=>this.getRepresentation(e)).join(", ")}${e.length>3?"...":""}]`;if(be(e)){const t=e;return`<${t.tagName.toLowerCase()}${t.id?"#"+t.id:""}${t.className?"."+t.className.split(" ").join("."):""}/>`}if(e instanceof Error)return"Error: "+e.message;if("string"==typeof e)return e.length>50?`"${e.substring(0,47)}..."`:`"${e}"`;if("object"==typeof e)try{const t=Object.keys(e);return`Object {${t.slice(0,3).join(", ")}${t.length>3?"...":""}}`}catch{return"[Object]"}return e+""}};return Io(t,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({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(t,r),i=t})()),pc=Po((()=>{let e,t,n=[qo({name:"breakpoint"})],r=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}};return Io(t,"BreakpointCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Lo(null,e={value:t},n,{kind:"class",name:t.name,metadata:o},null,r),i=t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),t.metadata=Ho({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),Mo(t,r),i=t})());class yc{constructor(){this.name="install"}get metadata(){return yc.metadata}async parseInput(e,t,n){if(1>e.args.length)throw Error("install command requires a behavior name");const r=e.args[0];let i,o;if(i="identifier"===r?.type&&"string"==typeof r.name?r.name:await t.evaluate(r,n)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(i))throw Error(`Behavior name must be PascalCase (start with uppercase): "${i}"`);const s=e.args[1];if(s){const e=await t.evaluate(s,n);if(e&&"object"==typeof e&&!Array.isArray(e)){o=e;for(const e of Object.keys(o))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}let a;return e.modifiers?.on&&(a=await t.evaluate(e.modifiers.on,n)),{behaviorName:i,parameters:o,target:a}}async execute(e,t){const{behaviorName:n,parameters:r={},target:i}=e;try{const e=this.resolveTarget(i,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(n,t))throw Error(`Behavior "${n}" is not defined. Define it using the 'behavior' keyword before installing.`);const o=[];for(const i of e){const e=await this.installBehavior(n,i,r,t);o.push(e)}return{success:!0,behaviorName:n,installedCount:o.length,instances:o}}catch(e){throw Error(`Failed to install behavior "${n}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(be(e))return[e];throw Error('No target specified and "me" is not available in context')}if(be(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>be(e));if(0===t.length)throw Error("Target array contains no valid HTMLElements");return t}if("string"==typeof e){if("me"===e){const e=t.me||t.locals.get("me");if(be(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),n=Array.from(t).filter(e=>be(e));if(0===n.length)throw Error(`No elements found matching selector: "${e}"`);return n}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>be(e));if(0===t.length)throw Error("Target collection contains no valid HTMLElements");return t}if("object"==typeof e&&"element"in e){const t=e.element;if(be(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+e)}behaviorExists(e,t){const n=t.locals.get("_behaviors");if(n&&"object"==typeof n){const t=n;if(t.has(e))return!0;if(t.resolve&&t.resolve(e))return!0}if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors){if(t.behaviors.has(e))return!0;if(t.behaviors.resolve&&t.behaviors.resolve(e))return!0}}return!1}async installBehavior(e,t,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(e,t,n)}if("undefined"!=typeof globalThis){const r=globalThis._hyperscript;if(r?.behaviors?.install)return await r.behaviors.install(e,t,n)}throw Error("Behavior system not available in context")}}yc.metadata=Ho({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 bc{constructor(){this.name="render"}get metadata(){return bc.metadata}async parseInput(e,t,n){if(1>e.args.length)throw Error("render command requires a template");const r=await t.evaluate(e.args[0],n);let i;if(!i&&e.modifiers?.with){const r=await t.evaluate(e.modifiers.with,n);r&&"object"==typeof r&&(i=r)}return{template:r,variables:i}}async execute(e,t){const{template:n,variables:r={}}=e,i=this.extractTemplateContent(n,t),o=this.createTemplateContext(t,r),s=[],a=await this.processTemplate(i,o,s),c=this.createDOMElement(a);return Object.assign(t,{it:c}),{element:c,rendered:a,directivesProcessed:s}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let n=e;if(!n.includes("<")&&!n.includes("$")){const e=this.resolveVariable(n,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(n=e)}const r=n.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return r?r[1]:n}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,n){const r=e.split("\n"),i=[];let o=0;for(;r.length>o;){const e=r[o].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:s}=await this.processRepeatDirective(r,o,t);i.push(s),o=e,n.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:s}=await this.processIfDirective(r,o,t,n);i.push(s),o=e,n.push("@if")}else if("@else"===e||"@end"===e)o++;else{const n=this.processVariableInterpolation(e,t);i.push(n),o++}}return i.join("\n")}async processRepeatDirective(e,t,n){const r=e[t].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(e,t+1),c=[];if(Array.isArray(o))for(const e of o){const t={...n,locals:new Map([...n.locals.entries(),["it",e]])},r=await this.processTemplate(a.join("\n"),t,[]);c.push(r)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(e,t,n,r){const i=e[t].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(e,t+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(e,t){const n=[];let r=1,i=t;for(;e.length>i&&r>0;){const t=e[i].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(r++,n.push(e[i])):"@end"===t?(r--,r>0&&n.push(e[i])):n.push(e[i]),i++}return{endIndex:i-1,blockContent:n}}extractIfElseBlock(e,t){const n=[],r=[];let i=1,o=t,s=!1;for(;e.length>o&&i>0;){const t=e[o].trim();if(t.startsWith("@if "))i++;else{if("@else"===t&&1===i){s=!0,o++;continue}if("@end"===t&&(i--,0===i))break}s?r.push(e[o]):n.push(e[o]),o++}return{endIndex:o,blockContent:n,elseContent:r}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,n)=>{try{const e=n.trim();if(e.startsWith("unescaped ")){const n=e.substring(10).trim();return(this.evaluateExpression(n,t)||"")+""}const r=this.evaluateExpression(e,t);return this.escapeHtml((r||"")+"")}catch(t){return In(`render: template interpolation error for ${n}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const n=Number(e);if(!isNaN(n)&&""!==e.trim())return n;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const n=e.split(".");let r=this.resolveVariable(n[0],t);for(let e=1;n.length>e&&null!=r;e++){if("object"!=typeof r||null===r)return;r=r[n[e]]}return r}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it??t.result:"you"===e?t.you:"result"===e?t.result??t.it:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}function gc(){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>')}bc.metadata=Ho({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 vc=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],wc=function(e,t){const n=new ro(null);for(const t of e)n.register(t);return new fo({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0})}([Zo(),Ko(),hs(),xs(),Zs(),Js(),Ys(),Qs(),na(),ia(),sa(),ca(),da(),ya(),va(),wa(),ka(),Sa(),Ta(),Ca(),Oa(),Na(),Ra(),qa(),Ba(),Da(),_a(),za(),Wa(),Ja(),Ha(),Ka(),Ga(),new Xa,Ya(),Qa(),nc(),rc(),ic(),oc(),sc(),ac(),cc(),lc(),uc(),fc(),hc(),mc(),pc(),new yc,new bc],{expressionRegistry:No()}),Ec={async execute(e,t,n){const r=gc(),i=r.parseSemantic(e,t);if(.5>i.confidence||!i.node)throw Error(`Failed to parse "${e}" in language "${t}" (confidence: ${i.confidence.toFixed(2)})`);const o=r.buildAST(i.node),s=ye(n);return wc.execute(o.ast,s)},parse(e,t){const n=gc(),r=n.parseSemantic(e,t);return.5>r.confidence||!r.node?null:n.buildAST(r.node).ast},translate:(e,t,n)=>gc().translate(e,t,n),getAllTranslations:(e,t)=>gc().getAllTranslations(e,t),createContext:pe,runtime:wc,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","log","tell","copy","pick","beep","install","render"],supportedLanguages:vc,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await Tc():e instanceof HTMLElement&&await Sc(e)},process:async e=>Ec.processNode(e)},xc=new WeakSet;let kc=null;async function Sc(e){if(xc.has(e))return;const t=e.getAttribute("_");if(t)try{const n=function(e){const t=function(e){const t=e.getAttribute("data-lang");if(t)return t;const n=e.closest("[lang]")?.getAttribute("lang");if(n)return n.split("-")[0];if("undefined"!=typeof document){const e=document.documentElement?.lang;if(e)return e.split("-")[0]}return"en"}(e).toLowerCase();return vc.includes(t)?t:"en"}(e);Hn(`ATTR-ML: Processing element with lang="${n}":`,t.substring(0,60));const r=gc(),i=r.parseSemantic(t,n);if(.5>i.confidence||!i.node)return void Hn(`ATTR-ML: Low confidence (${i.confidence.toFixed(2)}) for: ${t}`);const o=r.buildAST(i.node),s=ye(e);await wc.execute(o.ast,s),xc.add(e),Hn("ATTR-ML: Successfully processed element")}catch(e){Hn("ATTR-ML: Error processing element:",e.message)}}async function Tc(){const e=document.querySelectorAll("[_]");Hn(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(Sc(e))}),await Promise.all(t),Hn("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:e.length}}))}function Ac(){"undefined"!=typeof MutationObserver&&(kc=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&Sc(t).catch(e=>{Hn("ATTR-ML: Error processing dynamic element:",e)});const n=t.querySelectorAll?.("[_]");n?.forEach(e=>{e instanceof HTMLElement&&Sc(e).catch(e=>{Hn("ATTR-ML: Error processing dynamic descendant:",e)})})})}),kc.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=Ec,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(()=>Ac())}):Tc().then(()=>Ac())),e.default=Ec,e.hyperfixi=Ec,Object.defineProperty(e,"l",{value:!0}),e}({});
2
2
  //# sourceMappingURL=hyperfixi-multilingual.js.map