@hyperfixi/core 2.8.0 → 2.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/dist/ast-utils/index.js +1201 -891
- package/dist/ast-utils/index.mjs +1201 -891
- package/dist/chunks/{bridge-DHj-SYm2.js → bridge-BYhqTOnL.js} +2 -2
- package/dist/chunks/browser-modular-D2BHzZFB.js +2 -0
- package/dist/chunks/feature-eventsource-Bxg_UNZo.js +2 -0
- package/dist/chunks/feature-sockets-CcTxD5sT.js +2 -0
- package/dist/chunks/feature-webworker-DoqZ0Grg.js +2 -0
- package/dist/chunks/{index-CuPeasRm.js → index-DXgJaDj-.js} +2 -2
- package/dist/commands/index.js +168 -112
- package/dist/commands/index.mjs +168 -112
- package/dist/hyperfixi-browser-classic-i18n.js +1 -1
- package/dist/hyperfixi-browser-minimal.js +1 -1
- package/dist/hyperfixi-browser-standard.js +1 -1
- package/dist/hyperfixi-browser.js +1 -1
- package/dist/hyperfixi-classic-i18n.js +1 -1
- package/dist/hyperfixi-hx-v4.js +1 -1
- package/dist/hyperfixi-minimal.js +1 -1
- package/dist/hyperfixi-multilingual.js +1 -1
- package/dist/hyperfixi-standard.js +1 -1
- package/dist/hyperfixi.js +1 -1
- package/dist/hyperfixi.mjs +1 -1
- package/dist/index.js +2119 -1538
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +2119 -1538
- package/dist/lokascript-browser-classic-i18n.js +1 -1
- package/dist/lokascript-browser-minimal.js +1 -1
- package/dist/lokascript-browser-standard.js +1 -1
- package/dist/lokascript-browser.js +1 -1
- package/dist/lokascript-multilingual.js +1 -1
- package/dist/lsp-metadata.js +5 -5
- package/dist/lsp-metadata.mjs +5 -5
- package/dist/metadata.js +25 -25
- package/dist/metadata.mjs +25 -25
- package/dist/multilingual/index.js +17 -17
- package/dist/multilingual/index.mjs +17 -17
- package/dist/parser/command-parsers/utility-commands.d.ts +1 -0
- package/dist/parser/full-parser.js +155 -106
- package/dist/parser/full-parser.mjs +155 -106
- package/dist/parser/parser.d.ts +1 -0
- package/dist/reference/index.js +1 -0
- package/dist/reference/index.mjs +1 -0
- package/dist/registry/index.js +155 -106
- package/dist/registry/index.mjs +155 -106
- package/dist/types/base-types.d.ts +3 -0
- package/package.json +7 -6
- package/dist/chunks/browser-modular-D1m0Eikh.js +0 -2
- package/dist/chunks/feature-eventsource-BpZvPy_K.js +0 -2
- package/dist/chunks/feature-sockets-CrYvjZ4j.js +0 -2
- package/dist/chunks/feature-webworker-BSYguEIW.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var _hyperfixiMultilingualInternal=function(e){"use strict";class t{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 n(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function r(e){return{ok:!0,value:e}}function i(e){return{ok:!1,error:e}}function s(e){return!0===e.ok}const o="then",a="else",c="end",l="and",u="for",f="while",d="until",h="forever",m="times",p="index",y="in",g="to",v="from",b="with",w="of",E="on",x="event",k="behavior",S="global",A="the",T="start",C=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),O=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),N=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),j="at end of",$=["into","before","after","at",N,j,"at the start of","at the end of"],I=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"]),R=e=>C.has(e.toLowerCase()),L=e=>O.has(e.toLowerCase()),M=e=>I.has(e.toLowerCase()),D=e=>P.has(e.toLowerCase()),P=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"]),q=new Set(["me","it","you","result","my","its","your"]),B=new Set(["and","or","not","no"]),V=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"]),F=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),_=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]),H=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),U=new Set([")","]","}",","]);function z(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 W(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 J(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 s=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),s=!1),{type:"typeCheckExpression",value:t,typeName:i.value,nullOk:s,negated:e,start:t.start,end:i.end}}}const K=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",z(10)],["||",z(10)],["and",z(20)],["&&",z(20)],["==",z(30)],["!=",z(30)],["<",z(30)],[">",z(30)],["<=",z(30)],[">=",z(30)],["is",z(30)],["matches",z(30)],["contains",z(30)],["starts with",z(30)],["ends with",z(30)],["does not start with",z(30)],["does not end with",z(30)],["is between",z(30,(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!1,start:e.start,end:s.end}})],["is not between",z(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!0,start:e.start,end:s.end}})],["am between",z(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!1,start:e.start,end:s.end}})],["am not between",z(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!0,start:e.start,end:s.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",z(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",z(28,(e,t,n)=>{const r=n.parseExpr(29);let i="asc";const s=n.peek();if(s&&"string"==typeof s.value){const e=s.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",z(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",z(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",z(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}})],["+",{...z(40),...J(80)}],["-",{...z(40),...J(80)}],["*",z(50)],["/",z(50)],["%",z(50)],["mod",z(50)],["^",W(60)],["**",W(60)],["as",z(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();e&&void 0!==e.value&&(t.name=`${t.name}:${e.value}`,t.end=e.end)}return t};let i=r(),s={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();s={type:"asExpression",expression:s,targetType:e,start:s.start,end:e.end??s.end,line:s.line,column:s.column}}return s})],["not",J(80)],["!",J(80)],["no",J(27)]]),new Map([["===",z(30)],["!==",z(30)],["is not",z(30)],["am",z(30)],["is in",z(30)],["is not in",z(30)],["precedes",z(30)],["does not precede",z(30)],["follows",z(30)],["does not follow",z(30)],["is a",z(30,Z(!1))],["is an",z(30,Z(!1))],["is not a",z(30,Z(!0))],["is not an",z(30,Z(!0))],["has",z(30)],["have",z(30)],["match",z(30)],["include",z(30)],["includes",z(30)],["equals",z(30)],["does not contain",z(30)],["does not include",z(30)],["am in",z(30)],["am not in",z(30)],["is really",z(30)],["is not really",z(30)],["is equal",z(30)],["is not equal",z(30)],["contain",z(30)],["do not contain",z(30)],["does not contains",z(30)],["do not match",z(30)],["does not match",z(30)],["is equal to",z(30)],["is not equal to",z(30)],["is really equal to",z(30)],["is not really equal to",z(30)],["really equals",z(30)],["is greater than",z(30)],["is less than",z(30)],["is greater than or equal to",z(30)],["is less than or equal to",z(30)],["in",z(30)],["of",W(30)],["really",z(30)],["exists",{prefix:{bp:80,handler:(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",J(80)]]),new Map([["=",W(5)]])),X=new Map,G=new Map,Y=new Map,Q=new Set,ee=new Set,te=new Set,ne=new Set;function re(e){return X.get(e.toLowerCase())}function ie(e){return Y.get(e)}function se(e,t){if(0!==ee.size)for(const n of ee)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",e)}}function oe(e,t,n){if(0!==te.size)for(const r of te)try{r(e,t,n)}catch(e){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",e)}}function ae(e,t){if(0!==ne.size)for(const n of ne)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",e)}}function ce(e,t,n){if(e.globals.set(t,n),0!==Q.size)for(const r of Q)try{r(t,n,e)}catch(e){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",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 ae(t,e),fe(n).get(t)}function me(e,t,n){const r=de(e);r&&(fe(r).set(t,n),oe(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,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function ye(e){if(!e)return pe();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)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 ge(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}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 be(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 we(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)?(ae(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)?(ae(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 Ee(e,t,n,r){if("element"!==r){if("global"===r)return ce(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))return void ce(n,e.slice(1),t);if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void oe(e,t,n);if(n.globals&&n.globals.has(e))return ce(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 ce(n,e,t);n.locals.set(e,t),oe(e,t,n)}}else me(n,e,t)}function xe(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:we(e,t)}const ke=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),s=r.coerceFrom?.[i];if(s){const r=s(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 Se(e){const t=ke.get("String");return t?t.isType(e):"string"==typeof e}function Ae(e){const t=ke.get("Number");return t?t.isType(e):"number"==typeof e}function Te(e){const t=ke.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Ce(e){const t=ke.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Oe(e){const t=ke.get("Function");return t?t.isType(e):"function"==typeof e}function Ne(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function je(e){return e instanceof Element}function $e(e){return e instanceof HTMLElement}const Ie=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Re(e,t){return Ie.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const Le={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=>Ne(e)?e.tabIndex:void 0,hidden:e=>Ne(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 Me(e,t){if(t.startsWith("*"))return function(e,t){if(!$e(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 $e(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return Re(e,t.slice(1));const n=Le[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return Re(e,t);const r=e[t];return Oe(r)?r.bind(e):r}const De={1:"one",2:"two",3:"three",4:"four",5:"five"};function Pe(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${i=t,De[i]??i+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var i;return null}function qe(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function Be(e,t,n){return Pe(e,1,t,n)??qe(e,0,t,n)}function Ve(e,t){return Pe(e,2,t,"left, right")}function Fe(){return null}function _e(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 He(e,t,n,r,i){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${i?` (${i})`:""}`:null}function Ue(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const ze="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 We;function Je(){return We({validate:e=>({success:!0,data:e})})}function Ze(e,t){if(ze)return Je();const n=We({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:Ue("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:Ue("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:Ue("missing-argument",`Required field "${t}" is missing`,t)};const s=n.validate(e);if(!s.success)return{success:!1,error:Ue("validation-error",s.error.message||`Field "${t}" validation failed`,s.error.path?`${t}.${s.error.path}`:t)};void 0!==s.data&&(i[t]=s.data)}return{success:!0,data:i}}});return n.strict=()=>Ze(e,{strict:!0}),n}We=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 We(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:Ue("runtime-error",`String must be at least ${e} characters long`)}:r}};return We(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:Ue("runtime-error",`String must be at most ${e} characters long`)}:r}};return We(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 We(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:Ue("runtime-error",t||"Refinement validation failed")}:i}};return We(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 Ke=e=>function(e={}){return ze?Je():We({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:Ue("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:Ue("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:Ue("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:Ue("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:Ue("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),Xe=e=>function(e={}){return ze?Je():We({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:Ue("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:Ue("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:Ue("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(e||{}),Ge=()=>ze?Je():We({validate:e=>"boolean"!=typeof e?{success:!1,error:Ue("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),Ye=e=>Ze(e),Qe=e=>function(e){return ze?Je():We({validate:t=>{if(!Array.isArray(t))return{success:!1,error:Ue("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:Ue("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:Ue("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(e),et=()=>Je(),tt=()=>Je(),nt=()=>function(e,t="Custom validation failed"){return ze?Je():We({validate:n=>e(n)?{success:!0,data:n}:{success:!1,error:Ue("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class rt{trackPerformance(e,t,n,r){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(e,t,n,r=(n?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:t,duration:Date.now()-t,success:n})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||Ae(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":Ce(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":Se(e)?"String":Ae(e)?"Number":Te(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Se(e)?e.split(""):null==e?[]:Ce(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Ae(e)&&Number.isFinite(e))return e;if(Se(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Te(e)?e?1:0:null}}function it(e,t,n,r,i="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:i,message:n,code:t,suggestions:r}}}function st(e,t){return{success:!0,value:e,type:t}}function ot(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const at={Array:(e,t)=>{try{return Array.isArray(e)?st(e,"array"):e instanceof NodeList?st(Array.from(e),"array"):st(null==e?[]:[e],"array")}catch(e){return it("Array","ARRAY_CONVERSION_FAILED",ot("Failed to convert value to Array",e),["Check if value is iterable","Ensure value is not circular reference"])}},String:(e,t)=>{try{return null==e?st("","string"):Se(e)?st(e,"string"):Ce(e)?st(JSON.stringify(e),"string"):st(e+"","string")}catch(e){return it("String","STRING_CONVERSION_FAILED",ot("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Te(e))return st(e,"boolean");if(null==e)return st(!1,"boolean");if(Se(e)){const t=e.toLowerCase().trim();return st("false"!==t&&"0"!==t&&""!==t,"boolean")}return Ae(e)?st(0!==e&&!isNaN(e),"boolean"):st(!!e,"boolean")}catch(e){return it("Boolean","BOOLEAN_CONVERSION_FAILED",ot("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Ae(e))return st(e,"number");if(null==e)return st(0,"number");const t=Number(e);return isNaN(t)?it("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):st(t,"number")}catch(e){return it("Number","NUMBER_CONVERSION_FAILED",ot("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const n=at.Number(e,t);return n.success?st(Math.trunc(n.value),"number"):n},Float:(e,t)=>{const n=at.Number(e,t);return n.success?st(parseFloat(""+n.value),"number"):n},Date:(e,t)=>{try{if(e instanceof Date)return st(e,"object");if(null==e)return st(new Date(""),"object");if(Se(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return st(new Date(t,n-1,r),"object")}const t=new Date(e);return isNaN(t.getTime())?it("Date","INVALID_DATE",`Cannot convert "${e}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):st(t,"object")}catch(e){return it("Date","DATE_CONVERSION_FAILED",ot("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{if(!Se(e))return st(e,"object");try{return st(JSON.parse(e),"object")}catch(e){return it("JSON","JSON_PARSE_FAILED",ot("Failed to parse value as JSON",e),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(e,t)=>{try{return st(JSON.stringify(e),"string")}catch(e){return it("JSONString","JSON_STRINGIFY_FAILED",ot("Failed to stringify value as JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(Ce(e))return st(e,"object");if(Se(e))try{return st(JSON.parse(e),"object")}catch(e){return it("Object","JSON_PARSE_FAILED",ot("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return st({},"object")}catch(e){return it("Object","OBJECT_CONVERSION_FAILED",ot("Failed to convert value to Object",e),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(e,t)=>{try{if(e instanceof HTMLFormElement)return st(dt(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;if(t.name){const e=ht(t);void 0!==e&&(n[t.name]=e)}}),st(n,"object")}return st({},"object")}catch(e){return it("FormValues","FORM_VALUES_EXTRACTION_FAILED",ot("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(e,t)=>{try{let n=e;if(e instanceof HTMLElement){const r=at.Values(e,t);if(!r.success)return r;n=r.value}if(!Ce(n))return st("","string");const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return st(""+r,"string")}catch(e){return it("FormEncoded","FORM_ENCODE_FAILED",ot("Failed to URL-encode values",e),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(e,t)=>{try{return st(new Set(e),"object")}catch(e){return it("Set","SET_CONVERSION_FAILED",ot("Failed to convert to Set",e),["Ensure the value is iterable"])}},Map:(e,t)=>{try{return st(new Map(Object.entries(e??{})),"object")}catch(e){return it("Map","MAP_CONVERSION_FAILED",ot("Failed to convert to Map",e),["Ensure the value is a plain object"])}},Keys:(e,t)=>e instanceof Map?st(Array.from(e.keys()),"array"):st(Object.keys(e??{}),"array"),Entries:(e,t)=>e instanceof Map?st(Array.from(e.entries()),"array"):st(Object.entries(e??{}),"array"),Reversed:(e,t)=>{try{return st(Array.from(e).reverse(),"array")}catch(e){return it("Reversed","REVERSED_CONVERSION_FAILED",ot("Failed to reverse value",e),["Ensure the value is array-like"])}},Unique:(e,t)=>{try{return st([...new Set(e)],"array")}catch(e){return it("Unique","UNIQUE_CONVERSION_FAILED",ot("Failed to dedupe value",e),["Ensure the value is iterable"])}},Flat:(e,t)=>{try{return st(Array.from(e).flat(),"array")}catch(e){return it("Flat","FLAT_CONVERSION_FAILED",ot("Failed to flatten value",e),["Ensure the value is array-like"])}}},ct=Ye({value:tt(),type:Ke().min(1)}),lt=Ye({value:tt(),type:Ke().min(1)});new class extends rt{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=ct,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:i,type:s}=t;if(s.startsWith("Fixed")){const r=s.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):0,a=at.Number(i,e);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(e,t,c,n),c}let o=at[s];if(o){const r=o(i,e);return this.trackPerformance(e,t,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[s.toLowerCase()];if(a&&(o=at[a],o)){const r=o(i,e);return this.trackPerformance(e,t,r,n),r}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+s,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(e,t,c,n),c}catch(r){const i={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends rt{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=lt,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:i,type:s}=t,o=s.toLowerCase();let a;switch(o){case"null":a=null===i;break;case"undefined":a=void 0===i;break;case"string":a=Se(i);break;case"number":a=Ae(i)&&!isNaN(i);break;case"boolean":a=Te(i);break;case"object":a=Ce(i);break;case"array":a=Array.isArray(i);break;case"function":a=Oe(i);break;case"date":a=i instanceof Date;break;case"element":a=i instanceof Element;break;case"node":a=i instanceof Node;break;case"node-list":a=i instanceof NodeList;break;case"empty":a=null==i||""===i||Array.isArray(i)&&0===i.length||Ce(i)&&0===Object.keys(i).length;break;default:a=i?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(e,t,c,n),c}catch(r){const i=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const ut={conversions:{dynamicResolvers:[]}},ft={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Se(e)?e:Ce(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Te(e))return e;if(null==e)return!1;if(Se(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Ae(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(Ae(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Ae(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(!Ae(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=ft.Number(e);return Math.trunc(t)},Float:e=>{const t=ft.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Se(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(!Se(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(Ce(e))return e;if(Se(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=>Se(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:ft.String(e)).join(""):e instanceof Element?e.outerHTML:ft.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return dt(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=ht(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?ft.Values(e,t):e;if(!Ce(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=ft.Values(e,t);return ft.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=ft.Values(e,t);return JSON.stringify(n)}};function dt(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=ht(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}function ht(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 mt={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 pt(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 ft.Number(e).toFixed(n??0)}if(null==e)return e;let r=ft[t];if(r)return r(e,n);const i=mt[t.toLowerCase()];if(i&&(r=ft[i],r))return r(e,n);const s=ut.conversions[t];if("function"==typeof s)return s(e,n);for(const n of ut.conversions.dynamicResolvers){const r=n(t,e);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+t),e}const yt={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;return pt(n,r,e)},validate:e=>Pe(e,2,"as","value, type")??qe(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(!Se(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 Se(n);case"number":return Ae(n)&&!isNaN(n);case"boolean":return Te(n);case"object":return Ce(n);case"array":return Array.isArray(n);case"function":return Oe(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||Ce(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>Pe(e,2,"is","value, type")??qe(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Pe(e,1,"async","expression")}},gt=new Set(["__proto__","constructor","prototype"]);function vt(e,t){if(e instanceof Element)return Me(e,t);if(Ce(e)){if(gt.has(t))return;return e[t]}return e[t]}function bt(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 wt={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 bt(n)&&!(r in n)?Array.from(n,e=>vt(e,r)):vt(n,r)}},validate:e=>Pe(e,2,"possessive","element, property")??qe(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 Me(e.me,n);if(Ce(e.me)){if(gt.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>Be(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 Me(r,n);if(Ce(r)){if(gt.has(n))return;return r[n]}return r[n]},validate:e=>Be(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 Me(e.you,n);if(Ce(e.you)){if(gt.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>Be(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 Me(r,n);if(Ce(r)){if(gt.has(n))return;return r[n]}return r[n]}},validate:e=>Pe(e,2,"of","property, object")??qe(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=>He(e,1,2,"attribute","attributeName, optional element")??qe(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 s=i||e.me;return!!(s&&s instanceof Element)&&s.getAttribute(n)===r},validate:e=>He(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??qe(e,0,"attributeWithValue","attribute name")??qe(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=>Be(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=>Be(e,"idReference","idValue")}};function Et(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]}var xt;!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"}(xt||(xt={}));const kt=new Set(["+","-","*","/","mod"]),St=new Set(["ms","s","seconds","minutes","hours","days"]);function At(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function Tt(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 Ct(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;Tt(e)}}function Ot(e,t,n,r,i){const s=r??e.position-n.length,o=e.position;let a=e.column-n.length;if(void 0!==r){a=1;let t=-1;for(let n=0;r>n;n++)"\n"!==e.input[n]&&"\r"!==e.input[n]||(t=n);a=r-t}const c={kind:t,value:n,start:s,end:o,line:Nt(e,s),column:a};e.tokens.push(c)}function Nt(e,t){let n=1;for(let r=0;t>r&&e.input.length>r;r++){const t=e.input[r];"\n"===t?n++:"\r"===t&&(n++,e.input.length>r+1&&"\n"===e.input[r+1]&&r++)}return n}function jt(e){const t=e.position;let n="";for(Tt(e),Tt(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=Tt(e);Ot(e,xt.COMMENT,"--"+n,t)}function $t(e){const t=e.position,n=Tt(e);let r=n;for(;e.input.length>e.position;){const t=Tt(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=Tt(e))}Ot(e,xt.STRING,r,t)}function It(e){const t=e.position;Tt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){Tt(e);break}if("\\"===t){if(Tt(e),e.input.length>e.position){const t=Tt(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+=Tt(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);Ot(e,xt.TEMPLATE,n,t)}function Rt(e){const t=e.position;let n=Tt(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=Tt(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=Tt(e),"}"===t)break}Ot(e,xt.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)Tt(e),e.input.length>e.position&&(n+=Tt(e));else{if(!Ft(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=Tt(e)}}Ot(e,xt.SELECTOR,n,t)}}function Lt(e){const t=e.position;if(_t(e))return void function(e,t){const n=e.input;let r="",i=0,s="";for(;n.length>e.position;){const t=n[e.position];if(s)r+=Tt(e),t===s&&(s="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===n[e.position+1]){for(;n.length>e.position&&">"!==n[e.position];)r+=Tt(e);if(n.length>e.position&&(r+=Tt(e)),i--,0>=i)break;continue}let t=!1,s="";for(;n.length>e.position;){const i=n[e.position];if(s)r+=Tt(e),i===s&&(s="");else if('"'!==i&&"'"!==i){if(">"===i){t="/"===n[e.position-1],r+=Tt(e);break}r+=Tt(e)}else s=i,r+=Tt(e)}if(t||i++,0>=i)break;continue}r+=Tt(e)}else s=t,r+=Tt(e)}Ot(e,xt.SELECTOR,r,t)}(e,t);let n="";for(n+=Tt(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=Tt(e),"/"===t&&">"===r){n+=Tt(e);break}}Ot(e,xt.SELECTOR,n,t)}function Mt(e){const t=e.position;let n=Tt(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!Ft(t)&&"_"!==t&&"-"!==t)break;n+=Tt(e)}Ot(e,xt.SYMBOL,n,t)}function Dt(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===At(e,1))return n="'s",Tt(e),Tt(e),void Ot(e,xt.OPERATOR,n,t);const i=e.input.substring(e.position,e.position+2),s=e.input.substring(e.position,e.position+3);["===","!=="].includes(s)?(n=s,Tt(e),Tt(e),Tt(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,Tt(e),Tt(e)):n=Tt(e),Ot(e,xt.OPERATOR,n,t)}function Pt(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+=Tt(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(i+=Tt(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=Tt(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]:"",s=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">s||s>"9"))for(i+=Tt(e),"+"!==n[e.position]&&"-"!==n[e.position]||(i+=Tt(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=Tt(e)}}}const s=e.position;let o="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;o+=Tt(e)}St.has(o)?Ot(e,xt.TIME,i+o,t):(e.position=s,Ot(e,xt.NUMBER,i,t))}function qt(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+=Tt(e)}const s=function(e,t,n){const r=t.toLowerCase(),i=e.position;if("'s"===t||"'s"===t)return!1;const s=e.tokens[e.tokens.length-1];if(s&&(s.kind===xt.IDENTIFIER||s.kind===xt.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}Ct(e);let o="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;o+=Tt(e)}if(o){const t=o.toLowerCase(),i=`${r} ${t}`,s=function(e,t,n,r){const i=t.toLowerCase(),s=n.toLowerCase();if("at"===i){const t=e.position;if("the"===s){Ct(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+=Tt(e)}const i=n.toLowerCase();if("start"===i||"end"===i){Ct(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+=Tt(e)}if("of"===t.toLowerCase())return Ot(e,xt.IDENTIFIER,`at the ${i} of`,r),!0}return e.position=t,!1}if("start"===s||"end"===s){Ct(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+=Tt(e)}return"of"===n.toLowerCase()?(Ot(e,xt.IDENTIFIER,`at ${s} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(s)return!0;const a=function(e,t,n){const r=e.position;let i=`${t} ${n}`,s=e.position;const o=[t,n];for(;8>o.length&&(Ct(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+=Tt(e)}if(!t)break;o.push(t.toLowerCase());const n=o.join(" ");V.has(n)&&(i=n,s=e.position)}return V.has(i)&&i!==`${t} ${n}`?(e.position=s,i):(e.position=r,null)}(e,r,t);if(a)return Ot(e,xt.OPERATOR,a,n),!0;if(V.has(i))return Ot(e,xt.OPERATOR,i,n),!0}return V.has(r)?(e.position=i,Ot(e,xt.OPERATOR,t,n),!0):(e.position=i,!1)}(e,i,t);if(s)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||B.has(t)||kt.has(e)||kt.has(t)||V.has(t)?xt.OPERATOR:xt.IDENTIFIER}(i);Ot(e,o,i,t)}function Bt(e){const t=e.position,n=e.input,r=n.length;Tt(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+=Tt(e)}Ot(e,xt.IDENTIFIER,i,t)}function Vt(e){return/[a-zA-Z]/.test(e)}function Ft(e){return/[a-zA-Z0-9]/.test(e)}function _t(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 Ht(e){if(_t(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(Ft(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 Ut(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const zt=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}(),Wt=zt,Jt=zt,Zt=zt,Kt=zt,Xt=(...e)=>{Wt&&console.log("🔧",...e)},Gt=(...e)=>{Jt&&console.log("🎯",...e)},Yt=(...e)=>{Zt&&console.log("📝",...e)},Qt=(...e)=>{Kt&&console.log("🚀",...e)};let en=!1,tn=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(en=!0,tn=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let nn={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class rn{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(rn.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const n=e.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(e)}trySemanticParse(e){const t=performance.now();if(this.shouldSkipSemantic(e))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(e,this.language),i=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const s=r.confidence>=this.confidenceThreshold&&!!r.command,o=!s&&r.confidence>0;if(en){const t={};if(r.command?.roles)for(const[e,n]of r.command.roles)t[e]=n.value;const a={input:e.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:s,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(e){if(!en)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",n=Math.round(100*e.confidence),r=Math.round(100*e.threshold),i=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),e.command&&console.log("Command: "+e.command),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),tn){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});tn.dispatchEvent(t)}}(a),n=a,nn.totalParses++,n.semanticSuccess?nn.semanticSuccesses++:n.fallbackTriggered?nn.semanticFallbacks++:nn.traditionalParses++,nn.confidenceHistory.push(n.confidence),nn.confidenceHistory.length>100&&nn.confidenceHistory.shift(),nn.averageConfidence=nn.confidenceHistory.reduce((e,t)=>e+t,0)/nn.confidenceHistory.length}return s?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var n}buildCommandNode(e){const{command:t}=e;if(!t)throw Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const n=[],r={};for(const[e,i]of t.roles){const s=this.semanticValueToExpression(i);switch(e){case"patient":case"event":n.push(s);break;case"destination":"put"===t.name?r.into=s:"add"===t.name||"append"===t.name||"prepend"===t.name?r.to=s:r.on=s;break;case"source":"fetch"===t.name?n.push(s):r.from=s;break;case"quantity":r.by=s;break;case"duration":r.over=s;break;case"responseType":r.as=s;break;case"style":r.with=s;break;case"condition":r.when=s;break;default:r[e]=s}}return{type:"command",name:t.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],n={},r=e.roles.get("loopType");r&&t.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const i=e.roles.get("patient");"for"==(r?r.value+"":"")&&i&&t.push({type:"identifier",name:"expression"===i.type&&i.raw||i.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("event");s&&t.push({type:"string",value:s.value+"",start:0,end:0,line:1,column:0});const o=e.roles.get("source");o&&t.push(this.semanticValueToExpression(o));const a=e.roles.get("quantity");a&&t.push(this.semanticValueToExpression(a));const c=e.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],n=e.roles.get("destination");if(n)if("property-path"===n.type){const e=n;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(n));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=e.roles.get("patient");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],n=e.roles.get("condition");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:e.name,args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(e.raw||"")}}parseExpressionString(e){let t=0;const n=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},r=()=>{n();const r=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(r,t)},i=()=>{const r=[];if(t++,n(),")"!==e[t])for(r.push(s()),n();","===e[t];)t++,n(),r.push(s()),n();return")"===e[t]&&t++,r},s=()=>{n();const s=r();if(!s)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:s,start:0,end:0,line:1,column:0};for(;e.length>t;){n();const s=e[t];if("."===s){t++;const e=r();e&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:e,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==s)break;o={type:"callExpression",callee:o,arguments:i(),start:0,end:0,line:1,column:0}}}return o};return s()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function sn(e){return e.kind===xt.IDENTIFIER&&C.has(e.value.toLowerCase())}function on(e){return e.kind===xt.IDENTIFIER&&_.has(e.value.toLowerCase())}function an(e){return e.kind===xt.IDENTIFIER&&F.has(e.value.toLowerCase())}function cn(e){return e.kind===xt.IDENTIFIER&&q.has(e.value.toLowerCase())}function ln(e){return V.has(e.value.toLowerCase())}function un(e){return e.kind===xt.IDENTIFIER}function fn(e){return e.kind===xt.SELECTOR}function dn(e){return e.kind===xt.SELECTOR&&!e.value.startsWith("<")}function hn(e){return e.kind===xt.STRING||e.kind===xt.NUMBER||e.kind===xt.TEMPLATE}function mn(e){return e.kind===xt.IDENTIFIER}function pn(e){return e.kind===xt.TIME}function yn(e){return e.kind===xt.SYMBOL}function gn(e){return e.kind===xt.COMMENT}function vn(e){if(e.kind!==xt.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(C.has(t)||_.has(t)||F.has(t)||q.has(t))}function bn(e){return e.kind===xt.STRING}function wn(e){return e.kind===xt.NUMBER}function En(e){if(e.kind===xt.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function xn(e){return e.kind===xt.TEMPLATE}function kn(e){return e.kind===xt.SELECTOR&&e.value.startsWith("<")}function Sn(e){return e.kind===xt.SELECTOR&&e.value.startsWith("#")}function An(e){return e.kind===xt.SELECTOR&&e.value.startsWith(".")}function Tn(e){return e.kind===xt.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function Cn(e){if(e.kind!==xt.OPERATOR)return!1;const t=e.value.toLowerCase();return!B.has(t)&&!V.has(t)}function On(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function Nn(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function jn(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function $n(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 In(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Rn(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ln(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Mn(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Dn(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function Pn(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}}rn.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const qn=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function Bn(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const Vn=[o,l,a,c];function Fn(e,t=[]){if(e.isAtEnd())return!0;for(const t of Vn)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function _n(e,t=[]){if(!Fn(e,t))return e.parseExpression()}function Hn(e,t,n){return!!e.check(t)&&(e.advance(),n.push(e.createIdentifier(t)),!0)}function Un(e,t,n){for(const r of t)if(e.check(r))return e.advance(),n.push(e.createIdentifier(r)),r;return null}function zn(e,t){return!!e.check(t)&&(e.advance(),!0)}function Wn(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 Jn{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Jn(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 Jn(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 Jn(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 Jn(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 Zn(e,t){const n=[];let r="";const i=e.peek().start||0,s=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(r=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),r+=":",e.checkIdentifierLike()&&(r+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=Wn(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),n.push({type:"functionCall",name:r,args:t,start:i,end:e.getPosition().end,line:s,column:o})}else n.push({type:"string",value:r,start:i,end:e.getPosition().end,line:s,column:o})}const a=[...n];for(;!Fn(e);){if(e.check("on")||e.check("to")){const t=e.advance().value;a.push(e.createIdentifier(t));continue}a.push(e.parsePrimary())}return Jn.fromIdentifier(t).withArgs(...a).endingAt(e.getPosition()).build()}function Kn(e,t){const n=[];if(e.check(A)){const t=e.advance();if(n.push({type:"identifier",name:A,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(x)){const t=e.advance();n.push({type:"identifier",name:x,start:t.start,end:t.end,line:t.line,column:t.column})}}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Xn(e,t){const n=[];let r=!1;const i=e.savePosition();for(let t=0;500>t&&!e.isAtEnd();t++){const t=e.peek();if(t.value===o){r=!0;break}if(t.value===c||t.value===k||"def"===t.value||t.value===E)break;e.advance()}e.restorePosition(i);let s=!1;if(!r){const n=e.savePosition(),r=t.line,i=100;for(;!e.isAtEnd()&&i>e.current-n;){const t=e.peek(),n=t.value?.toLowerCase();if(n===k||"def"===n||n===E)break;if(n===a||n===c){t.line===r&&(s=!0);break}if((e.checkIsCommand()||e.isCommand(n))&&void 0!==t.line&&t.line!==r){s=!0;break}e.advance()}e.restorePosition(n)}const l=r||s;let u;if(l)u=e.parseExpression();else{const n=[],r=20;let i=0;for(;!e.isAtEnd()&&!e.checkIsCommand()&&!e.isCommand(e.peek().value)&&!e.check(o)&&r>i;){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");u=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(u),l){r&&e.advance();const i=[];for(;!e.isAtEnd()&&!e.check(a)&&!e.check(c)&&(e.checkIsCommand()||e.isCommand(e.peek().value));){e.advance();const t=e.parseCommand();t&&i.push(t)}if(0===i.length&&e.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");n.push(In(i,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}));let s=!1;if(e.check(a))if(e.advance(),e.check("if")){const t=e.peek();e.advance();const r=Xn(e,t);n.push(In([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column})),s=!0}else{const r=[];for(;!e.isAtEnd()&&!e.check(c)&&(e.checkIsCommand()||e.isCommand(e.peek().value));){e.advance();const t=e.parseCommand();t&&r.push(t)}n.push(In(r,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}s||e.consume(c,"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(In([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}}return Jn.from(t).withArgs(...n).endingAt(e.getPosition()).build()}function Gn(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=Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}function Yn(e,t){const n=[],r=_n(e,[v]);r&&n.push(r),Hn(e,v,n);const i=_n(e);return i&&n.push(i),Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Qn(e,t){const n=[];if(e.check("between")){e.advance(),n.push(e.createIdentifier("between"));const r=_n(e,[l]);if(r&&"binaryExpression"===r.type&&"and"===r.operator)r.left&&n.push(r.left),n.push(e.createIdentifier("and")),r.right&&n.push(r.right);else{r&&n.push(r),Hn(e,l,n);const t=_n(e,[v,E,u]);t&&n.push(t)}if(Un(e,[v,E],n)){const t=_n(e);t&&n.push(t)}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}const r=_n(e,[v,E]);if(r&&n.push(r),Un(e,[v,E],n)){const t=_n(e);t&&n.push(t)}return e.check("modal")&&(e.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function er(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const r=e.peek();if(!r||!$.includes(r.value))return e.addError(`Expected operation keyword (${$.join(", ")}) after put expression, got: ${r?.value}`),null;let i=e.advance().value;const s=i.toLowerCase();"at start of"===s||"at the start of"===s?i=N:"at end of"===s||"at the end of"===s?i=j:"at"===i&&(e.check(T)||e.check(A)?(zn(e,A),e.check(T)&&(e.advance(),e.check(w)&&(e.advance(),i=N))):e.check(c)&&(e.advance(),e.check(w)&&(e.advance(),i=j)));const o=e.parseExpression();return o?Jn.fromIdentifier(t).withArgs(n,e.createIdentifier(i),o).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const tr=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function nr(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(S)&&!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===w){const e=n.left,t=n.right;return Dn(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(o)||e.check(l)||e.check(a)||e.check(c));)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")===w){const n=t[1],r=t[3];return{expression:Dn(jn(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 s=e.parseExpression()??e.parsePrimary();let u;var f;e.check(E)&&(f=e.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||rr.has(f.value))&&(e.advance(),u=_n(e));const d=[];r?d.push(r):i.length>0&&d.push(...i),d.push(e.createIdentifier(g)),s&&d.push(s);const h=Jn.fromIdentifier(t).withArgs(...d);return u&&h.withModifier("on",u),h.endingAt(e.getPosition()).build()}const rr=new Set(["me","my","it","its","you","your","yourself"]),ir=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]),sr=new Set(["in","then","and","else","end","otherwise","when","where","catch","finally"]);function or(e){return e.isAtEnd()||sr.has(e.peek().value)}function ar(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function cr(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}function lr(e,t){const n=[];for(;!Fn(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)n.push(e.parsePrimary());return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function ur(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||Fn(e)}function fr(e,t=ur){const n=e.savePosition();let r="";for(;!e.isAtEnd()&&!t(e);)r+=e.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:n,end:e.savePosition()}:(e.restorePosition(n),null)}function dr(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function hr(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 mr=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class pr{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new rn({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors]),e}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}const e=this.peek(),t=e&&re(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!==re(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?re(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")){Yt("✅ PARSER: Found event handlers after command sequence, parsing as program");const t=[e];Yt(`✅ PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){Yt(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(Yt("✅ PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,Yt(`✅ PARSER: Added event handler, now have ${t.length} statements total`)),Yt(`✅ 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 Yt("⚠️ 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};Yt("✅ PARSER: No more event handlers, at end of input");break}}return Yt(`✅ 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=pr.PRATT_TABLE.get(r.value);let s;if(i?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();s=i.prefix.handler(e,this.makePrattContext())}else s=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(s,t);if(e){s=e;continue}}const n=pr.PRATT_TABLE.get(t.value);if(!n?.infix){if(H.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){Yt("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}`),s}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}`),s}const i=this.advance();if(this.isAtEnd()&&!pr.POSTFIX_UNARY_OPERATORS.has(i.value))return this.addError(`Expected expression after '${i.value}' operator`),s;s=n.infix.handler(s,i,this.makePrattContext())}return this.prattCache.set(t,{node:s,endPos:this.current}),s}tryParseStringPostfix(e,t){const n=t.value;let r=null;if(mr.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const i=this.advance();return{type:"stringPostfix",expression:e,unit:r,start:e.start,end:i.end,line:e.line,column:e.column}}canStartOperand(e){if(!e)return!1;const t=e.value;return!H.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||H.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):R(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):M(e)}createCommandFromIdentifier(e){const t=[],n=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:!1,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return L(e)}parseCompoundCommand(e){return function(e,t){switch(t.name.toLowerCase()){case"put":return er(e,t);case"trigger":case"send":return Zn(e,t);case"remove":return Yn(e,t);case"toggle":return Qn(e,t);case"set":return nr(e,t);case"halt":return Kn(e,t);case"measure":return Gn(e,t);case"js":return function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const 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&&"’"!==e&&"‘"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===e&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==e&&"E"!==e||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return t+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==e;)"\\"===n[r]&&r++,r++;r++}}return t+n.length}(e,r);for(;!e.isAtEnd()&&!e.check(c)&&e.peek().start<i;)e.advance();e.consume(c,"Expected end after js code body");const s={type:"literal",value:e.getInputSlice(r,i).trim(),start:t.start,end:e.getPosition().end},o={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Jn.fromIdentifier(t).withArgs(s,o).endingAt(e.getPosition()).build()}(e,t);case"go":return function(e,t){const n=[];for(;!Fn(e,["when","where","catch","finally"]);){const t=e.peek(),r=e.resolveKeyword(t.value).toLowerCase();if(ir.has(r)){e.advance(),n.push(ar(r,t));continue}if(cr(e)){const r=fr(e,or);if(r){n.push(r);continue}e.advance(),n.push(ar(t.value,t));continue}if("+"===t.value||"-"===t.value){e.advance(),n.push(ar(t.value,t));continue}if("number"===t.kind){e.advance();const r=e.peek();if(e.isAtEnd()||"px"!==r.value||r.start!==t.end)n.push({type:"literal",value:Number(t.value),raw:t.value,start:t.start,end:t.end,line:t.line,column:t.column});else{const r=e.advance();n.push(ar(t.value+"px",{...t,end:r.end}))}continue}const i=e.current;if(n.push(e.parsePrimary()),e.current===i)break}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(e,t);case"tell":return function(e,t){const n=e.parseExpression();if(!n)throw Error("tell command requires a target expression");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(l))continue;if(e.check(o)||e.check(a)||e.check(c))break;if(e.checkIsCommand())continue;break}break}if(0===r.length)throw Error("tell command requires at least one command after the target");return Jn.fromIdentifier(t).withArgs(n,...r).endingAt(e.getPosition()).build()}(e,t);case"pick":return function(e,t){const n=Jn.fromIdentifier(t);zn(e,A);const r=e.peek().value,i=e=>({type:"literal",value:e,start:t.start,end:t.end}),s=()=>{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=s();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=s();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=s(),o=n.withArgs(r).withModifier("variant",i("random"));return t&&o.withModifier("count",t),o.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?i("start"):e.parsePrimary();let o=!1;(e.match("to")||e.match(".."))&&(e.match("end")?o=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=s(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",t).withModifier("rangeMode",i(a));return o?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 o;e.matchOperator("|")&&(o=e.advance().value);const a=s(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",t);return o&&c.withModifier("flags",i(o)),c.endingAt(e.getPosition()).build()}return lr(e,t)}(e,t);case"start":return function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd();return Jn.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(e,t);case"swap":case"morph":return function(e,t){const n=[];let r=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const i=t.value.toLowerCase();tr.includes(i)&&(r=i,e.advance(),n.push(e.createIdentifier(r)))}}if("delete"===r){const r=e.parseExpression();return r&&n.push(r),Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(w)&&(e.advance(),n.push(e.createIdentifier("of")));const i=e.parseExpression();if(i&&n.push(i),!e.isAtEnd()&&e.check(b)){e.advance(),n.push(e.createIdentifier("with"));const t=e.parseExpression();t&&n.push(t)}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(e,t);default:return lr(e,t)}}(this.getContext(),e)}parsePutCommand(e){return er(this.getContext(),e)}parseSetCommand(e){return nr(this.getContext(),e)}parseHaltCommand(e){return Kn(this.getContext(),e)}parseMeasureCommand(e){return Gn(this.getContext(),e)}parseTriggerCommand(e){return Zn(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(Yt("🔄 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){Yt("📍 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){Yt(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(Yt("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(Yt("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(e){Yt("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n}}else this.checkIdentifier()&&Yt("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){Yt("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(Yt("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)Yt("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))Yt("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){Yt("📍 No separator and no command, breaking. Current token:",this.peek().value);break}Yt("✅ 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=""),Yt("✅ parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(){const{commands:e}=this.parseCommandListUntilTerminator([]);if(Yt('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw Yt('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return Yt('✅ Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",i=null,s=null,o=null,a=null,c=null,l=null;if(e.check(u)){e.advance(),r=u;const t=e.peek();un(t)&&(c=t.value,e.advance()),e.check(y)&&(e.advance(),a=e.parseExpression())}else if(e.check(y))e.advance(),r=u,c="it",a=e.parseExpression();else if(e.check(f))e.advance(),r=f,o=e.parseExpression();else if(e.check(d))if(e.advance(),r=d,e.check(x)){e.advance(),r="until-event";const t=e.peek();if(Yt("📍 Parsing event name, current token:",{value:t.value,kind:t.kind}),!un(t)&&!an(t))throw Error('Expected event name after "event"');if(i=t.value,e.advance(),Yt("✅ Got event name:",i,"Next token:",e.peek().value),Yt('🔍 Checking for "from", current token:',e.peek().value),e.check(v)){Yt('✅ Found "from", advancing...'),e.advance(),Yt('📍 After consuming "from", current token:',e.peek().value),zn(e,A)&&Yt('✅ Found "the", advancing...');const t=e.peek();Yt("🔍 Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),s=e.parsePrimary(),Yt("✅ After parsePrimary, eventTarget:",s)}else Yt('❌ No "from" found, skipping target parsing')}else o=e.parseExpression();else e.check(h)?(e.advance(),r=h):(l=e.parseExpression(),e.check(m)&&(e.advance(),r=m));let g,w=null;if(e.check(b)){const t=e.peekAt(1);t&&t.value.toLowerCase()===p&&(e.advance(),e.advance(),w=p)}else if(e.check(p)){e.advance();const t=e.peek();un(t)?(w=t.value,e.advance()):w=p}let E=null,k=!1;if(r===h){const t=e.parseRepeatBody();if(g=t.commands,"else"===t.terminator)e.advance(),E=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(k=!0,r=t.terminator,e.advance(),o=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();g=t.commands,t.hasElse&&(e.advance(),E=e.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column});const S={start:t.start,end:t.end,line:t.line,column:t.column};c&&n.push(Rn(c,S)),a&&n.push(a),o&&n.push(o),l&&n.push(l),i&&n.push(Rn(i,S)),s&&n.push(s),w&&n.push(Rn(w,S)),n.push(In(g,{...S,end:S.end||0})),null!==E&&n.push(In(E,{...S,end:S.end||0}));const T=Jn.from(t).withArgs(...n);return k&&T.withModifier("bottomTested",{type:"literal",value:!0,...S}),T.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 s=e.peek();if(!un(s))throw Error('Expected variable name after "for"');if(r=s.value,e.advance(),!e.check(y))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 o=null;if(e.check(b)){const t=e.peekAt(1);t&&t.value.toLowerCase()===p&&(e.advance(),e.advance(),o=p)}else if(e.check(p)){e.advance();const t=e.peek();un(t)?(o=t.value,e.advance()):o=p}const a=e.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(Rn(r,c)),n.push(i),o&&n.push(Rn(o,c)),n.push(In(a,{...c,end:c.end||0})),Jn.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")&&!Fn(e)){const r=e.parseExpression();return n.push(r),Jn.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{const t=e.peek();if(!un(t))throw Error('Expected event name 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(!un(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({name:n,params:i}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let i=null;e.check(v)&&(e.advance(),zn(e,A),i=e.parsePrimary());const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(Mn(r.map(e=>Ln([{key:jn("name",s),value:Nn(e.name,`"${e.name}"`,s)},{key:jn("args",s),value:Mn(e.params.map(e=>Nn(e,`"${e}"`,s)),s)}],s)),s)),i&&n.push(i)}return Jn.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(jn(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(Wn(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(Ln(r.map(e=>({key:e.name?jn(e.name,i):Nn("_positional","_positional",i),value:e.value})),i))}}return Jn.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let i=null;const s=e.peek();if(un(s)||"*"===s.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:s.start||0,end:e.getPosition().end,line:s.line,column:s.column})}if(!i)throw Error("Transition command requires a CSS property");if(n.push(i),!e.check(g))throw Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(r.to=o,e.check("over")){e.advance();const t=e.parsePrimary();r.over=t}if(e.check(b)){e.advance();const t=e.parsePrimary();r.with=t}return Jn.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=_n(e,[g]);t&&n.push(t)}if(e.check(g)){e.advance();const t=_n(e);t&&n.push(t)}return Jn.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return Xn(this.getContext(),e)}parseRemoveCommand(e){return Yn(this.getContext(),e)}parseToggleCommand(e){return Qn(this.getContext(),e)}parseRegularCommand(e){return lr(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):yn(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()&&un(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}}{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}}}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(vn)||this.matchPredicate(on)||this.matchPredicate(cn)||this.matchPredicate(sn)||this.matchPredicate(an))){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(yn(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{type:"dollarExpression",expression:t,raw:`$${e.value}${this.previous().value||""}`,line:e.line,column:e.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.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(vn))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(vn)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",n=!0,this.checkPredicate(vn)&&(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(vn))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,s=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==s||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),0>o&&"number"==typeof e.start&&(o=e.start),"number"==typeof e.end&&(a=e.end),"$"===e.value&&this.check("{")&&(i=!0),"{"===e.value&&s++,"}"===e.value&&s--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,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"]);let i,s,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(i=this.advance().value),s=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==s&&{errorHandler:s},...void 0!==o&&{finallyHandler:o},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let n=t.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,n,r,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(!(pr.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||vn(r)&&!this.isCommand(r.value)||cn(r)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let i,s;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}}),pr.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{s=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,i,s,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(Yt("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return Yt("⚠️ 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(),s=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);e[n]=s,Yt(`🔧 parseEventHandler: Parsed '${t} at ${i.value}' (${s}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);e[n]=r,Yt(`🔧 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(){Yt("🔧 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,Yt("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),Yt("🔧 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),Yt("🔧 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),Yt("🔧 parseEventHandler: Parsed additional event name: "+t)}let r;if(Yt("🔧 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,Yt(`🔧 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"),Yt("🔧 parseEventHandler: Parsed event parameters: "+i.join(", "))}const s={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)s.once=!0,Yt("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)s.prevent=!0,Yt("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)s.stop=!0,Yt("🔧 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?(s.debounce=n,Yt(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(s.throttle=n,Yt(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else Yt(`🔧 parseEventHandler: Warning - unknown modifier '.${e}'`)}let o,a,c,l;if(this.parseTemporalKeywordModifiers(s),t&&(s.once=!0),Object.keys(s).length>0&&Yt("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();a=e.value,Yt(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${e.kind})`),this.parseTemporalKeywordModifiers(s)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value,Yt("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(Yt("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),Yt("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(Yt(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(Yt(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){Yt("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())Yt("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){Yt("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&"js"!==t&&"tell"!==t){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const n=this.parseCommand();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.parseCommandWithErrorRecovery();e&&(u.push(e),Yt("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&u.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){Yt("⚠️ Expression parsing error, restoring error state:",e instanceof Error?e.message:e+""),this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator)break;{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name))break;{const 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)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const f=this.getPosition(),d={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:u,...i.length>0&&{args:i},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:f.start,end:f.end,line:f.line,column:f.column};return Yt(`🔧 parseEventHandler: Created node with events: ${e.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),d}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let s;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();vn(e)?(n.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=r.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),s=t.value,this.advance())}}const o={type:"eventHandler",event:t,commands:this.parseCommandListUntilEnd(),...void 0!==s&&{target:s},...n.length>0&&{args:n},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};i.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}s={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:n,eventHandlers:i,...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")||(Yt("⚠️ 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"));)Yt("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){Yt('✅ 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=Pn(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)}getMultiWordPattern(e){return function(e){return qn.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return Bn(e,t)}parseMultiWordCommand(e,t){return function(e,t,n){const r=e.getMultiWordPattern(n);if(!r)return null;const i=[],s={};for(;!Fn(e,["catch","finally",...r.keywords])&&!Bn(e.peek(),r.keywords);){const t=e.parsePrimary();if(!t)break;if(i.push(t),!e.match(",")&&Bn(e.peek(),r.keywords))break}for(;!e.isAtEnd()&&Bn(e.peek(),r.keywords);){const t=e.advance().value,n=e.parseExpression();if(n&&(s[t]=n),!Bn(e.peek(),r.keywords))break}const o=Jn.from(t).withArgs(...i).endingAt(e.getPosition());return Object.keys(s).length>0&&o.withModifiers(s),o.build()}(this.getContext(),e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();t.push(e)}}return t}trySemanticParse(e){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const t=this.semanticAdapter.trySemanticParse(e);return t.success&&t.node?(Yt(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(Yt(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return Yt("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),n=t.value.toLowerCase();if(e.includes(n))break;if(sn(t))break;this.advance()}}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 t=e.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch"].includes(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return function(e,t){const n={};let r=null;if(!e.isAtEnd()&&e.check("/")&&(r=fr(e)),r||(r=e.parsePrimary()),!r)return e.addError("fetch requires a URL"),Jn.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(n.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||n.as){if(!e.check("with")||n.with){if(e.check("do")&&!n.doNotThrow){const t=e.peekAt(1),r=e.peekAt(2);if("not"===t?.value&&"throw"===r?.value){const t=e.advance();e.advance();const r=e.advance();n.doNotThrow={type:"literal",value:!0,start:t.start,end:r.end,line:t.line,column:t.column};continue}}break}e.advance(),n.with=dr(e)?hr(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||zn(e,"a")||zn(e,"an"),n.as=e.parsePrimary();const i=Jn.from(t).withArgs(r).endingAt(e.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}(this.getContext(),e);const n=this.parseMultiWordCommand(e,t);if(n)return n;const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||function(e,t){return{type:"command",name:e,args:[],partial:!0,start:t.start,end:t.end,line:t.line,column:t.column}}(r,this.getPosition());const i=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const n=t.value,r="increment"===n?"+":"-";let i=!1;e.check(S)&&(i=!0,e.advance());const s=e.parseExpression();if(!s)throw Error("Expected variable or expression after "+n);let o;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);o=t}else o=Nn(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let a=s;i&&"identifier"===s.type&&(a={...s,scope:"global"});const c={start:t.start,end:e.previous().end,line:t.line,column:t.column},l=$n(r,s,o,c);l.coerceNumeric=!0;const u=[a,jn(g,c),l];return Jn.from(t).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(this.getContext(),e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const e=this.parseExpression();if(i.push(e||this.parsePrimary()),this.match(","))continue;const t=["into","from","to","with","by","at","before","after","over"];if(t.some(e=>this.check(e)))continue;const n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!t.includes(n.name??n.value))break}const s=this.getPosition();return{type:"command",name:t,args:i,isBlocking:!1,start:s.start,end:s.end,line:s.line,column:s.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}const n=this.createCallExpression(this.createIdentifier(e),t);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(n.relativePositional=e)}return n}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){if(this.match("*")){let t="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(""),!1);for(t=this.advance().value;this.check("-")&&!this.isAtEnd();){if(t+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}t+=this.advance().value}const n="*"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const t=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(e),{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column},!0)}if(yn(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}const t=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;D(t)&&Yt(`💡 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 Nn(e,t,this.getPosition())}createIdentifier(e){return jn(e,this.getPosition())}createBinaryExpression(e,t,n){return $n(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(Yt(`✅ createProgramNode: Called with ${e.length} statements`),0===e.length)return Yt("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return Yt(`✅ 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 Yt(`✅ 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!(!Cn(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(dn)}matchSelector(){return this.matchPredicate(dn)}checkAnySelector(){return this.checkPredicate(fn)}checkLiteral(){return this.checkPredicate(hn)}checkIdentifierLike(){return this.checkPredicate(un)}checkIsCommand(){return this.checkPredicate(sn)}checkCommandTerminator(){return this.checkPredicate(On)}checkReference(){return this.checkPredicate(mn)}checkTimeExpression(){return this.checkPredicate(pn)}checkEvent(){return this.checkPredicate(an)}checkContextVar(){return this.checkPredicate(cn)}checkComment(){return this.checkPredicate(gn)}checkIdentifier(){return this.checkPredicate(vn)}checkKeyword(){return this.checkPredicate(on)}checkString(){return this.checkPredicate(bn)}matchString(){return this.matchPredicate(bn)}checkNumber(){return this.checkPredicate(wn)}matchNumber(){return this.matchPredicate(wn)}checkBoolean(){return this.checkPredicate(En)}matchBoolean(){return this.matchPredicate(En)}checkTemplateLiteral(){return this.checkPredicate(xn)}matchTemplateLiteral(){return this.matchPredicate(xn)}checkQueryReference(){return this.checkPredicate(kn)}matchQueryReference(){return this.matchPredicate(kn)}checkIdSelector(){return this.checkPredicate(Sn)}checkClassSelector(){return this.checkPredicate(An)}checkCssSelector(){return this.checkPredicate(Tn)}checkBasicOperator(){return this.checkPredicate(Cn)}matchBasicOperator(){return this.matchPredicate(Cn)}matchTimeExpression(){return this.matchPredicate(pn)}matchIdentifierLike(){return this.matchPredicate(un)}matchComparisonOperator(){return this.matchPredicate(ln)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(vn,e)}consumeIdentifierLike(e){return this.consumePredicate(un,e)}consumeEvent(e){return this.consumePredicate(an,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)}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;Yt("⚠️ 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 s="["+i+"]";return{type:"literal",value:s,raw:s,start:e,end:this.previous().end,line:t,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),i=this.tokens[this.current],s=this.tokens[this.current+1];if("identifier"===i?.kind&&("]"===s?.value||s&&r.has(s.value)&&"string"===this.tokens[this.current+2]?.kind)){let e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:e,end:this.previous().end,line:t,column:n}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>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 yr(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&&(Ct(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==At(t,1))if('"'!==n){if("'"===n||"'"===n){const e=At(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||n.kind!==xt.IDENTIFIER&&n.kind!==xt.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)$t(t);else{const e=t.position;Tt(t),Tt(t),Ot(t,xt.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===At(t,1)){const e=t.position;Tt(t),Tt(t),Ot(t,xt.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===xt.IDENTIFIER&&C.has(e.value.toLowerCase()),i=e&&e.kind===xt.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===xt.OPERATOR&&")"!==e.value&&"]"!==e.value||r||i||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(Vt(At(t))||"{"===At(t)||"-"===At(t))){Rt(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===xt.IDENTIFIER&&F.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==xt.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(Ot(t,xt.SYMBOL,"["),Tt(t)):(Ot(t,xt.OPERATOR,"["),Tt(t));continue}if("]"!==n){if("$"===n){const e=At(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){Bt(t);continue}}Ut(n)?Dt(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(Ot(t,xt.UNKNOWN,n),Tt(t)):qt(t):Pt(t)}else Ot(t,xt.OPERATOR,"]"),Tt(t)}else Ot(t,xt.OPERATOR,"}"),Tt(t);else Ot(t,xt.OPERATOR,"{"),Tt(t);else Mt(t)}else Rt(t);else Ht(t)?Lt(t):Dt(t);else It(t)}else $t(t);else jt(t)}return t.tokens}(e);return new pr(n,t,e).parse()}function gr(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 vr(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}async function br(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 Tr(e,t);const n=e;switch(e.type){case"literal":return function(e){return e.value}(n);case"identifier":return Tr(n,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,i=e.left;if("="===n){const n=await br(e.right,t);if("identifier"===i?.type&&"string"==typeof i.name){const e=i.name;return e.startsWith("$")?ce(t,e.slice(1),n):"global"===i.scope?ce(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 br(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 br(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 br(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 br(e.right,t);return gr(t,"styleRef").evaluate(t,i.value.slice(1),n)}if("of"===n){const n=Cr(e.left);if(n){const r=await br(e.right,t);let i=r;for(const e of n){if(null==i)return;i=je(i)?Me(i,e):i[e]}return"function"==typeof i?i.bind(r):i}}const s=await br(e.left,t);if("and"===n){if(!s)return s;const n=await br(e.right,t);return gr(t,"and").evaluate(t,s,n)}if("or"===n){if(s)return s;const n=await br(e.right,t);return gr(t,"or").evaluate(t,s,n)}const o=await br(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(s):s,l=e.ignoringCase?a(o):o;switch(n){case"+":{let n=s,r=o;return e.coerceNumeric&&("string"==typeof n&&(n=be(n)),"string"==typeof r&&(r=be(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:vr(await gr(t,"addition").evaluate(t,{left:n,right:r}))}case"-":return vr(await gr(t,"subtraction").evaluate(t,{left:s,right:o}));case"*":return vr(await gr(t,"multiplication").evaluate(t,{left:s,right:o}));case"/":return vr(await gr(t,"division").evaluate(t,{left:s,right:o}));case"%":case"mod":return vr(await gr(t,"modulo").evaluate(t,{left:s,right:o}));case"^":case"**":return vr(await gr(t,"power").evaluate(t,{left:s,right:o}));case">":case"is greater than":return gr(t,"greaterThan").evaluate(t,s,o);case"<":case"is less than":return gr(t,"lessThan").evaluate(t,s,o);case">=":case"is greater than or equal to":return gr(t,"greaterThanOrEqual").evaluate(t,s,o);case"<=":case"is less than or equal to":return gr(t,"lessThanOrEqual").evaluate(t,s,o);case"==":return gr(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=jr(e,s,o);return void 0!==n?n:gr(t,"equals").evaluate(t,c,l)}case"!=":return gr(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const n=jr(e,s,o);return void 0!==n?!n:gr(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return gr(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return gr(t,"strictNotEquals").evaluate(t,c,l);case"as":return gr(t,"as").evaluate(t,s,Ir(o));case"contains":case"contain":case"includes":case"include":return gr(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return gr(t,"doesNotContain").evaluate(t,c,l);case"starts with":return gr(t,"startsWith").evaluate(t,c,l);case"ends with":return gr(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await gr(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await gr(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return gr(t,"matches").evaluate(t,c,Nr(e.right,l));case"does not match":case"do not match":return!await gr(t,"matches").evaluate(t,c,Nr(e.right,l));case"in":case"is in":case"am in":return Or(s,o);case"is not in":case"am not in":return!Or(s,o);case"of":return o&&"object"==typeof o?o[s]:void 0;case"precedes":return $r(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!$r(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return $r(s,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!$r(s,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,t);case"asExpression":return async function(e,t){const n=await br(e.expression,t),r=Ir(e.targetType);return gr(t,"as").evaluate(t,n,r)}(n,t);case"betweenExpression":return async function(e,t){const n=await br(e.value,t),r=await br(e.min,t),i=await br(e.max,t),s=e=>"string"==typeof e?e.toLowerCase():e,[o,a,c]=e.ignoringCase?[s(n),s(r),s(i)]:[n,r,i],l=await gr(t,"between").evaluate(t,o,a,c);return e.negated?!l:l}(n,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await br(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(n,t);case"collectionExpression":return async function(e,t){const n=await br(e.collection,t);if(null==n)return n;const r=async(e,n)=>br(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=Et(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=[...Et(e)],s=await Promise.all(i.map(e=>r(t,e))),o=i.map((e,t)=>t);o.sort((e,t)=>{const n=s[e],r=s[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.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=Et(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return s=await br(e.right,t),null==(i=n)?[]:(i+"").split(null==s?"":s+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return Et(e).map(e=>null==e?"":e+"").join(n)}(n,await br(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var i,s}(n,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await br(n,t);switch(e.operator){case"not":case"!":return gr(t,"not").evaluate(t,r);case"no":return gr(t,"no").evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return gr(t,"exists").evaluate(t,r);case"does not exist":return gr(t,"doesNotExist").evaluate(t,r);case"is empty":return gr(t,"isEmpty").evaluate(t,r);case"is not empty":return gr(t,"isNotEmpty").evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(n,t);case"memberExpression":return async function(e,t){const n=await br(e.object,t);if(e.computed){const r=await br(e.property,t);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Dr(n,e.property.name,t)}(n,t);case"propertyAccess":return async function(e,t){let n=await br(e.object,t);for(const r of(e.property+"").split(".")){if(null==n)return;n=await Dr(n,r,t)}return n}(n,t);case"callExpression":return async function(e,t){const n=await br(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>br(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,i=await async function(e,t,n){return Pr.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:br(e,n))):Promise.all(e.map(e=>br(e,n)))}(e.arguments,r,t);switch(r){case"closest":return gr(t,"closest").evaluate(t,...i);case"previous":case"next":{const n=e.relativePositional;if(n){const e=n.from?qr(await br(n.from,t)):t.me,s=n.within?qr(await br(n.within,t)):void 0,o=n.inElt?await br(n.inElt,t):void 0;return gr(t,r).evaluate(t,i[0],e,{within:s,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return gr(t,r).evaluate(t,...i)}case"first":return gr(t,"first").evaluate(t,...i);case"last":return gr(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=>br(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const i=await br(e.callee.object,t);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(n,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 gr(t,"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=Hr(e),r=await Promise.all(n.filter(e=>"expr"in e).map(e=>kr(e.expr,t)));return Ur(n,r)}(n,t),s=Fr(e,r);i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await gr(t,"elementWithSelector").evaluate(t,s)}finally{i.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!e.fromQuery&&n.includes("{")&&(n=await function(e,t){return Mr(e,/\{([^}]*)\}/g,async(e,n)=>(await kr(n.trim(),t)??"")+"")}(n,t));const r="string"==typeof n?Fr(e,n):n,i=await gr(t,"elementWithSelector").evaluate(t,r);return!e.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(i)?i[0]??null:i}(n,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return gr(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return gr(t,"me").evaluate(t);case"your":case"yourself":return gr(t,"you").evaluate(t);case"its":return gr(t,"it").evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??gr(t,"me").evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return gr(t,"document").evaluate(t);case"window":return gr(t,"window").evaluate(t);default:return}}(n,t);case"possessiveExpression":return async function(e,t){const n=await br(e.object,t),r=e.property.name;return gr(t,"possessive").evaluate(t,n,r)}(n,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await br(t,r)}}}(n,t);case"conditionalExpression":return async function(e,t){return await br(e.test,t)?br(e.consequent,t):e.alternate?br(e.alternate,t):void 0}(n,t);case"string":return n.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await br(r,t));return n}(n,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let i;i="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await br(e,t)+"",n[i]=await br(r.value,t)}return n}(n,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(n,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await br(e.target,t);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return gr(t,"possessive").evaluate(t,i,r)}(n,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await Mr(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=Lr(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(Lr(n,t)??"")+""}catch{return""}}),n=await Mr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const i=n||r;try{return await kr(i,t)+""}catch{return"undefined"}}),n}(n,t);case"stringPostfix":return async function(e,t){return`${await br(e.expression,t)}${e.unit}`}(n,t);case"blockLiteral":return Rr(n,t);default:{const n=G.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}}}pr.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),pr.PRATT_TABLE=K,pr.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class wr extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function Er(e,t){const n=e;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(e,t){const n=e.value;if("string"!=typeof n)throw new wr("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new wr("selector");if(e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(e,t){const n=Hr(e),r=n.filter(e=>"expr"in e).map(e=>xr(e.expr,t));return Ur(n,r)}(n,t),s=Fr(e,r),o=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new wr("selector");i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(o.querySelectorAll(s))}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)=>(xr(n.trim(),t)??"")+"")}(n,t):n,i=Fr(e,r),s=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new wr("selector");const o=Array.from(s.querySelectorAll(i));return!e.fromQuery&&r.startsWith("#")?o[0]??null:o}(n,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:"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)):void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(n.name,t,n.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 wr("contextReference")}}(n.contextType,t);case"arrayLiteral":return n.elements.map(e=>Er(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:Er(e,t)+"",n[i]=Er(r.value,t)}return n}(n,t);case"asExpression":return pt(Er(n.expression,t),Ir(n.targetType),t);case"stringPostfix":return`${Er(n.expression,t)}${n.unit}`;case"blockLiteral":return Rr(n,t);case"memberExpression":{const e=Er(n.object,t);if(null==e)return;if(e instanceof Element||Array.isArray(e)||"undefined"!=typeof Node&&e instanceof Node)throw new wr("memberExpression");const r=e[n.computed?Er(n.property,t)+"":n.property?.name];return"function"==typeof r?r.bind(e):r}default:throw new wr(n?.type??"unknown")}}function xr(e,t){const n=yr(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return Er(n.node,t)}async function kr(e,t){const n=yr(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 Ar()};return br(n.node,r)}let Sr=null;async function Ar(){if(!Sr){const e=await Promise.resolve().then(function(){return xs});Sr=e.createFullExpressionRegistry()}return Sr}async function Tr(e,t){const n=e.name;return"me"===n||"my"===n||"I"===n?gr(t,"me").evaluate(t):"you"===n||"your"===n||"yourself"===n?gr(t,"you").evaluate(t):"it"===n||"its"===n?gr(t,"it").evaluate(t):"window"===n?gr(t,"window").evaluate(t):"document"===n?gr(t,"document").evaluate(t):"global"===e.scope&&t.globals?.has(n)?(se(n,t),t.globals.get(n)):"element"===e.scope?he(t,n):t.locals&&t.locals.has(n)?(ae(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?(n.startsWith("$")&&se(n.slice(1),t),t.globals.get(n)):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?(se(n.slice(1),t),t.globals.get(n.slice(1))):void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function Cr(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=Cr(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 Or(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 Nr(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function jr(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 $r(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function Ir(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 Rr(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 s={...t,locals:i};try{return Er(e.body,s)}catch(t){if(t instanceof wr)return br(e.body,s);throw t}}}function Lr(e,t){return t.locals?.has(e)?(ae(e,t),t.locals.get(e)):"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function Mr(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 s=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:i}=r[e];s=s.substring(0,t)+i+s.substring(t+n)}return s}function Dr(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?Me(e,t):bt(e)&&!(t in e)?gr(n,"possessive").evaluate(n,e,t):e?.[t]}const Pr=new Set(["closest","previous","next"]);function qr(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const Br=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"),Vr=/[:&()[\]/]/g;function Fr(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace(Br,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(Vr,"\\$&")}(t)}const _r=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Hr(e){const t=[];let n,r=0;for(_r.lastIndex=0;null!==(n=_r.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 Ur(e,t){let n="";const r=[];let i=0;for(const s of e){if("lit"in s){n+=s.lit;continue}const e=t[i++];je(e)?(n+=`[data-hs-query-id='${r.length}']`,r.push(e)):n+=(e??"")+""}return{selector:n,elements:r}}class zr{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&&Qt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&Qt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&Qt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&Qt("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&&Qt("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&&Qt(`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&&Qt("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&Qt(`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&&Qt("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&Qt(`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 s of this.globalCleanups)switch(s.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 Wr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&Qt("[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 Qt("[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()}}class Jr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,n){const r=e.toLowerCase();this.providers.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}registerGlobal(e,t,n){const r=e.toLowerCase();this.globalProviders.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,n){const r=this.get(e);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const e of r.dependencies)await this.resolve(e,t,n);const s=await r.provide(t);return r.cache&&n&&n.set(i,s),s}resolveSync(e,t,n){const r=this.get(e);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);const s=r.provide(t);if(s instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,s),s}enhance(e){const t=this,n=new Map;return new Proxy(e,{get(e,r,i){if("string"==typeof r&&t.get(r))try{return t.resolveSync(r,e,n)}catch{return t.resolve(r,e,n)}return Reflect.get(e,r,i)},has:(e,n)=>!("string"!=typeof n||!t.has(n))||Reflect.has(e,n)})}async resolveAll(e){const t=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,s]of r)try{n[i]=await this.resolve(i,e,t)}catch(e){Qt(`[ContextProviderRegistry] Failed to resolve '${i}':`,e),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Zr={evaluate:(e,t)=>br(e,t)};class Kr{static toTyped(e){return{me:e.me,...void 0!==e.owner&&{owner:e.owner},it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},...void 0!==e.registry&&{registry:e.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class Xr{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(e)?e.join(" | "):e||""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(Xt(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void Xt(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Kr.toTyped(e);let s,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(Xt(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!await br(r,e))return void Xt(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);s=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName},Zr,e)}else s=t;else Xt(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),s=t;if(Xt("CommandAdapterV2: Calling execute with parsed input:",s),2===this.impl.execute.length)o=await this.impl.execute(s,i);else{const e=Array.isArray(s)?s:[s];o=await this.impl.execute(i,...e)}return Xt("CommandAdapterV2: Command result:",o),Object.assign(e,Kr.fromTyped(i,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(e){if(ni(e)||Xt(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class Gr{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);Qt(`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();Qt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new Xr(e,void 0,this.hookRegistry);this.adapters.set(n,r),C.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),C.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 Yr=null;function Qr(){return Yr||(Yr=function(e){const t=e?.commands??new Gr,n=e?.eventSources??new Wr,r=e?.context??new Jr,i=new Set,s={commands:t,eventSources:n,context:r,use(e){if(i.has(e.name))Qt(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:n,options:i}of e.contextProviders)r.register(t,n,i);e.setup?.(s),i.add(e.name)}},reset(){i.clear()}};return s}()),Yr}class ei{constructor(e={}){this.contextCache=new WeakMap;const t=Qr();this.options={enableContextProviders:e.enableContextProviders??!0,enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,Qt(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(e){if(!this.options.enableContextProviders)return e;const t=this.contextCache.get(e);if(t)return t;try{const t=this.contextRegistry.enhance(e);return this.contextCache.set(e,t),Qt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return Qt("[RegistryIntegration] Failed to enhance context: "+(t instanceof Error?t.message:t+"")),e}}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return Qt(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return Qt(`[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 Qt(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,Qt("[RegistryIntegration] Destroyed")}}function ti(e){const t=Error(e.type.toUpperCase()+"_EXECUTION");return t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}function ni(e){return e instanceof Error&&(null!==n(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function ri(e){if(void 0===e)return;let t=e;if(t&&"object"==typeof t){const e=t;if("result"in e&&"wasAsync"in e)t=e.result;else if("result"in e&&"executed"in e){if(t=e.result,e.preserveArrayResult)return void 0!==t?t:void 0}else if("lastResult"in e&&"type"in e)t=e.lastResult;else if("conditionResult"in e&&"executedBranch"in e){if(void 0===e.result)return;t=e.result}else"value"in e&&1===Object.keys(e).length||"value"in e&&"target"in e&&"targetType"in e?t=e.value:"data"in e&&"status"in e&&"headers"in e&&(t=e.data)}return Array.isArray(t)&&t.length>0&&(t=t[0]),t}function ii(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const si=new WeakMap;class oi{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=le,this.hookRegistry=new t,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new zr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new ei("object"==typeof e.registryIntegration?e.registryIntegration:{}),Qt("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&&Qt(`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(),Qt("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){Qt(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.registry||(t.registry=this.expressionRegistry),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,n)=>this.execute(e,n||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return Qt("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(e,t);if(!s(n)){if("return"===n.error.type){const e=n.error.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw ti(n.error)}return n.value}try{return await this.processCommand(e,t)}catch(e){const r=n(e);if(r?.isReturn){const e=r.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw e}case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(n,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=e,r=await this.executeCommandSequenceWithResult(n.commands||[],t);if(!s(r))throw ti(r.error);return r.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(e,t);if(!s(n))throw ti(n.error);return n.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:n,args:r,modifiers:i}=e,s=n.toLowerCase();if(Xt(`RUNTIME BASE: Processing command '${s}'`),this.registry.has(s)){const e=await this.registry.getAdapter(s);if(!e)throw Error(`Command '${s}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:r||[],modifiers:i||{},commandName:s,runtime:this})}catch(e){throw ni(e)||this.logError(`Error executing command '${s}':`,e),e}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(e){const t=n(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:n,args:s,modifiers:o}=e,a=n.toLowerCase();if(Xt(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const c=await this.registry.getAdapter(a);if(!c)throw Error(`Command '${a}' is registered but failed to load adapter.`);try{return r(await c.execute(t,{args:s||[],modifiers:o||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return i(t);throw this.logError(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const i of e){if(this.hasErrorDiagnostics(i)){const e=i.diagnostics?.[0];Qt("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===i.type){const e=await this.processCommandWithResult(i,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}),r(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(i,t);if(!s(e))return e;n=e.value}}return r(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await br(e,n);return ii(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},o=await async function(e,t){try{return r(await br(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return i({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return i({type:"exit",returnValue:t.returnValue});if(t.isBreak)return i({type:"break"});if(t.isContinue)return i({type:"continue"});if(t.isReturn)return i({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!s(o))return o;const a=o.value;if(ii(a)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:a.command,args:[{type:"literal",value:a.selector}]},t);try{return r(await this.executeCommandFromPattern(a.command,a.selector,t))}catch(e){const t=this.toSignal(e);if(t)return i(t);throw e}}return r(a)}async executeCommandFromPattern(e,t,n){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},n)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let n;const r=[],i=[],s=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"initBlock"===t.type?i.push(t):s.push(t);for(const e of r)try{await this.execute(e,t)}catch(e){if(ni(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{n=await this.execute(e,t)}catch(e){if(ni(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{n=await this.execute(e,t)}catch(e){if(ni(e)&&(e.isHalt||e.isExit))break;throw e}return n}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const n of e.commands)try{await this.execute(n,t)}catch(e){if(ni(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let n;for(const r of e.commands)try{n=await this.execute(r,t)}catch(e){if(ni(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return n}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const i=await this.execute(r.value,t);n[e]=i}return n}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:s}=e,o=e.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),Qt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:s}),Qt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){Qt("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&&(Qt(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),Qt(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));Qt("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,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},s=this.enhanceContext(i);if(r.parameters)for(const e of r.parameters)s.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||s.locals.set(e,t);if(r.initBlock){Qt("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),Qt("BEHAVIOR: Init block completed for "+e)}catch(t){if(Qt(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&ni(t)))throw t}}if(Qt(`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,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}Qt("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:n,events:r,commands:i,target:s,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,f=r&&r.length>0?r:[n];Qt(`BEHAVIOR: executeEventHandler: event='${n}', target='${s}'`);let d=[],h=null;if(s){const e="string"==typeof s?s.toLowerCase():"";if("window"===e||"the window"===e)h=window;else if("document"===e||"the document"===e||"body"===e)h=document;else if("me"===e||"myself"===e)d=t.me?[t.me]:[];else if("string"==typeof s&&t.locals.has(s)){const e=t.locals.get(s);Qt(`BEHAVIOR: Target resolution: found local '${s}', isElement: ${this.isElement(e)}`),this.isElement(e)?d=[e]:Array.isArray(e)?d=e.filter(e=>this.isElement(e)):"string"==typeof e&&(d=this.queryElements(e,t))}else Qt(`BEHAVIOR: Target resolution: querying for '${s}'`),d=this.queryElements(s,t)}else d=t.me?[t.me]:[];if(0===d.length&&!h)return void Qt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(d,c,i,t);if("change"===n&&l)return void this.setupChangeObserver(l,i,t);const m=e.customEventSource;if(m&&this.registryIntegration){Qt(`BEHAVIOR: executeEventHandler - Using custom event source '${m}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),s={...t,locals:r,it:e,event:e},o=this.enhanceContext(s);Qt(`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(m,{event:n,handler:e,target:s,selector:a},t);Qt(`BEHAVIOR: Subscribed to custom event source '${m}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${m}' subscription ${r.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${m}':`,e)}return}const p=oi.createEventHandler(this,i,t,a,o);let y,g=null;if(u){let e=p;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},g=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const t=u.throttle;let n=0;y=r=>{const i=Date.now();t>i-n||(n=i,e(r))}}else y=e}else y=p;const v=u?.once?{once:!0}:void 0;if(h){for(const e of f)h.addEventListener(e,y,v),d.length>0?this.cleanupRegistry.registerListener(d[0],h,e,y):this.cleanupRegistry.registerGlobal(()=>h.removeEventListener(e,y),"listener",`Global ${e} listener`);g&&(d.length>0?this.cleanupRegistry.registerCustom(d[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const e of d){for(const t of f){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const n of e){const e=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(e.synthetic=!0,y(e),v?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,y,v),this.cleanupRegistry.registerListener(e,e,t,y)}g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,n,r,i){return async s=>{const o=si.get(s)??0;if(o>=100)return;if(si.set(s,o+1),r&&s.target instanceof Element)try{if(!s.target.matches(r)&&!s.target.closest(r))return}catch{Qt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const a=new Map(n.locals),c={...n,locals:a,it:s,event:s};a.has("target")||c.locals.set("target",s.target);const l=e.enhanceContext(c);if(i&&i.length>0){const e=s,t=e.detail;for(const n of i)l.locals.set(n,e[n]??t?.[n]??null)}for(const n of t)try{const t=ri(await e.execute(n,l));void 0!==t&&Object.assign(l,{it:t,result:t})}catch(t){if(ni(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(l,{it:t.returnValue,result:t.returnValue});break}}throw e.logError("COMMAND FAILED:",t),t}}}setupMutationObserver(e,t,n,r){Qt(`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 s of e)if("attributes"===s.type&&s.attributeName===t){Gt(`MUTATION DETECTED: attribute '${t}' changed on`,i);const e={...r,me:i,it:s,locals:new Map(r.locals)},o=s.oldValue,a=i.getAttribute(t);e.locals.set("oldValue",o),e.locals.set("newValue",a);const c=this.enhanceContext(e);for(const e of n)try{await this.execute(e,c)}catch(e){if(ni(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing mutation handler command:",e)}}});e.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(i,e),Qt("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){Qt("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))),Qt(`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){Gt("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 s=i.oldValue,o=e.textContent;null!==s&&r.locals.set("oldValue",s),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const e of t)try{await this.execute(e,a)}catch(e){if(ni(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing change handler command:",e)}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),Qt("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 Qt(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function ai(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}const ci=Ye({selector:Ke().min(1),single:Ge().optional().default(!1)});function li(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]}new class extends rt{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=nt(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.me,i=this.isElement(r)?r:null,s=this.success(i,"element");return this.trackPerformance(e,t,s,n),s}catch(r){const i=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends rt{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=nt(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.you,i=this.isElement(r)?r:null,s=this.success(i,"element");return this.trackPerformance(e,t,s,n),s}catch(r){const i=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends rt{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=nt(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.it,i={success:!0,value:r,type:this.inferType(r)};return this.trackPerformance(e,t,i,n),i}catch(r){const i=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends rt{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=ci,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const n=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,r,n),r}let r;if(t.single)r=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));r=e.length>0?e:null}const i={success:!0,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(e,t,i,n),i}catch(r){const i=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=t.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}};const ui={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:Fe},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:Fe},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Fe},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Fe},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Fe},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=>Be(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=>Be(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=>Be(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=>Be(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:Fe},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Fe},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Fe},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=>Be(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 li(i,n)},validate:e=>He(e,1,2,"styleRef","property, optional element")??qe(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 li(i,r)},validate:e=>Pe(e,2,"possessiveStyleRef","possessor, property")??qe(e,0,"possessiveStyleRef","possessor")??qe(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 li(i,n)},validate:e=>Pe(e,2,"ofStyleRef","property, reference")??qe(e,0,"ofStyleRef","property")??qe(e,1,"ofStyleRef","reference")}};class fi{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 di=new class{constructor(){this.domQueryCache=new fi(200,3e3),this.exprResultCache=new fi(500,2e3),this.cssMatchCache=new fi(100,5e3),this.formValueCache=new fi(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)})})}};"undefined"!=typeof window&&setInterval(()=>{di.cleanup()},1e4);const hi=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=di.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 mi(){di.cleanup(),hi.getMetrics().memoryUsage>52428800&&hi.reset()}let pi=null;function yi(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 yi(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 gi(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 vi(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 bi(e){try{return yi(e,"_"),!0}catch{return!1}}function wi(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=gi(e),r=gi(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 Ei(e,t);case"!=":return!Ei(e,t);default:return!1}}function Ei(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?Ei(e?1:0,t):"boolean"==typeof t?Ei(e,t?1:0):e+""==t+""}function xi(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function ki(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function Si(e,t,n,r,i,s=!0,o){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:s,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(e=3e4){pi&&clearInterval(pi),pi=setInterval(mi,e)}();const Ai=Ye({left:et().describe("Left operand value"),right:et().describe("Right operand value")}).strict(),Ti=Ye({operand:et().describe("Operand value to negate")}).strict();function Ci(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new class extends rt{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=Ai,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.toBoolean(t.left);if(!i)return this.trackSimple(e,n,!0,"boolean"),this.success(!1,"boolean");const s=this.toBoolean(t.right),o=i&&s;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=Ai,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.toBoolean(t.left);if(i)return this.trackSimple(e,n,!0,"boolean"),this.success(!0,"boolean");const s=this.toBoolean(t.right),o=i||s;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=Ti,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=!this.toBoolean(t.operand);return this.trackSimple(e,n,!0,"boolean"),this.success(i,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Oi=Qe([et(),et()]),Ni=Qe([et(),Ke()]),ji={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){const r=Date.now();try{return Si(this,e,[t,n],t==n,r)}catch(i){throw Si(this,e,[t,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:e=>Ve(e,"equals"),inputSchema:Oi,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},$i={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,n){const r=e.evaluationHistory,i=t===n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"strictEquals")},Ii={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,n){const r=e.evaluationHistory,i=t!=n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"notEquals")},Ri={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,n){const r=e.evaluationHistory,i=t!==n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"strictNotEquals")},Li={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,"<");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"lessThan")},Mi={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,"<=");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"lessThanOrEqual")},Di={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,">");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"greaterThan")},Pi={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,">=");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"greaterThanOrEqual")},qi={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){const r=Date.now();try{return Si(this,e,[t,n],t&&n,r)}catch(i){throw Si(this,e,[t,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:e=>Ve(e,"and"),inputSchema:Oi,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},Bi={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,n){const r=e.evaluationHistory,i=t||n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"or")},Vi={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const n=e.evaluationHistory,r=!t;return n&&Si(this,e,[t],r,n?Date.now():0),r},validate:e=>Pe(e,1,"not","operand")},Fi={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let i;return i=null==t||(Se(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Ce(t)||0!==Object.keys(t).length)),n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"isEmpty","value")},_i={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let i;return i=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:(Se(t),!1)),n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"no","value")},Hi={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=!await Fi.evaluate(e,t);return n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"isNotEmpty","value")},Ui={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=zi(t);return n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"exists","value")};function zi(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const Wi={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=!zi(t);return n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"doesNotExist","value")},Ji={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0;let s;if(t&&n){if(Ci(t)&&Ci(n))return s=t.contains(n),r&&Si(this,e,[t,n],s,i),s;if(Se(t)&&t.match(/^[.#][\w-]+$/)){const o=document.querySelector(t);if(o&&Ci(n))return s=o.contains(n),r&&Si(this,e,[t,n],s,i),s;if(o&&Se(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return s=!!a&&o.contains(a),r&&Si(this,e,[t,n],s,i),s}}if(Se(n)&&n.match(/^[.#][\w-]+$/)&&Ci(t)){const o=document.querySelector(n);return s=!!o&&t.contains(o),r&&Si(this,e,[t,n],s,i),s}}if(Se(t)&&Se(n))s=t.includes(n);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);s=e.includes(n)||n instanceof Node&&e.some(e=>e instanceof Node&&e.contains(n))}else s=!(!Ce(t)||!Se(n))&&n in t;return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"contains","container, value")},Zi={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=!await Ji.evaluate(e,t,n);return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"doesNotContain","container, value")},Ki={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=null!=t&&null!=n&&(t+"").startsWith(n+"");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"startsWith","str, prefix")},Xi={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=null!=t&&null!=n&&(t+"").endsWith(n+"");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"endsWith","str, suffix")},Gi={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){const i=e.evaluationHistory;let s=n,o=r;if(null!=s&&null!=o&&s>o){const e=s;s=o,o=e}const a=null!=s&&null!=o&&t>=s&&o>=t;return i&&Si(this,e,[t,n,r],a,i?Date.now():0),a},validate:e=>Pe(e,3,"between","value, min, max")},Yi={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){const r=Date.now();try{let i;if(t instanceof Element&&Se(n)){const e=n;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{i=function(e,t){return di.matches(e,t)}(t,e)}catch(e){i=!1}else i=!1}else if(Se(t)&&Se(n)){const e=t,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(e)}catch(t){i=e.includes(r)}}else i=!1;return Si(this,e,[t,n],i,r)}catch(i){throw Si(this,e,[t,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:e=>Pe(e,2,"matches","element, selector"),inputSchema:Ni,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},Qi={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0;let s=!1;if(t instanceof Element&&Se(n)){const e=n;e.startsWith(".")?s=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(s=t.hasAttribute(e.slice(1,-1)))}return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"has","element, selector")},es={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=!await Qi.evaluate(e,t,n);return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"doesNotHave","element, selector")},ts={equals:ji,strictEquals:$i,notEquals:Ii,strictNotEquals:Ri,lessThan:Li,lessThanOrEqual:Mi,greaterThan:Di,greaterThanOrEqual:Pi,and:qi,or:Bi,not:Vi,no:_i,isEmpty:Fi,isNotEmpty:Hi,exists:Ui,doesNotExist:Wi,contains:Ji,doesNotContain:Zi,startsWith:Ki,endsWith:Xi,between:Gi,matches:Yi,has:Qi,doesNotHave:es},ns=Ye({value:Ke().describe("String literal value")}).strict(),rs=Ye({value:Xe().describe("Number literal value")}).strict(),is=Ye({value:Ge().describe("Boolean literal value")}).strict(),ss=Ye({left:et().describe("Left operand"),right:et().describe("Right operand")}).strict();const os={stringLiteral:new class extends rt{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=ns,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 s=this.success(i,"string");return this.trackSimple(e,n,!0,i),s}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)?(ae(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends rt{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=rs,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 rt{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=is,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends rt{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=ss,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=yi(t.left,"left operand")+yi(t.right,"right operand");return this.trackSimple(e,n,!0,i),this.success(i,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends rt{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=ss,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=ss.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(Se(e))return e;if(Ae(e))return""+e;if(Te(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends rt{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=ss,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=yi(t.left,"left operand")*yi(t.right,"right operand");return this.trackSimple(e,n,!0,i),this.success(i,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}},as={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},cs=Ye({collection:et().describe("Collection to operate on (array, NodeList, or string)")}).strict(),ls=Ye({collection:et().describe("Collection to access"),index:Xe().describe("Index position to access")}).strict(),us=Ye({collection:et().describe("Collection to select random item from")}).strict();new class extends rt{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=cs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),s=i.length>0?i[0]:void 0,o={success:!0,value:s,type:as[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=cs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),s=i.length>0?i[i.length-1]:void 0,o={success:!0,value:s,type:as[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=ls,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),s=this.normalizeIndex(t.index,i.length),o=s>=0&&i.length>s?i[s]:void 0,a={success:!0,value:o,type:as[this.inferEvaluationType(o)]};return this.trackPerformance(e,t,a,n),a}catch(r){const i=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid at input: "+e.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return 0>e?t+e:e}},new class extends rt{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=us,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection);if(0===i.length){const r={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,r,n),r}const s=i[this.getSecureRandomIndex(i.length)],o={success:!0,value:s,type:as[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid random input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}};const fs={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:Se(n)?n.length>0?n[0]:null:Ce(n)&&"length"in n&&Ae(n.length)&&n.length>0?n[0]:null},validate:e=>_e(e,1,"first","collection")},ds={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 Se(n)?n.length>0?n[n.length-1]:null:Ce(n)&&"length"in n&&Ae(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>_e(e,1,"last","collection")},hs={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!Ae(n))throw Error("Index must be a number");const i=n,s=void 0!==r?r:e.it;if(null==s)return null;if(Array.isArray(s)){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}if(s instanceof NodeList||s instanceof HTMLCollection){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}if(s instanceof Element){const e=s.children,t=0>i?e.length+i:i;return t>=0&&e.length>t?e[t]:null}if(Se(s)){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}if(Ce(s)&&"length"in s&&Ae(s.length)){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}return null},validate:e=>He(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function ms(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?ms(r,t):null}function ps(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?ps(r,t):null}function ys(e,t,n,r){if(n.inSearch){if(null==n.inElt)return;return function(e,t,n,r){const i=Array.from(t??[]),s=[];for(const t of i)(t.matches&&t.matches(n)||t===e)&&s.push(t);for(let t=0;s.length-1>t;t++)if(s[t]===e)return s[t+1];if(r){const e=s[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 gs(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 vs={first:fs,last:ds,at:hs,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r,i]=t,s=r||e.me;return s&&s instanceof Element?n?i?ys(s,n,i,!0):ms(s,n):s.nextElementSibling:null},validate:e=>_e(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,s=r||e.me;return s&&s instanceof Element?n?i?ys(s,n,i,!1):ps(s,n):s.previousElementSibling:null},validate:e=>_e(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,s=i||e.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=gs(e);for(const e of r)if(gs(e)>i)return e;return null}(s,n,o):null},validate:e=>He(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,s=i||e.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=gs(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(i>gs(t))return t}return null}(s,n,o):null},validate:e=>He(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")}};class bs{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=yi(e,"left operand");return{success:!0,value:vi(r+yi(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[ki("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 xi([ki("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return xi([ki("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"),xi([ki("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 bi(n)?bi(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[ki("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[ki("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const ws={addition:new bs,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=yi(e,"left operand");return{success:!0,value:vi(r-yi(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).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=yi(e,"left operand");return{success:!0,value:vi(r*yi(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).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}(yi(e,"left operand"),yi(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).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}(yi(e,"left operand"),yi(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[ki("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 bs).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=yi(e,"left operand"),i=yi(n,"right operand");return{success:!0,value:vi(Math.pow(r,i),"power"),type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).validate(e)}}};function Es(){return ai(ui,ts,yt,vs,wt,os,ws)}var xs=Object.freeze({__proto__:null,conversion:yt,conversionExpressions:yt,createCommonRegistry:function(){return ai(ui,ts,os,yt,vs)},createCoreRegistry:function(){return ai(ui,ts,os)},createExpressionRegistry:ai,createFullExpressionRegistry:Es,createFullRegistry:function(){return ai(ui,ts,os,yt,vs,wt)},logical:ts,logicalExpressions:ts,positional:vs,positionalExpressions:vs,properties:wt,propertiesExpressions:wt,references:ui,referencesExpressions:ui,special:os,specialExpressions:os});function ks(e,t,n,r,i,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),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");s.push(o(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=o(y.get))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&i.unshift(a)}else(a=o(y))&&("field"===c?i.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),d=!0}function Ss(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 As(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"==typeof SuppressedError&&SuppressedError;const Ts=Symbol("command:name"),Cs=Symbol("command:category"),Os=Symbol("command:metadata");function Ns(e){return function(t,n){const r=t;r[Ts]=e.name,r[Cs]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function js(e){return function(t,n){const r=t,i=r[Cs];if(!i)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const s={description:e.description,syntax:e.syntax,examples:e.examples,category:i,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};r[Os]=s,Object.defineProperty(t,"metadata",{value:s,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>s,enumerable:!0,configurable:!1})}}function $s(e){return()=>new e}function Is(e,t){return e?`[${e}] ${t}`:t}function Rs(e,t,n){if(ge(e))return e;if(!e){const e=t.me;if(!e)throw Error(Is(n,"No target element — provide explicit target or ensure context.me is set"));return Ms(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error(Is(n,'Context reference "me" is not available'));return Ms(t.me)}if("it"===r){if(!ge(t.it))throw Error(Is(n,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===r){if(!t.you)throw Error(Is(n,'Context reference "you" is not available'));return Ms(t.you)}const i=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw Error(Is(n,"DOM not available — cannot resolve element selector"));const s=i.querySelector(r);if(!s)throw Error(Is(n,"Element not found with selector: "+r));if(!ge(s))throw Error(Is(n,"Element found but is not an HTMLElement: "+r));return s}throw Error(Is(n,"Invalid target type: "+typeof e))}function Ls(e,t){if(Array.isArray(e))return e.filter(ge);if(ve(e))return Array.from(e).filter(ge);if(ge(e))return[e];if(!e){const e=t.me;return e&&ge(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&ge(t.me)?[t.me]:[];if("it"===n)return ge(t.it)?[t.it]:[];if("you"===n)return t.you&&ge(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(ge)}}return[]}function Ms(e){if(ge(e))return e;throw Error("Value is not an HTMLElement")}function Ds(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(Is(n,'No "me" element in context'));if(!ge(t.me))throw Error(Is(n,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(Is(n,'No "it" value in context'));if(!ge(t.it))throw Error(Is(n,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(Is(n,'No "you" element in context'));if(!ge(t.you))throw Error(Is(n,"context.you is not an HTMLElement"));return t.you;default:throw Error(Is(n,"Unknown possessive: "+e))}}const Ps=["on","from","to","in","with","at"];async function qs(e,t,n,r,i={},s){let o=e;if(i.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Ps.includes(t.name.toLowerCase())})),(!o||0===o.length)&&i.fallbackModifierKey&&s){const e=s[i.fallbackModifierKey];e&&(o=[e])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!ge(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of o){const i=await t.evaluate(e,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(ge(i))a.push(i);else if(ve(i)){const e=Array.from(i).filter(ge);a.push(...e)}else if(Array.isArray(i)){const e=i.filter(ge);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),s=Array.from(r).filter(ge);a.push(...s)}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(!ge(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}class Bs{async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await qs(e.args,t,n,r)}}(e,t,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>ge(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 Vs=(()=>{let e,t,n=[js({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Ns({name:"hide",category:"dom"})],r=[],i=Bs;return t=class extends i{constructor(){super(...arguments),this.mode="hide"}async execute(e,t){for(const t of e.targets)this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>ge(e))}},As(t,"HideCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Fs=$s(Vs);let _s=(()=>{let e,t,n=[js({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Ns({name:"show",category:"dom"})],r=[],i=Bs;return t=class extends i{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>ge(e))&&"string"==typeof t.defaultDisplay}},As(t,"ShowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Hs=$s(_s);function Us(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function zs(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 Ws(e,t){for(const n of e)t(n);return e}function Js(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function Zs(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 Ks(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&&Gs(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&&Gs(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&Gs(n)?[n]:[]}function Xs(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Gs(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Xs(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Ys(e,t){return e.map(e=>{if(Xs(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+"":(Xt(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}function Qs(e){return"string"==typeof e&&e.trim().startsWith("*")}function eo(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 to(e,t,n){e.style.setProperty(t,n)}const no=["dialog","details","summary","select"];function ro(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 io(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=ro(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=ro(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:ro(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=ro(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:ro(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class so{async resolveTargets(e,t,n,r){return qs(e,t,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(e,t,n){return io(e,t,n)}parseClassNames(e){return Ks(e)}isAttribute(e){return Us(e.trim())}isCSSProperty(e){return Qs(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>ge(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 oo=(()=>{let e,t,n=[js({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"]}),Ns({name:"add",category:"dom"})],r=[],i=so;return t=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:s}=function(e){const t=zs(e);return{name:t.name,value:t.value??""}}(i);return{type:"attribute",name:r,value:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const s=await t.evaluate(e.args[1],n);return{type:"styles",styles:{[r]:s+""},targets:await this.resolveTargets(e.args.slice(2),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(e.args.slice(1),t,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=Ys(e.classes,t);n.length>0&&Js(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,Ws(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){Js(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}},As(t,"AddCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const ao=$s(oo);function co(e){return!!e.parentNode&&(e.remove(),!0)}let lo=(()=>{let e,t,n=[js({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"]}),Ns({name:"remove",category:"dom"})],r=[],i=so;return t=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(ge(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&ge(r[0]))return{type:"element",targets:r.filter(e=>ge(e))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:zs(i).name,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),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(e.args.slice(1),t,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=Ys(e.classes,t);n.length>0&&Js(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,Ws(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){Js(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)co(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}},As(t,"RemoveCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const uo=$s(lo);function fo(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 ho(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const n=fo(e);return n?n.milliseconds:t}return t}function mo(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=fo(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function po(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 yo(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 go(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function vo(e){return"DIALOG"===e.tagName}function bo(e){return"DETAILS"===e.tagName}function wo(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&Zs(e,n)}}function Eo(e,t,n,r){const i=wo(e,t,n),s=setTimeout(i,r);return()=>{clearTimeout(s)}}function xo(e,t,n,r){const i=wo(e,t,n),s=()=>{i(),e.removeEventListener(r,s)};return e.addEventListener(r,s,{once:!0}),()=>{e.removeEventListener(r,s)}}function ko(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 So(e){return null==e||""===e}const Ao=/^the\s+(.+?)\s+of\s+(.+)$/i,To=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 Co(e){return"string"==typeof e&&Ao.test(e)}function Oo(e,t){const n=e.match(Ao);if(!n)return null;try{return{element:Rs(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function No(e,t,n){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let i=await t.evaluate(e.target,n);return Array.isArray(i)&&(i=i[0]),ge(i)?{element:i,property:r}:null}(e,t,n);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let i=await t.evaluate(e.object,n);return Array.isArray(i)&&(i=i[0]),ge(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 s=await t.evaluate(e,n);if(Array.isArray(s)&&(s=s[0]),!ge(s))return null;const o=i?.name||i?.value;return o?{element:s,property:o}:null}return null}function jo(e,t){const{element:n,property:r}=e;r.startsWith("*")?to(n,r.substring(1),t+""):ko(n,r,t)}async function $o(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?ho(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 Io(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 no.includes(t)}(t)}(t);if(ge(e)||Array.isArray(e)&&e.every(e=>ge(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 no.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const Ro=$s((()=>{let e,t,n=[js({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),Ns({name:"toggle",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(e){if(!e||"asExpression"!==e.type)return!1;const t=e.targetType,n="string"==typeof t?t:t?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(e.args[0])){r=!0;const t=e.args[0].expression;e={...e,args:[t,...e.args.slice(1)]}}const i=e.args[0],s=i?.name;if("between"===s&&e.args.length>=4){const{duration:r,untilEvent:i}=await $o(e.modifiers,t,n),s=async e=>{const r=e;return"selector"===r?.type?r.value:t.evaluate(e,n)},o=await s(e.args[1]),a=await s(e.args[3]),c=[];for(let t=4;e.args.length>t;t++){const n=e.args[t]?.name;"on"!==n&&"from"!==n&&c.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await qs(c,t,n,"toggle",l,e.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:i}}const o=await No(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,s=1;if("*"===r&&e.args.length>1&&"identifier"===e.args[1].type&&(r="*"+e.args[1].name,s=2),"*"===r&&e.modifiers?.on){const i=e.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:s,untilEvent:o}=await $o(e.modifiers,t,n),a=eo(r);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:s,untilEvent:o}}}}const o=eo(r);if(o){const{duration:r,untilEvent:i}=await $o(e.modifiers,t,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await qs(e.args.slice(s),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await $o(e.modifiers,t,n),{value:l}=await io(i,t,n);if(Co(l)){const e=Oo(l,n);if(e)return{type:"property",target:e}}const{type:u,expression:f}=Io(l,i),d={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:i}=zs(f);return{type:"attribute",name:r,value:i,targets:await qs(e.args.slice(1),t,n,"toggle",d,e.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=eo(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await qs(e.args.slice(1),t,n,"toggle",d,e.modifiers)}}case"element":{let s;if(ge(l))s=[l];else if(Array.isArray(l)&&l.every(e=>ge(e)))s=l;else if(f){const e=document.querySelectorAll(f);s=Array.from(e).filter(e=>ge(e))}else s=await qs([i],t,n,"toggle",d,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}}(s);if("dialog"===o){const i=r?"modal":await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await n.evaluate(e[1],r);if("string"==typeof t){const i=t.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&e.length>=3){const t=await n.evaluate(e[2],r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,n);return{type:"dialog",mode:i,targets:s}}return"details"===o?{type:"details",targets:go(s)}:"select"===o?{type:"select",targets:s}:{type:"classes",classes:Ks(f),targets:s,duration:a,untilEvent:c}}default:{const r=Ks(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await qs(e.args.slice(1),t,n,"toggle",d,e.modifiers),duration:a,untilEvent:c}}}}async execute(e,t){switch(e.type){case"classes":{const n=Ys(e.classes,t);if(0===n.length)return[...e.targets];if(Js(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&Eo(t,"class",n[0],e.duration),e.untilEvent&&xo(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,Ws(e.targets,e=>{Zs(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Eo(t,"attribute",e.name,e.duration),e.untilEvent&&xo(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return Ws(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):Me(t,n)}(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||To.has(r)||To.has(r.toLowerCase())){const n=!t;return jo(e,n),n}if("number"==typeof t){const n=0===t?1:0;return jo(e,n),n}if("string"==typeof t){const r="__ht_"+n,i=e.element[r];return""===t&&void 0!==i?(jo(e,i),i):(e.element[r]=t,jo(e,""),"")}jo(e,!t)}(e.target),[e.target.element];case"dialog":return Ws(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 Ws(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return Ws(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&&Eo(t,"class",e.classA,e.duration),e.untilEvent&&xo(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}},As(t,"ToggleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());const Lo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"put",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=e=>e?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let s=-1,o=null;for(let t=0;e.args.length>t;t++){const n=e.args[t],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&i.includes(c)){s=t,o=c;break}}let a=null,c=null;if(-1===s){const t=i.find(t=>e.modifiers[t]);if(t)a=e.args[0],o=t,c=e.modifiers[t];else if(3>e.args.length){if(2>e.args.length)throw Error("put requires content and position");a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||"into"}else a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||null,c=e.args[2]}else a=e.args.slice(0,s)[0]||null,c=e.args.slice(s+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await t.evaluate(a,n),u=this.mapPosition(o);let f,d,h=null;if(c){const e=r(c),i=await No(c,t,n);if(i)return{value:l,targets:[i.element],position:"replace",memberPath:i.property};if("memberExpression"===e){const e=c.object,r=c.property;if("selector"===e?.type)h=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:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===i||"it"===i){const e=await t.evaluate(c,n);"string"==typeof e&&(h=e)}else h=i}if(h&&r?.name)f=r.name;else if(!h&&!f){const e=await t.evaluate(c,n);"string"==typeof e&&(h=e)}}else if("identifier"===e&&"me"===c.name)h=null;else if("selector"===e||"cssSelector"===e)h=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&Co(e)){const t=Oo(e,n);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?h=e:d=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))h=e;else{const r=await t.evaluate(c,n),i=this.resolveEvaluatedAsElements(r);if(i)return{value:l,targets:i,position:u,memberPath:f};d=e}}else{const e=await t.evaluate(c,n),r=this.resolveEvaluatedAsElements(e);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?h=e:d=e)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(h,n),position:u,memberPath:f}}async execute(e,t){const{value:n,targets:r,position:i,memberPath:s,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,n),t[o]=n,void Object.assign(t,{it:n});if(s)for(const e of r)this.setProperty(e,s,n);else for(const e of r){const t=this.parseValue(n);this.insertContent(e,t,i)}return r}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!ge(t.me))throw Error("put: no target and context.me is null");return[t.me]}const n=Array.from(document.querySelectorAll(e)).filter(e=>ge(e));if(!n.length)throw Error(`No elements: "${e}"`);return n}parseValue(e){return ge(e)?e:null==e?"":e+""}insertContent(e,t,n){if("replace"!==n)if(ge(t)){const r=t;switch(n){case"beforebegin":e.parentElement?.insertBefore(r,e);break;case"afterbegin":e.insertBefore(r,e.firstChild);break;case"beforeend":e.appendChild(r);break;case"afterend":e.parentElement?.insertBefore(r,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t);else ge(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(ge(e))return[e];if(Array.isArray(e)){const t=e.filter(ge);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(ge);return t.length>0?t:null}return null}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,n){const r=t.split(".");let 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}},As(t,"PutCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Mo={"&":"&","<":"<",">":">",'"':""","'":"'"};function Do(e){return e.replace(/[&<>"']/g,e=>Mo[e])}let Po=(()=>{let e,t,n=[js({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"]}),Ns({name:"make",category:"dom"})],r=[];return t=class{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 s="string"==typeof i&&i.startsWith("<")?i:await t.evaluate(r,n);if(null==s)throw Error("Make command requires class name or DOM element expression");"string"==typeof s&&s.startsWith("<")&&(s=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 kr(i[1].trim(),t);null!=n&&(e=Do(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:e})}let s=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,text:i}=r[e];s=s.slice(0,t)+i+s.slice(t+n)}return s}(s,n));const o=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:o,expression:s,constructorArgs:a,variableName:c}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:i}=e,s="string"==typeof n&&n.startsWith("<"),o=s&&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 s=document.createElement(n),o=r.split(/(?=[.#])/);for(const e of o)if(e.startsWith("#")){const t=e.slice(1);t&&(s.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&s.classList.add(t)}return s}(n):s&&/<\/[a-zA-Z]/.test(n)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstElementChild;if(n&&ge(n))return n;const r=document.createElement("div");r.innerHTML=e.trim();const i=r.firstElementChild;return i&&ge(i)?i:r}(n):function(e,t,n){if(ge(e))return e;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:o}),i&&Ee(i,o,t),o}},As(t,"MakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const qo=$s(Po),Bo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"empty",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ge(e))}},As(t,"EmptyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Vo(e){return e.hasAttribute("popover")}const Fo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"open",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=go(await qs(r,t,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)),s=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e){const t=e.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}for(let t=0;e.length-1>t;t++){const 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:s}}async execute(e,t){for(const t of e.targets)if(vo(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(bo(t))t.open=!0;else if(Vo(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=>ge(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}},As(t,"OpenCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function _o(e){return e.hasAttribute("popover")}const Ho=$s((()=>{let e,t,n=[js({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"]}),Ns({name:"close",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:go(await qs(e.args,t,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(vo(t))t.open&&t.close();else if(bo(t))t.open=!1;else if(_o(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=>ge(e))}},As(t,"CloseCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Uo(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const zo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"select",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(Uo(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=>ge(e))}},As(t,"SelectCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Wo(e){return"FORM"===e.tagName}const Jo=$s((()=>{let e,t,n=[js({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"]}),Ns({name:"reset",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)Wo(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=>ge(e))}},As(t,"ResetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Zo(e,t,n,r){return e?new Promise(n=>{const i=()=>{s({event:null,timedOut:!1,cancelled:!0})},s=Xo(()=>{e.removeEventListener(t,o),r&&r.removeEventListener("abort",i)},n),o=e=>{s({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,o),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function Ko(e){return new Promise(t=>setTimeout(t,e))}function Xo(e,t){let n=!1;return r=>{n||(n=!0,e(),t(r))}}const Go=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"wait",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,n);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n);const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await Ko(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,i=(await Zo(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:mo(await t.evaluate(e,n))}}async parseEventWait(e,t,n,r){const i=await n.evaluate(e,r);if("string"!=typeof i)throw Error("wait for: event name must be a string");const s=i.match(/^(\w+)\(([^)]+)\)$/),o=s?s[1]:i,a=s?s[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(e,t,n,r){const i=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",n=[];for(const r of e.properties){const e=r.key?.name||r.key?.value;"name"===e&&r.value?t=r.value.value||"":"args"===e&&r.value?.elements&&(n=r.value.elements.map(e=>e.value||e.name||""))}t&&i.push({name:t,params:n})}}let s;if(t){const e=await n.evaluate(t,r);e&&"object"==typeof e&&"addEventListener"in e&&(s=e)}return s||(s=r.me??void 0),1===i.length?{type:"event",eventName:i[0].name,target:s,destructure:i[0].params.length>0?i[0].params:void 0}:{type:"race",conditions:i.map(e=>({type:"event",eventName:e.name,target:s,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,n){const r=[];e.modifiers.for?r.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n)):e.args[0]&&r.push(await this.parseTimeWait(e.args[0],t,n));const i=await t.evaluate(e.modifiers.or,n),s=Array.isArray(i)?i:[i];for(const e of s)try{r.push({type:"time",milliseconds:mo(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);r.push(t?{type:"event",eventName:t[1],target:n.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(e,t){const n=new AbortController,r=n.signal,i=e.map(e=>"time"===e.type?Ko(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Zo(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()}}},As(t,"WaitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Yo=new Map;let Qo=[/^4\d{2}$/,/^5\d{2}$/],ea=(()=>{let e,t,n=[js({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),Ns({name:"fetch",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),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:s}=e,o=new AbortController;let a;t.me&&(a=()=>o.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...s,signal:o.signal},l=Yo.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;s.timeout&&(u=setTimeout(()=>o.abort(),s.timeout));try{let s=await fetch(r,c);if(t.me){const e={response:s};this.dispatchEvent(t.me,"fetch:afterResponse",e),s=e.response}if(e.throwOnError&&function(e){const t=e+"";return Qo.some(e=>e.test(t))}(s.status)){const e=Error(`Fetch failed for ${r}: HTTP ${s.status} ${s.statusText}`.trim());throw e.response=s,e.isFetchStatusError=!0,e}const o=await this.handleResponse(s,i,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:o});const a={status:s.status,statusText:s.statusText,headers:s.headers,data:o,url:s.url,duration:Date.now()-n};return Object.assign(t,{it:o}),a}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r)throw Error("fetch: URL must be a non-empty string");return r}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(Yo.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=Yo.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&&ge(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}},As(t,"FetchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const ta=$s(ea),na=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"set",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],i=r?.name||r?.value,s=r?.scope,o=r?.type;if(o){const i=ie(o);if(i)return{type:"node-write",node:r,value:await this.extractValue(e,t,n),writer:i}}const a=await this.resolveAttributeWriteTarget(r,e,t,n);if(a){const r=await this.extractValue(e,t,n);return{type:"attribute",elements:a.elements,name:a.name,value:r}}const c=await No(r,t,n);if(c){const r=await this.extractValue(e,t,n);if(c.property.startsWith("*")){const e=c.property.substring(1);return{type:"style",element:c.element,property:e,value:r+""}}return{type:"property",element:c.element,property:c.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,e,t,n);if(i)return i}let l;if(l="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(ge(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(l))return{type:"object-literal",properties:l,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(Co(l)){const r=Oo(l,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(l,e,t,n)}if("string"==typeof l&&Qs(l)){const r=l.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 l&&Us(l)){const r=l.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 l){const r=l.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=Ds(r[1],n),s=await this.extractValue(e,t,n);return{type:"property",element:i,property:r[2],value:s}}}if(ge(l))return{type:"property",element:l,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(l)&&l.length>0&&ge(l[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:l[0],property:"textContent",value:r}}if("string"!=typeof l)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===l?"null":typeof l} — check that all intermediate objects exist)`:""));return{type:"variable",name:l,value:await this.extractValue(e,t,n),scope:"element"===s||"global"===s?s:void 0}}async execute(e,t){switch(e.type){case"variable":return"element"===e.scope?me(t,e.name,e.value):"global"===e.scope?Ee(e.name,e.value,t,"global"):Ee(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 ko(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return to(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))ko(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 resolveAttributeWriteTarget(e,t,n,r){const i=e;if("attributeAccess"===i?.type)return{elements:await this.resolveTargets(t.modifiers.on,n,r),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const e=await this.evaluateToElement(i.right,n,r);if(e)return{elements:[e],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const e=await this.evaluateToElement(i.object,n,r);if(e)return{elements:[e],name:i.property.attributeName}}return null}async evaluateToElement(e,t,n){const r=await t.evaluate(e,n),i=Array.isArray(r)?r[0]:r;return ge(i)?i:null}async tryParseMemberExpression(e,t,n,r){const i=e.object,s=e.property;if(i?.name&&s?.name){const e=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const i=Ds(e,r),o=await this.extractValue(t,n,r);return{type:"property",element:i,property:s.name,value:o}}}const o=e.object,a=e.computed;if(o){const i=o;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(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const i=a?await n.evaluate(e.property,r)+"":s?.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.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(r>=0&&e.args.length>r+1)return t.evaluate(e.args[r+1],n);if(e.args.length>=2)return t.evaluate(e.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return Rs(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return Ls(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[,s,o]=i,a=Rs(o,r),c=await this.extractValue(t,n,r);return{type:"property",element:a,property:s.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(ge)&&"value"in t;case"property":return"string"==typeof t.property&&ge(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&ge(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}}},As(t,"SetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),ra=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"get",category:"data"})],r=[];return t=class{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}},As(t,"GetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function ia(e){return e&&"object"==typeof e&&e.type||"unknown"}let sa=(()=>{let e,t,n=[js({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"]}),Ns({name:"increment",category:"data"})],r=[];return t=class{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 s,o,a;const c=ia(i);if("identifier"===c)s=i.name,i.scope&&(o=i.scope);else if("literal"===c)s=i.value;else{const e=ie(c);if(e){const r=await t.evaluate(i,n),o="number"==typeof r?r:null==r?0:Number(r)||0;s=o,a={node:i,writer:e,currentValue:o}}else{const e=await t.evaluate(i,n);s=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=o;for(let r=1;e.args.length>r;r++){const i=e.args[r];if(i&&"literal"===i.type){const e=i.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(i&&"literal"!==i.type){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"===ia(f)&&"number"==typeof e)l=e;else if("literal"!==ia(f)){const e=await t.evaluate(f,n);"number"==typeof e&&(l=e)}}return{target:s,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:s=1,operation:o="increment",customWrite:a}=e;if(a){const e=isFinite(s)?s:1,n="increment"===o?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(ge(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?be(n.getAttribute(t)):be(n[t]):be(n.value||n.textContent)}return"string"==typeof e?"element"===n?be(we(e,r,"element")):"global"===n?be(we(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],i=xe(n[0],t);return i?be(i[r]):0}(e,r):be("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:we(e,r)):be(e)}(n,r,i,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(s)?s:1;l="increment"===o?c+e:c-e}return function(e,t,n,r,i){if(ge(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 Ee(e,r,i,"element");if("global"===n)return void Ee(e,r,i,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),i=r[1],s=xe(r[0],n);s&&(s[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);Ee(e,r,i)}}(n,r,i,l,t),Object.assign(t,{it:l}),l}},As(t,"NumericModifyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const oa=$s(sa),aa=$s(sa),ca=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"default",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("default command requires a target");const r=await t.evaluate(e.args[0],n);let i;if(e.modifiers?.to)i=await t.evaluate(e.modifiers.to,n);else{if(2>e.args.length)throw Error('default command requires a value (use "to <value>")');i=await t.evaluate(e.args[1],n)}return{target:r,value:i}}async execute(e,t){const{target:n,value:r}=e;if("string"==typeof n){if(n.startsWith("@"))return this.defaultAttribute(t,n.substring(1),r);const e=n.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,n,i]=e;return this.defaultElementProperty(t,n,i,r)}return this.defaultVariable(t,n,r)}if(ge(n))return this.defaultElementValue(t,n,r);throw Error("Invalid target type: "+typeof n)}defaultVariable(e,t,n){const r=we(t,e);return null!=r?{target:t,value:n,wasSet:!1,existingValue:r,targetType:"variable"}:(Ee(t,n,e),Object.assign(e,{it:n}),{target:t,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,n){if(!e.me)throw Error("No element context available for attribute default");const r=e.me.getAttribute(t);return null!==r?{target:"@"+t,value:n,wasSet:!1,existingValue:r,targetType:"attribute"}:(e.me.setAttribute(t,n+""),Object.assign(e,{it:n}),{target:"@"+t,value:n,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,n,r){const i=Ds(t,e,"default"),s=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]}(i,n),o=`${t} ${n}`;return So(s)?(ko(i,n,r),Object.assign(e,{it:r}),{target:o,value:r,wasSet:!0,targetType:"property"}):{target:o,value:r,wasSet:!1,existingValue:s,targetType:"property"}}defaultElementValue(e,t,n){const r=function(e){return"value"in e?e.value:e.textContent}(t);return So(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"}}},As(t,"DefaultCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function la(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const ua=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"clear",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args?.[0],i=r?.type,s=r?.name;if(r&&("variable"===i||"identifier"===i&&"string"==typeof s))try{const e=await t.evaluate(r,n);if(!ge(e)&&!Array.isArray(e))return{type:"variable",name:s}}catch{return{type:"variable",name:s}}return{type:"form-fields",targets:await qs(e.args,t,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return t.locals.set(e.name,null),void Object.assign(t,{it:null});for(const t of e.targets)la(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=>ge(e))}return!1}},As(t,"ClearCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function fa(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 da=(()=>{let e,t,n=[js({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),Ns({name:"trigger",category:"event"})],r=[];return t=class{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 s=e=>e?.type||"unknown",o=e.args[0];let a,c,l;if("functionCall"===s(o)||"callExpression"===s(o)){a=o.name||o.callee?.name;const e=o.args||o.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===s(o)||"keyword"===s(o))a=o.name;else{const e=await t.evaluate(o,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,n,i);else{const r=e.args.findIndex((e,t)=>{if(0===t)return!1;const n=e.name||e.value;return"on"===n||"to"===n});if(-1!==r&&e.args.length-1>r){const s=e.args.slice(r+1),o=s.findIndex(e=>"with"===(e.name||e.value)),a=-1===o?s:s.slice(0,o);l=await this.resolveTargets(a,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.args,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const 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(ge(e))i.push(e);else if(e instanceof NodeList)i.push(...Array.from(e).filter(ge));else if(Array.isArray(e))i.push(...e.filter(ge));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(ge));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()]=fa(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},i=e.findIndex(e=>"with"===(e.name||e.value));if(-1===i)return r;for(const s of e.slice(i+1)){const e=await t.evaluate(s,n);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?r.bubbles=!0:"nobubbles"===t?r.bubbles=!1:"cancelable"===t?r.cancelable=!0:"nocancelable"===t?r.cancelable=!1:"composed"===t&&(r.composed=!0)}}return r}},As(t,"EventDispatchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const ha=$s(da),ma=$s(da),pa=$s((()=>{let e,t,n=[js({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),Ns({name:"go",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{args:[]}}async execute(e,t){const{args:n}=e;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,t),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}findBareUrl(e){for(const t of e)if("to"!==t&&"the"!==t)return"string"==typeof t&&this.isBareUrl(t)?t:null;return null}async navigateToBareUrl(e,t){if(t.includes("new")&&t.includes("window")){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e));return e}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const n=e.findIndex(e=>"url"===e),r=e[n+1];if(!r)throw Error('URL is required after "url" keyword');const i="string"==typeof r?r:r+"",s=e.includes("new")&&e.includes("window");if(!this.isValidUrl(i))throw Error(`Invalid URL: "${i}"`);if(s){if("undefined"!=typeof window&&window.open){const e=window.open(i,"_blank");e?.focus&&e.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const n=this.parseScrollPosition(e),r=this.parseScrollTarget(e),i=this.parseScrollOffset(e),s=!e.includes("instantly"),o=this.resolveScrollTarget(r,t);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const e=s?"smooth":"instant",t=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){o.scrollIntoView?.({behavior:e,block:t,inline:r});const{x:s,y:a}=this.calculateScrollPosition(o,n,i);window.scrollTo?.({left:s,top:a,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:r})}return o}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,s=!1;for(const o of e)"string"==typeof o&&(n.includes(o)?(t.vertical=o,i=!0):r.includes(o)&&(t.horizontal=o,s=!0));return s&&!i&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let n=e[t+1];return"the"===n&&e.length>t+2&&(n=e[t+2]),n}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!n.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const n=e[t];if("string"==typeof n){const e=n.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===n||"-"===n)&&e.length>t+1){const r=e[t+1],i="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&ge(t.me))return t.me;if("it"===n&&ge(t.it))return t.it;if("you"===n&&ge(t.you))return t.you;const r=we(n,t);if(ge(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=e.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,s=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=i,l=s;switch(t.horizontal){case"left":c=r.left+i;break;case"center":c=r.left+i+r.width/2-o/2;break;case"right":c=r.right+i-o}switch(t.vertical){case"top":l=r.top+s+n;break;case"middle":l=r.top+s+r.height/2-a/2+n;break;case"bottom":l=r.bottom+s-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}},As(t,"GoCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function ya(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=we(e,t);return void 0!==n?!!n:!!e}return!!e}const ga=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"if",category:"control-flow"})],r=[];return t=class{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,s;if("unless"===r){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");i=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(i=e.args[1],s=3>e.args.length?void 0:e.args[2]):e.modifiers?.then&&(i=e.modifiers.then,s=e.modifiers.else),!i)throw Error('if command requires "then" branch with commands');return{mode:r,condition:await t.evaluate(e.args[0],n),thenCommands:i,elseCommands:s}}async execute(e,t){const{mode:n,condition:r,thenCommands:i,elseCommands:s}=e,o=ya(r,t);let a,c;return("unless"===n?!o:o)?(a="then",c=await this.executeCommandsOrBlock(i,t),"unless"===n&&Object.assign(t,{it:c})):s&&"if"===n?(a="else",c=await this.executeCommandsOrBlock(s,t)):a="none",{mode:n,conditionResult:o,executedBranch:a,result:c}}async executeCommandsOrBlock(e,t){return"block"===e?.type?this.executeBlock(e,t):Array.isArray(e)?this.executeCommands(e,t):e}async executeBlock(e,t){const n=t.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let r;if(e.commands?.length)for(const i of e.commands)r=await n(i,t);return r}async executeCommands(e,t){let n;for(const r of e)n=r?.execute?await r.execute(t):"function"==typeof r?await r():r;return n}},As(t,"ConditionalCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),va=ga,ba=ga;let wa=(()=>{let e,t,n=[js({description:"Iteration in hyperscript - for-in, counted, conditional, event-driven, and infinite loops",syntax:["repeat for <var> in <collection> { <commands> }","repeat <count> times { <commands> }","repeat while <condition> { <commands> }","repeat until <condition> { <commands> }","repeat forever { <commands> }"],examples:["repeat for item in items { log item }",'repeat 5 times { log "hello" }'],sideEffects:["iteration","conditional-execution"]}),Ns({name:"repeat",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){let r;if(e.modifiers?.index){const i=await t.evaluate(e.modifiers.index,n);"string"==typeof i&&(r=i)}let i,s=e.modifiers?.block||e.modifiers?.commands;if(!s){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(r),2===t.length))break}2===t.length?(s=t[0],i=t[1]):1===t.length&&(s=t[0])}const o=e.args[0],a="identifier"===o?.type?o.name:null,c=!!e.modifiers?.bottomTested&&await t.evaluate(e.modifiers.bottomTested,n);if("for"===a||e.modifiers?.for){const o=e.args[1],a=o?.value||o?.name,c=e.args[2]?await t.evaluate(e.args[2],n):void 0;if(!a||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:a,collection:Array.isArray(c)?c:[c],indexVariable:r,commands:s,elseCommands:i}}if("times"===a||e.modifiers?.times){const o=e.args[1],a=o?await t.evaluate(o,n):void 0,c="number"==typeof a?a:parseInt(a+"",10);if(isNaN(c))throw Error("times loops require a count number");return{type:"times",count:c,indexVariable:r,commands:s,elseCommands:i}}if("while"===a||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw Error("while loops require a condition");return{type:"while",condition:t,indexVariable:r,commands:s,elseCommands:i,bottomTested:c}}if("until"===a&&e.modifiers?.from||"until-event"===a){const o=e.args[1],a=o?.value||o?.name;if(!a)throw Error("until-event loops require an event name");let c=n.me;if(e.args[2]){const r=e.args[2];if("identifier"===r?.type&&"document"===r.name)c=document;else if("identifier"===r?.type&&"window"===r.name&&"undefined"!=typeof window)c=window;else{const r=await t.evaluate(e.args[2],n);r instanceof EventTarget?c=r:"document"===r?c=document:"undefined"!=typeof window&&r===window&&(c=window)}}return{type:"until-event",eventName:a,eventTarget:c,indexVariable:r,commands:s,elseCommands:i}}if("until"===a||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw Error("until loops require a condition");return{type:"until",condition:t,indexVariable:r,commands:s,elseCommands:i,bottomTested:c}}if("forever"===a||e.modifiers?.forever)return{type:"forever",indexVariable:r,commands:s,elseCommands:i};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:n,variable:r,collection:i,condition:s,count:o,indexVariable:a,commands:c,elseCommands:l,bottomTested:u,eventName:f,eventTarget:d}=e;let h,m;switch(n){case"for":({config:h,iterCtx:m}=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}}}(i,r,a));break;case"times":({config:h,iterCtx:m}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(o,a));break;case"while":({config:h,iterCtx:m}=function(e,t,n,r){return{config:{type:"while",shouldContinue:()=>t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(s,ya,t,a));break;case"until":({config:h,iterCtx:m}=function(e,t,n,r){return{config:{type:"until",shouldContinue:()=>!t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(s,ya,t,a));break;case"until-event":({config:h,iterCtx:m}=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}}(f,d,a));break;case"forever":({config:h,iterCtx:m}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(a));break;default:throw Error("Unknown repeat type: "+n)}if(u){const e=h.shouldContinue;h.shouldContinue=async t=>0===t.index||await e(t)}try{const e=await async function(e,t,n,r,i){const s=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(;s>a&&await e.shouldContinue(r);){e.beforeIteration&&await e.beforeIteration(r,n),r.indexVariable&&n.locals&&n.locals.set(r.indexVariable,a);try{o=await i(t,n)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){c=!0;break}if(t.message.includes("CONTINUE")){a++,r.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}a++,r.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!r.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:a,lastResult:o,interrupted:c}}(h,c,t,m,this.executeCommands.bind(this));if(0===e.iterations&&!e.interrupted&&l){const e=await this.executeCommands(l,t);return Object.assign(t,{it:e}),{type:n,iterations:0,completed:!0,lastResult:e}}return Object.assign(t,{it:e.lastResult}),{type:n,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:n,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const n=e,r=t.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let i;if(n.commands)for(const e of n.commands)i=await r(e,t);return i}if(Array.isArray(e)){let n;for(const r of e)n="function"==typeof r?await r(t):r&&"function"==typeof r.execute?await r.execute(t):r;return n}return"function"==typeof e?await e(t):e}},As(t,"RepeatCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const Ea=$s(wa);class xa{async parseInput(e,t,n){return{signalType:this.signalType}}async execute(e,t){const n=Error(this.errorMessage);throw n[this.errorFlag]=!0,"exit"===this.signalType&&(n.returnValue=void 0,n.timestamp=Date.now()),n}}let ka=(()=>{let e,t,n=[js({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"]}),Ns({name:"break",category:"control-flow"})],r=[],i=xa;return t=class extends i{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},As(t,"BreakCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Sa=$s(ka);let Aa=(()=>{let e,t,n=[js({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"]}),Ns({name:"continue",category:"control-flow"})],r=[],i=xa;return t=class extends i{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},As(t,"ContinueCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Ta=$s(Aa),Ca=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"halt",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(e.args&&e.args.length>0){const r=e.args[0];return!r||"the"!==r.name&&"the"!==r.value?{target:await t.evaluate(e.args[0],n)}:{target:n.event}}return{}}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}}"halted"in t&&(t.halted=!0);const r=Error("HALT_EXECUTION");throw r.isHalt=!0,r}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},As(t,"HaltCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Oa=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"return",category:"control-flow"})],r=[];return t=class{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;"returnValue"in t&&(t.returnValue=n),Object.assign(t,{it:n});const r=Error("RETURN_VALUE");throw r.isReturn=!0,r.returnValue=n,r}},As(t,"ReturnCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());let Na=(()=>{let e,t,n=[js({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"]}),Ns({name:"exit",category:"control-flow"})],r=[],i=xa;return t=class extends i{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},As(t,"ExitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const ja=$s(Na),$a=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"throw",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],n)}}async execute(e,t){const{message:n}=e;let r;throw r=n instanceof Error?n:Error("string"==typeof n?n:n+""),r}},As(t,"ThrowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ia=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"call",category:"execution"})],r=[];return t=class{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 br(n,t);let s,o,a=!1;return"function"==typeof i?(o="function",s=i(),s instanceof Promise&&(a=!0,s=await s)):i instanceof Promise?(o="promise",a=!0,s=await i):(o="value",s=i),Object.assign(t,{it:s,result:s}),{result:s,wasAsync:a,expressionType:o}}},As(t,"CallCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());class Ra{constructor(){this.name="pseudo-command"}get metadata(){return Ra.metadata}async parseInput(e,t,n){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const r=e.args[0].properties||[];let i,s,o="",a=[];for(const e of r){const r=e.value;switch(e.key?.name||e.key?.value){case"methodName":o=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":s=await t.evaluate(r,n)}}if(!o)throw Error("pseudo-command requires method name");if(null==s)throw Error("pseudo-command requires a target expression");return{methodName:o,methodArgs:a,preposition:i,targetExpression:s}}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 s,o;const a=["from","on","with","into","at","to"];for(const r of a)if(e.modifiers?.[r]){o=r,s=await t.evaluate(e.modifiers[r],n);break}if(s||3>e.args.length||(s=await t.evaluate(e.args[2],n)),!s)throw Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:o,targetExpression:s}}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 s=this.resolveMethod(e,n);if(!s)throw Error(`Method "${n}" not found on target object`);if("function"!=typeof s)throw Error(`"${n}" is not a function (it's a ${typeof s})`);const o=await this.executeMethod(s,e,r);return t.locals.set("result",o),Object.assign(t,{it:o}),{result:o,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+""))}}}Ra.metadata={description:"Treat a method on an object as a top-level command",syntax:["<method>(<args>) [(to|on|with|into|from|at)] <expression>"],examples:['getElementById("d1") from the document',"reload() the location of the window",'setAttribute("foo", "bar") on me',"foo() on me"],category:"execution",sideEffects:["method-execution"]};const La=$s((()=>{let e,t,n=[js({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"]}),Ns({name:"focus",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ge(e))}},As(t,"FocusCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ma=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"blur",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ge(e))}},As(t,"BlurCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Da=$s((()=>{let e,t,n=[js({description:"Add content to the end of a string, array, or HTML element",syntax:["append <content>","append <content> to <target>"],examples:['append "Hello"','append "World" to greeting',"append item to myArray",'append "<p>New</p>" to #content'],sideEffects:["data-mutation","dom-mutation"]}),Ns({name:"append",category:"content"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("append requires content");const r=await t.evaluate(e.args[0],n);let i;if(e.modifiers?.to){const r=e.modifiers.to,s=r.type;i="identifier"!==s&&"variable"!==s&&"symbol"!==s||"string"!=typeof r.name?await t.evaluate(e.modifiers.to,n):r.name}else e.target&&(i=e.target);return{content:r,target:i}}async execute(e,t){const{content:n,target:r}=e,i=n+"";if(!r)return Object.assign(t,void 0===t.it?{it:i}:{it:t.it+""+i}),{result:t.it,targetType:"result"};if("string"==typeof r){if(r.startsWith("#")||r.startsWith(".")||r.includes("[")){const e=this.resolveDOMElement(r);return e.innerHTML+=i,{result:e,targetType:"element",target:e}}if("me"===r||"it"===r||"you"===r){const e=this.resolveContextRef(r,t);if(ge(e))return e.innerHTML+=i,{result:e,targetType:"element",target:e}}const e=we(r,t);if(void 0!==e){if(ge(e))return e.innerHTML+=i,{result:e,targetType:"element",target:e};if(Array.isArray(e))return e.push(n),{result:e,targetType:"array",target:r};const s=(null==e?"":e+"")+i;return Ee(r,s,t),{result:s,targetType:"variable",target:r}}return Ee(r,i,t),{result:i,targetType:"variable",target:r}}if(Array.isArray(r))return r.push(n),{result:r,targetType:"array"};if(ge(r))return r.innerHTML+=i,{result:r,targetType:"element",target:r};{const e=r+""+i;return Object.assign(t,{it:e}),{result:e,targetType:"string"}}}resolveDOMElement(e){if("undefined"==typeof document)throw Error("DOM not available");const t=document.querySelector(e);if(!t)throw Error("Element not found: "+e);return t}resolveContextRef(e,t){switch(e){case"me":return t.me;case"it":return t.it;case"you":return t.you;default:throw Error("Unknown context ref: "+e)}}},As(t,"AppendCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Pa=$s((()=>{let e,t,n=[js({description:"Animate CSS properties using CSS transitions",syntax:"transition <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"]}),Ns({name:"transition",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("transition requires property and value");let r,i;const s=await t.evaluate(e.args[0],n);if(ge(s)||"string"==typeof s&&/^[#.]|^(?:me|it|you)$/.test(s)?(i=s,r=await t.evaluate(e.args[1],n)+""):r=s+"",!r)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let o=await t.evaluate(e.modifiers.to,n);void 0===o&&"identifier"===e.modifiers.to.type&&(o=e.modifiers.to.name);const a={property:r,value:o};return void 0!==i&&(a.target=i),e.modifiers?.over&&(a.duration=await t.evaluate(e.modifiers.over,n)),e.modifiers?.with&&(a.timingFunction=await t.evaluate(e.modifiers.with,n)+""),a}async execute(e,t){let{property:n}=e;const{target:r,value:i,duration:s,timingFunction:o}=e;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const a=Rs(r,t,"transition"),c=ho(s,300),l=getComputedStyle(a).getPropertyValue(n),u=a.style.transition,f=`${n} ${c}ms ${o||"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&&o({completed:!0,cancelled:!1})},s=n=>{n.target===e&&n.propertyName===t&&o({completed:!1,cancelled:!0})},o=Xo(()=>{e.removeEventListener("transitionend",i),e.removeEventListener("transitioncancel",s),clearTimeout(a)},r);e.addEventListener("transitionend",i),e.addEventListener("transitioncancel",s);const a=setTimeout(()=>{o({completed:!0,cancelled:!1})},n+50)})}(a,n,c);return a.style.transition=u,h&&a.style.removeProperty(n),Object.assign(t,{it:a}),{element:a,property:n,fromValue:l,toValue:d,duration:c,completed:m.completed}}},As(t,"TransitionCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),qa=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"measure",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){let r,i,s;if(e.args?.length){const s=e.args[0];if("identifier"===s.type&&s.name){const o=s.name.toLowerCase();if("me"===o||"it"===o||"you"===o){const o=await t.evaluate(s,n);if(ge(o)&&(r=o,e.args.length>1)){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else i=s.name}else{const o=await t.evaluate(s,n);if(ge(o)||"string"==typeof o&&/^[#.]/.test(o)){if(r=o,e.args.length>1){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else"string"==typeof o&&(i=o)}}e.modifiers?.set&&(s=await t.evaluate(e.modifiers.set,n)+"");const o={};return void 0!==r&&(o.target=r),void 0!==i&&(o.property=i),void 0!==s&&(o.variable=s),o}async execute(e,t){const n=Rs(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(),s={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(s[r])return{value:s[r](),unit:"px"};const o=n.getPropertyValue(t),a=parseFloat(o);if(!isNaN(a)){const e=o.match(/([a-zA-Z%]+)$/);return{value:a,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},As(t,"MeasureCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ba=$s((()=>{let e,t,n=[js({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),Ns({name:"settle",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){let r,i;if(e.args&&e.args.length>0){const i=await t.evaluate(e.args[0],n);(ge(i)||"string"==typeof i&&(i.startsWith("#")||i.startsWith(".")||"me"===i||"it"===i||"you"===i))&&(r=i)}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=Rs(n,t,"settle"),s=ho(r,5e3),o=Date.now(),a=getComputedStyle(i),c=po(a.transitionDuration),l=po(a.transitionDelay),u=po(a.animationDuration),f=po(a.animationDelay),d=yo(c,l),h=yo(u,f),m=Math.max(d,h),p=await(y=i,g=m,v=s,g>0?new Promise(e=>{const t=e=>{e.target===y&&r({completed:!0,type:"transition"})},n=e=>{e.target===y&&r({completed:!0,type:"animation"})},r=Xo(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(s)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},g+50),s=setTimeout(()=>{r({completed:!1,type:"timeout"})},v)}):Promise.resolve({completed:!0,type:"timeout"}));var y,g,v;const b=Date.now()-o;return Object.assign(t,{it:i}),{element:i,settled:p.completed,timeout:s,duration:b}}},As(t,"SettleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());const Va=$s((()=>{let e,t,n=[js({description:"Move classes, attributes, and properties from one element to another",syntax:["take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"]}),Ns({name:"take",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){if(3>e.args.length)throw Error('take requires property, "from", and source');const r=await t.evaluate(e.args[0],n)+"";if("from"!==await t.evaluate(e.args[1],n))throw Error("take syntax: take <property> from <source>");const i=await t.evaluate(e.args[2],n);let s;if(8>e.args.length)e.args.length>3&&(s=await t.evaluate(e.args[3],n));else{const r=await Promise.all([3,4,5,6].map(r=>t.evaluate(e.args[r],n)));"and"===r[0]&&"put"===r[1]&&"it"===r[2]&&"on"===r[3]&&e.args[7]&&(s=await t.evaluate(e.args[7],n))}return!s&&e.modifiers?.on&&(s=await t.evaluate(e.modifiers.on,n)),{property:r,source:i,target:s}}async execute(e,t){const n=Rs(e.source,t,"take"),r=Rs(e.target?e.target:void 0,t,"take"),i=this.takeProperty(n,e.property);return this.putProperty(r,e.property,i),{targetElement:r,property:e.property,value:i}}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 s=e.getAttribute(t);return null!==s?(e.removeAttribute(t),s):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 s=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());r.includes("-")||s in e.style||r in e.style?s in e.style?e.style[s]=n+"":r in e.style?e.style[r]=n+"":e.style.setProperty(r,n+""):e.setAttribute(t,n+"")}},As(t,"TakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Fa=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"js",category:"advanced"})],r=[];return t=class{async parseInput(e,t,n){let r,i;if(0===e.args.length)throw Error("js command requires JavaScript code");const s=e.args[0],o=e.args[1];if(s&&"literal"===s.type&&"string"==typeof s.value)r=s.value;else{if(!s||void 0===s.value)throw Error("js command requires JavaScript code");r=s.value+""}o&&"arrayLiteral"===o.type&&Array.isArray(o.elements)&&(i=o.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),s=await i(...Object.values(e));return void 0!==s&&Object.assign(t,{it:s}),{result:s,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},{})}}},As(t,"JsCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),_a=$s((()=>{let e,t,n=[js({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),Ns({name:"async",category:"advanced"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:n}=e,r=Date.now();try{const e=await this.executeCommandsAsync(t,n),i=Date.now()-r;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:n.length,results:e,executed:!0,duration:i}}catch(e){throw Error("Async command execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}async executeCommandsAsync(e,t){const n=[];for(let r=0;t.length>r;r++){const i=t[r];try{const t=await this.executeCommand(i,e);n.push(t),Object.assign(e,{it:t})}catch(e){const n=this.getCommandName(i);throw Error(`Command '${n}' (${r+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return n}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"execute"in e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},As(t,"AsyncCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ha=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"log",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},As(t,"LogCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ua=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"tell",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],n),commands:e.args.slice(1)}}async execute(e,t){const{target:n,commands:r}=e,i=Ls(n,t);if(0===i.length)throw Error("tell command found no target elements");const s=t.locals.get("_runtimeExecute"),o=[];for(const e of i){const n={...t,me:e,you:e};for(const e of r)try{const t=await this.executeCommand(e,n,s);o.push(t),Object.assign(n,{it:t})}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}}return{targetElements:i,commandResults:o,executionCount:i.length*r.length}}async executeCommand(e,t,n){if(e&&"object"==typeof e&&"command"===e.type&&n)return await n(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}},As(t,"TellCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());let za=(()=>{let e,t,n=[js({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"]}),Ns({name:"copy",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("copy command requires a source (text or element)");const r=await t.evaluate(e.args[0],n);let i="text";if(e.modifiers?.format){const r=await t.evaluate(e.modifiers.format,n);"html"!==r&&"text"!==r||(i=r)}return{source:r,format:i}}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(ge(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===n.me&&ge(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(ge(e.me)){const r=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!1});e.me.dispatchEvent(r)}}},As(t,"CopyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const Wa=$s(za);const Ja=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"pick",category:"utility"})],r=[];return t=class{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),s=await t.evaluate(e.modifiers.count,n);if(!Array.isArray(r))throw Error(`pick ${i}: source must be an array, got ${typeof r}`);if("number"!=typeof s||!Number.isFinite(s))throw Error(`pick ${i}: count must be a number, got ${typeof s}`);return{variant:i,array:r,count:s}}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,s="start"===i?.value?"start":await t.evaluate(e.modifiers.rangeStart,n),o="start"===s?"start":Number(s);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:o,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 s=await t.evaluate(e.modifiers.regex,n),o="string"==typeof s?s:s+"",a=e.modifiers.flags,c=a?.value;return{variant:i,source:r,regex:o,flags:c}}if(e.modifiers?.from){const r=await t.evaluate(e.modifiers.from,n);if(!Array.isArray(r))throw Error("pick from requires an array");if(0===r.length)throw Error("Cannot pick from empty array");return{variant:"random",array:r}}if(0===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 s=n.slice(r,i);return Object.assign(t,{it:s}),{selectedItem:s,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),s=Array.from(n.matchAll(i));return Object.assign(t,{it:s}),{selectedItem:s,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(),s=[];for(let t=0;e.count>t&&i.length>0;t++){const e=Math.floor(Math.random()*i.length);s.push(i.splice(e,1)[0])}return Object.assign(t,{it:s}),{selectedItem:s,sourceLength:r.length,sourceType:e.items?"items":"array",variant:"random"}}},As(t,"PickCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());const Za=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"beep",category:"utility"})],r=[];return t=class{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("🔔 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("🔔 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":ge(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(ge(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+""}},As(t,"BeepCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ka=$s((()=>{let e,t,n=[js({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"]}),Ns({name:"breakpoint",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}},As(t,"BreakpointCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());class Xa{constructor(){this.name="install"}get metadata(){return Xa.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,s,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}"`);if(e.args.length>=2){const r=await t.evaluate(e.args[1],n);if(r&&"object"==typeof r&&!Array.isArray(r)){s=r;for(const e of Object.keys(s))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(o=await t.evaluate(e.modifiers.on,n)),{behaviorName:i,parameters:s,target:o}}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 s=[];for(const i of e){const e=await this.installBehavior(n,i,r,t);s.push(e)}return{success:!0,behaviorName:n,installedCount:s.length,instances:s}}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(ge(e))return[e];throw Error('No target specified and "me" is not available in context')}if(ge(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>ge(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(ge(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=>ge(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=>ge(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(ge(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")}}Xa.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};class Ga{constructor(){this.name="render"}get metadata(){return Ga.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(e.args.length>=3&&"with"===await t.evaluate(e.args[1],n)){const r=await t.evaluate(e.args[2],n);r&&"object"==typeof r&&(i=r)}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),s=this.createTemplateContext(t,r),o=[],a=await this.processTemplate(i,s,o),c=this.createDOMElement(a);return Object.assign(t,{it:c}),{element:c,rendered:a,directivesProcessed:o}}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 s=0;for(;r.length>s;){const e=r[s].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:o}=await this.processRepeatDirective(r,s,t);i.push(o),s=e,n.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:o}=await this.processIfDirective(r,s,t,n);i.push(o),s=e,n.push("@if")}else if("@else"===e||"@end"===e)s++;else{const n=this.processVariableInterpolation(e,t);i.push(n),s++}}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 s=this.evaluateExpression(i[1],n),{endIndex:o,blockContent:a}=this.extractDirectiveBlock(e,t+1),c=[];if(Array.isArray(s))for(const e of s){const t={...n,locals:new Map([...n.locals.entries(),["it",e]])},r=await this.processTemplate(a.join("\n"),t,[]);c.push(r)}return{nextIndex:o+1,rendered:c.join("\n")}}async processIfDirective(e,t,n,r){const i=e[t].trim(),s=i.match(/^@if\s+(.+)$/);if(!s)throw Error("Invalid @if syntax: "+i);const o=!!this.evaluateExpression(s[1],n),{endIndex:a,blockContent:c,elseContent:l}=this.extractIfElseBlock(e,t+1);let u="";return o?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,s=t,o=!1;for(;e.length>s&&i>0;){const t=e[s].trim();if(t.startsWith("@if "))i++;else{if("@else"===t&&1===i){o=!0,s++;continue}if("@end"===t&&(i--,0===i))break}o?r.push(e[s]):n.push(e[s]),s++}return{endIndex:s,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 Xt(`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:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Ya(){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>')}Ga.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};const Qa=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],ec=function(e,t){const n=new Gr(null);for(const t of e)n.register(t);return new oi({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([Fs(),Hs(),ao(),uo(),Ro(),Lo(),qo(),Bo(),Fo(),Ho(),zo(),Jo(),Go(),ta(),na(),ra(),oa(),aa(),ca(),ua(),ha(),ma(),pa(),va(),Ea(),Sa(),Ta(),Ca(),Oa(),ja(),ba(),$a(),Ia(),new Ra,La(),Ma(),Da(),Pa(),qa(),Ba(),Va(),Fa(),_a(),Ha(),Ua(),Wa(),Ja(),Za(),Ka(),new Xa,new Ga],{expressionRegistry:Es()}),tc={async execute(e,t,n){const r=Ya(),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 s=r.buildAST(i.node),o=ye(n);return ec.execute(s.ast,o)},parse(e,t){const n=Ya(),r=n.parseSemantic(e,t);return.5>r.confidence||!r.node?null:n.buildAST(r.node).ast},translate:(e,t,n)=>Ya().translate(e,t,n),getAllTranslations:(e,t)=>Ya().getAllTranslations(e,t),createContext:pe,runtime:ec,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","transition","measure","settle","take","js","async","log","tell","copy","pick","beep","install","render"],supportedLanguages:Qa,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await sc():e instanceof HTMLElement&&await ic(e)},process:async e=>tc.processNode(e)},nc=new WeakSet;let rc=null;async function ic(e){if(nc.has(e))return;const t=e.getAttribute("_");if(t)try{const n=function(e){const t=e.getAttribute("data-lang");if(t&&Qa.includes(t))return t;let n=e;for(;n;){const e=n.getAttribute("lang");if(e){const t=e.split("-")[0].toLowerCase();if(Qa.includes(t))return t}n=n.parentElement}return"en"}(e);Yt(`ATTR-ML: Processing element with lang="${n}":`,t.substring(0,60));const r=Ya(),i=r.parseSemantic(t,n);if(.5>i.confidence||!i.node)return void Yt(`ATTR-ML: Low confidence (${i.confidence.toFixed(2)}) for: ${t}`);const s=r.buildAST(i.node),o=ye(e);await ec.execute(s.ast,o),nc.add(e),Yt("ATTR-ML: Successfully processed element")}catch(e){Yt("ATTR-ML: Error processing element:",e.message)}}async function sc(){const e=document.querySelectorAll("[_]");Yt(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(ic(e))}),await Promise.all(t),Yt("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:e.length}}))}function oc(){"undefined"!=typeof MutationObserver&&(rc=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&ic(t).catch(e=>{Yt("ATTR-ML: Error processing dynamic element:",e)});const n=t.querySelectorAll?.("[_]");n?.forEach(e=>{e instanceof HTMLElement&&ic(e).catch(e=>{Yt("ATTR-ML: Error processing dynamic descendant:",e)})})})}),rc.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=tc,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",()=>{sc().then(()=>oc())}):sc().then(()=>oc())),e.default=tc,e.hyperfixi=tc,Object.defineProperty(e,"l",{value:!0}),e}({});
|
|
1
|
+
var _hyperfixiMultilingualInternal=function(e){"use strict";class t{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 n(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function r(e){return{ok:!0,value:e}}function i(e){return{ok:!1,error:e}}function s(e){return!0===e.ok}const o="then",a="else",c="end",l="and",u="for",f="while",d="until",h="forever",m="times",p="index",y="in",g="to",v="from",b="with",w="of",E="on",x="event",k="behavior",S="global",A="the",T="start",C=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),O=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),N=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),j="at end of",$=["into","before","after","at",N,j,"at the start of","at the end of"],I=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"]),R=e=>C.has(e.toLowerCase()),L=e=>O.has(e.toLowerCase()),M=e=>I.has(e.toLowerCase()),D=e=>P.has(e.toLowerCase()),P=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"]),q=new Set(["me","it","you","result","my","its","your"]),B=new Set(["and","or","not","no"]),V=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"]),F=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),_=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]),H=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),U=new Set([")","]","}",","]);function z(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 W(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 J(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 s=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),s=!1),{type:"typeCheckExpression",value:t,typeName:i.value,nullOk:s,negated:e,start:t.start,end:i.end}}}const K=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",z(10)],["||",z(10)],["and",z(20)],["&&",z(20)],["==",z(30)],["!=",z(30)],["<",z(30)],[">",z(30)],["<=",z(30)],[">=",z(30)],["is",z(30)],["matches",z(30)],["contains",z(30)],["starts with",z(30)],["ends with",z(30)],["does not start with",z(30)],["does not end with",z(30)],["is between",z(30,(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!1,start:e.start,end:s.end}})],["is not between",z(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!0,start:e.start,end:s.end}})],["am between",z(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!1,start:e.start,end:s.end}})],["am not between",z(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 s=n.parseExpr(31);return{type:"betweenExpression",value:e,min:r,max:s,negated:!0,start:e.start,end:s.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,n)=>(e.ignoringCase=!0,e)}}],["where",z(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",z(28,(e,t,n)=>{const r=n.parseExpr(29);let i="asc";const s=n.peek();if(s&&"string"==typeof s.value){const e=s.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",z(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",z(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",z(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}})],["+",{...z(40),...J(80)}],["-",{...z(40),...J(80)}],["*",z(50)],["/",z(50)],["%",z(50)],["mod",z(50)],["^",W(60)],["**",W(60)],["as",z(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();e&&void 0!==e.value&&(t.name=`${t.name}:${e.value}`,t.end=e.end)}return t};let i=r(),s={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();s={type:"asExpression",expression:s,targetType:e,start:s.start,end:e.end??s.end,line:s.line,column:s.column}}return s})],["not",J(80)],["!",J(80)],["no",J(27)]]),new Map([["===",z(30)],["!==",z(30)],["is not",z(30)],["am",z(30)],["is in",z(30)],["is not in",z(30)],["precedes",z(30)],["does not precede",z(30)],["follows",z(30)],["does not follow",z(30)],["is a",z(30,Z(!1))],["is an",z(30,Z(!1))],["is not a",z(30,Z(!0))],["is not an",z(30,Z(!0))],["has",z(30)],["have",z(30)],["match",z(30)],["include",z(30)],["includes",z(30)],["equals",z(30)],["does not contain",z(30)],["does not include",z(30)],["am in",z(30)],["am not in",z(30)],["is really",z(30)],["is not really",z(30)],["is equal",z(30)],["is not equal",z(30)],["contain",z(30)],["do not contain",z(30)],["does not contains",z(30)],["do not match",z(30)],["does not match",z(30)],["is equal to",z(30)],["is not equal to",z(30)],["is really equal to",z(30)],["is not really equal to",z(30)],["really equals",z(30)],["is greater than",z(30)],["is less than",z(30)],["is greater than or equal to",z(30)],["is less than or equal to",z(30)],["in",z(30)],["of",W(30)],["really",z(30)],["exists",{prefix:{bp:80,handler:(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",J(80)]]),new Map([["=",W(5)]])),X=new Map,G=new Map,Y=new Map,Q=new Set,ee=new Set,te=new Set,ne=new Set;function re(e){return X.get(e.toLowerCase())}function ie(e){return Y.get(e)}function se(e,t){if(0!==ee.size)for(const n of ee)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",e)}}function oe(e,t,n){if(0!==te.size)for(const r of te)try{r(e,t,n)}catch(e){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",e)}}function ae(e,t){if(0!==ne.size)for(const n of ne)try{n(e,t)}catch(e){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",e)}}function ce(e,t,n){if(e.globals.set(t,n),0!==Q.size)for(const r of Q)try{r(t,n,e)}catch(e){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",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 ae(t,e),fe(n).get(t)}function me(e,t,n){const r=de(e);r&&(fe(r).set(t,n),oe(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,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function ye(e){if(!e)return pe();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)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 ge(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}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 be(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 we(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)?(ae(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)?(ae(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 Ee(e,t,n,r){if("element"!==r){if("global"===r)return ce(n,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$"))return void ce(n,e.slice(1),t);if(n.locals&&n.locals.has(e))return n.locals.set(e,t),void oe(e,t,n);if(n.globals&&n.globals.has(e))return ce(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 ce(n,e,t);n.locals.set(e,t),oe(e,t,n)}}else me(n,e,t)}function xe(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:we(e,t)}const ke=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),s=r.coerceFrom?.[i];if(s){const r=s(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 Se(e){const t=ke.get("String");return t?t.isType(e):"string"==typeof e}function Ae(e){const t=ke.get("Number");return t?t.isType(e):"number"==typeof e}function Te(e){const t=ke.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function Ce(e){const t=ke.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Oe(e){const t=ke.get("Function");return t?t.isType(e):"function"==typeof e}function Ne(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function je(e){return e instanceof Element}function $e(e){return e instanceof HTMLElement}const Ie=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Re(e,t){return Ie.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const Le={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=>Ne(e)?e.tabIndex:void 0,hidden:e=>Ne(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 Me(e,t){if(t.startsWith("*"))return function(e,t){if(!$e(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 $e(e)?getComputedStyle(e).getPropertyValue(n):void 0}if(t.startsWith("@"))return Re(e,t.slice(1));const n=Le[t.toLowerCase()];if(n)return n(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return Re(e,t);const r=e[t];return Oe(r)?r.bind(e):r}const De={1:"one",2:"two",3:"three",4:"four",5:"five"};function Pe(e,t,n,r){if(e.length!==t){return`${n} requires exactly ${i=t,De[i]??i+""} argument${1===t?"":"s"}${r?` (${r})`:""}`}var i;return null}function qe(e,t,n,r){return"string"!=typeof e[t]?`${n} ${r||"argument "+(t+1)} must be a string`:null}function Be(e,t,n){return Pe(e,1,t,n)??qe(e,0,t,n)}function Ve(e,t){return Pe(e,2,t,"left, right")}function Fe(){return null}function _e(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 He(e,t,n,r,i){return t>e.length||e.length>n?`${r} requires ${t}-${n} arguments${i?` (${i})`:""}`:null}function Ue(e,t,n,r=[]){return{type:e,message:t,suggestions:r,...n&&{path:n}}}const ze="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 We;function Je(){return We({validate:e=>({success:!0,data:e})})}function Ze(e,t){if(ze)return Je();const n=We({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:Ue("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:Ue("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:Ue("missing-argument",`Required field "${t}" is missing`,t)};const s=n.validate(e);if(!s.success)return{success:!1,error:Ue("validation-error",s.error.message||`Field "${t}" validation failed`,s.error.path?`${t}.${s.error.path}`:t)};void 0!==s.data&&(i[t]=s.data)}return{success:!0,data:i}}});return n.strict=()=>Ze(e,{strict:!0}),n}We=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 We(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:Ue("runtime-error",`String must be at least ${e} characters long`)}:r}};return We(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:Ue("runtime-error",`String must be at most ${e} characters long`)}:r}};return We(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 We(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:Ue("runtime-error",t||"Refinement validation failed")}:i}};return We(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 Ke=e=>function(e={}){return ze?Je():We({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:Ue("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:Ue("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:Ue("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:Ue("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:Ue("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),Xe=e=>function(e={}){return ze?Je():We({validate:t=>{const n=Number(t);return isNaN(n)?{success:!1,error:Ue("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>n?{success:!1,error:Ue("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&n>e.max?{success:!1,error:Ue("runtime-error","Number must be at most "+e.max)}:{success:!0,data:n}}})}(e||{}),Ge=()=>ze?Je():We({validate:e=>"boolean"!=typeof e?{success:!1,error:Ue("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),Ye=e=>Ze(e),Qe=e=>function(e){return ze?Je():We({validate:t=>{if(!Array.isArray(t))return{success:!1,error:Ue("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:Ue("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:Ue("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(e),et=()=>Je(),tt=()=>Je(),nt=()=>function(e,t="Custom validation failed"){return ze?Je():We({validate:n=>e(n)?{success:!0,data:n}:{success:!1,error:Ue("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class rt{trackPerformance(e,t,n,r){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(e,t,n,r=(n?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:t,duration:Date.now()-t,success:n})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||Ae(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":Ce(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":Se(e)?"String":Ae(e)?"Number":Te(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):Se(e)?e.split(""):null==e?[]:Ce(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(Ae(e)&&Number.isFinite(e))return e;if(Se(e)){const t=Number(e);return Number.isFinite(t)?t:null}return Te(e)?e?1:0:null}}function it(e,t,n,r,i="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:i,message:n,code:t,suggestions:r}}}function st(e,t){return{success:!0,value:e,type:t}}function ot(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const at={Array:(e,t)=>{try{return Array.isArray(e)?st(e,"array"):e instanceof NodeList?st(Array.from(e),"array"):st(null==e?[]:[e],"array")}catch(e){return it("Array","ARRAY_CONVERSION_FAILED",ot("Failed to convert value to Array",e),["Check if value is iterable","Ensure value is not circular reference"])}},String:(e,t)=>{try{return null==e?st("","string"):Se(e)?st(e,"string"):Ce(e)?st(JSON.stringify(e),"string"):st(e+"","string")}catch(e){return it("String","STRING_CONVERSION_FAILED",ot("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(Te(e))return st(e,"boolean");if(null==e)return st(!1,"boolean");if(Se(e)){const t=e.toLowerCase().trim();return st("false"!==t&&"0"!==t&&""!==t,"boolean")}return Ae(e)?st(0!==e&&!isNaN(e),"boolean"):st(!!e,"boolean")}catch(e){return it("Boolean","BOOLEAN_CONVERSION_FAILED",ot("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(Ae(e))return st(e,"number");if(null==e)return st(0,"number");const t=Number(e);return isNaN(t)?it("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):st(t,"number")}catch(e){return it("Number","NUMBER_CONVERSION_FAILED",ot("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const n=at.Number(e,t);return n.success?st(Math.trunc(n.value),"number"):n},Float:(e,t)=>{const n=at.Number(e,t);return n.success?st(parseFloat(""+n.value),"number"):n},Date:(e,t)=>{try{if(e instanceof Date)return st(e,"object");if(null==e)return st(new Date(""),"object");if(Se(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,n,r]=e.split("-").map(Number);return st(new Date(t,n-1,r),"object")}const t=new Date(e);return isNaN(t.getTime())?it("Date","INVALID_DATE",`Cannot convert "${e}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):st(t,"object")}catch(e){return it("Date","DATE_CONVERSION_FAILED",ot("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{if(!Se(e))return st(e,"object");try{return st(JSON.parse(e),"object")}catch(e){return it("JSON","JSON_PARSE_FAILED",ot("Failed to parse value as JSON",e),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(e,t)=>{try{return st(JSON.stringify(e),"string")}catch(e){return it("JSONString","JSON_STRINGIFY_FAILED",ot("Failed to stringify value as JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(Ce(e))return st(e,"object");if(Se(e))try{return st(JSON.parse(e),"object")}catch(e){return it("Object","JSON_PARSE_FAILED",ot("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return st({},"object")}catch(e){return it("Object","OBJECT_CONVERSION_FAILED",ot("Failed to convert value to Object",e),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(e,t)=>{try{if(e instanceof HTMLFormElement)return st(dt(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{const t=e;if(t.name){const e=ht(t);void 0!==e&&(n[t.name]=e)}}),st(n,"object")}return st({},"object")}catch(e){return it("FormValues","FORM_VALUES_EXTRACTION_FAILED",ot("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(e,t)=>{try{let n=e;if(e instanceof HTMLElement){const r=at.Values(e,t);if(!r.success)return r;n=r.value}if(!Ce(n))return st("","string");const r=new URLSearchParams;for(const[e,t]of Object.entries(n))if(null!=t)if(Array.isArray(t))for(const n of t)r.append(e,n+"");else r.append(e,t+"");return st(""+r,"string")}catch(e){return it("FormEncoded","FORM_ENCODE_FAILED",ot("Failed to URL-encode values",e),["Ensure input is a form element or plain object of scalar/array values"])}},Set:(e,t)=>{try{return st(new Set(e),"object")}catch(e){return it("Set","SET_CONVERSION_FAILED",ot("Failed to convert to Set",e),["Ensure the value is iterable"])}},Map:(e,t)=>{try{return st(new Map(Object.entries(e??{})),"object")}catch(e){return it("Map","MAP_CONVERSION_FAILED",ot("Failed to convert to Map",e),["Ensure the value is a plain object"])}},Keys:(e,t)=>e instanceof Map?st(Array.from(e.keys()),"array"):st(Object.keys(e??{}),"array"),Entries:(e,t)=>e instanceof Map?st(Array.from(e.entries()),"array"):st(Object.entries(e??{}),"array"),Reversed:(e,t)=>{try{return st(Array.from(e).reverse(),"array")}catch(e){return it("Reversed","REVERSED_CONVERSION_FAILED",ot("Failed to reverse value",e),["Ensure the value is array-like"])}},Unique:(e,t)=>{try{return st([...new Set(e)],"array")}catch(e){return it("Unique","UNIQUE_CONVERSION_FAILED",ot("Failed to dedupe value",e),["Ensure the value is iterable"])}},Flat:(e,t)=>{try{return st(Array.from(e).flat(),"array")}catch(e){return it("Flat","FLAT_CONVERSION_FAILED",ot("Failed to flatten value",e),["Ensure the value is array-like"])}}},ct=Ye({value:tt(),type:Ke().min(1)}),lt=Ye({value:tt(),type:Ke().min(1)});new class extends rt{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=ct,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:i,type:s}=t;if(s.startsWith("Fixed")){const r=s.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):0,a=at.Number(i,e);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(e,t,c,n),c}let o=at[s];if(o){const r=o(i,e);return this.trackPerformance(e,t,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[s.toLowerCase()];if(a&&(o=at[a],o)){const r=o(i,e);return this.trackPerformance(e,t,r,n),r}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+s,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(e,t,c,n),c}catch(r){const i={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends rt{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=lt,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:i,type:s}=t,o=s.toLowerCase();let a;switch(o){case"null":a=null===i;break;case"undefined":a=void 0===i;break;case"string":a=Se(i);break;case"number":a=Ae(i)&&!isNaN(i);break;case"boolean":a=Te(i);break;case"object":a=Ce(i);break;case"array":a=Array.isArray(i);break;case"function":a=Oe(i);break;case"date":a=i instanceof Date;break;case"element":a=i instanceof Element;break;case"node":a=i instanceof Node;break;case"node-list":a=i instanceof NodeList;break;case"empty":a=null==i||""===i||Array.isArray(i)&&0===i.length||Ce(i)&&0===Object.keys(i).length;break;default:a=i?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(e,t,c,n),c}catch(r){const i=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const ut={conversions:{dynamicResolvers:[]}},ft={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":Se(e)?e:Ce(e)?JSON.stringify(e):e+"",Boolean:e=>{if(Te(e))return e;if(null==e)return!1;if(Se(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return Ae(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(Ae(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(Ae(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(!Ae(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=ft.Number(e);return Math.trunc(t)},Float:e=>{const t=ft.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(Se(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(!Se(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(Ce(e))return e;if(Se(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=>Se(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:ft.String(e)).join(""):e instanceof Element?e.outerHTML:ft.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return dt(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),n={};return t.forEach(e=>{e.name&&(n[e.name]=ht(e))}),n}return{}},FormEncoded:(e,t)=>{const n=e instanceof HTMLElement?ft.Values(e,t):e;if(!Ce(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=ft.Values(e,t);return ft.FormEncoded(n,t)},"Values:JSON":(e,t)=>{const n=ft.Values(e,t);return JSON.stringify(n)}};function dt(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const n=e;if(n.name){const e=ht(n);void 0!==e&&(void 0!==t[n.name]?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(e)):t[n.name]=e)}}),t}function ht(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 mt={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 pt(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 ft.Number(e).toFixed(n??0)}if(null==e)return e;let r=ft[t];if(r)return r(e,n);const i=mt[t.toLowerCase()];if(i&&(r=ft[i],r))return r(e,n);const s=ut.conversions[t];if("function"==typeof s)return s(e,n);for(const n of ut.conversions.dynamicResolvers){const r=n(t,e);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+t),e}const yt={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[n,r]=t;return pt(n,r,e)},validate:e=>Pe(e,2,"as","value, type")??qe(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(!Se(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 Se(n);case"number":return Ae(n)&&!isNaN(n);case"boolean":return Te(n);case"object":return Ce(n);case"array":return Array.isArray(n);case"function":return Oe(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||Ce(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:e=>Pe(e,2,"is","value, type")??qe(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Pe(e,1,"async","expression")}},gt=new Set(["__proto__","constructor","prototype"]);function vt(e,t){if(e instanceof Element)return Me(e,t);if(Ce(e)){if(gt.has(t))return;return e[t]}return e[t]}function bt(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 wt={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 bt(n)&&!(r in n)?Array.from(n,e=>vt(e,r)):vt(n,r)}},validate:e=>Pe(e,2,"possessive","element, property")??qe(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 Me(e.me,n);if(Ce(e.me)){if(gt.has(n))return;return e.me[n]}return e.me[n]}},validate:e=>Be(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 Me(r,n);if(Ce(r)){if(gt.has(n))return;return r[n]}return r[n]},validate:e=>Be(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 Me(e.you,n);if(Ce(e.you)){if(gt.has(n))return;return e.you[n]}return e.you[n]}},validate:e=>Be(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 Me(r,n);if(Ce(r)){if(gt.has(n))return;return r[n]}return r[n]}},validate:e=>Pe(e,2,"of","property, object")??qe(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=>He(e,1,2,"attribute","attributeName, optional element")??qe(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 s=i||e.me;return!!(s&&s instanceof Element)&&s.getAttribute(n)===r},validate:e=>He(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??qe(e,0,"attributeWithValue","attribute name")??qe(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=>Be(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=>Be(e,"idReference","idValue")}};function Et(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]}var xt;!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"}(xt||(xt={}));const kt=new Set(["+","-","*","/","mod"]),St=new Set(["ms","s","seconds","minutes","hours","days"]);function At(e,t=1){const n=e.position+t;return e.input.length>n?e.input[n]:""}function Tt(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 Ct(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;Tt(e)}}function Ot(e,t,n,r,i){const s=r??e.position-n.length,o=e.position;let a=e.column-n.length;if(void 0!==r){a=1;let t=-1;for(let n=0;r>n;n++)"\n"!==e.input[n]&&"\r"!==e.input[n]||(t=n);a=r-t}const c={kind:t,value:n,start:s,end:o,line:Nt(e,s),column:a};e.tokens.push(c)}function Nt(e,t){let n=1;for(let r=0;t>r&&e.input.length>r;r++){const t=e.input[r];"\n"===t?n++:"\r"===t&&(n++,e.input.length>r+1&&"\n"===e.input[r+1]&&r++)}return n}function jt(e){const t=e.position;let n="";for(Tt(e),Tt(e);e.input.length>e.position&&"\n"!==e.input[e.position];)n+=Tt(e);Ot(e,xt.COMMENT,"--"+n,t)}function $t(e){const t=e.position,n=Tt(e);let r=n;for(;e.input.length>e.position;){const t=Tt(e);if(r+=t,t===n)break;"\\"===t&&e.input.length>e.position&&(r+=Tt(e))}Ot(e,xt.STRING,r,t)}function It(e){const t=e.position;Tt(e);let n="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){Tt(e);break}if("\\"===t){if(Tt(e),e.input.length>e.position){const t=Tt(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+=Tt(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-n.length}`);Ot(e,xt.TEMPLATE,n,t)}function Rt(e){const t=e.position;let n=Tt(e);if(e.input.length>e.position&&"{"===e.input[e.position]){for(n+=Tt(e);e.input.length>e.position;){const t=e.input[e.position];if(n+=Tt(e),"}"===t)break}Ot(e,xt.SELECTOR,n,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)Tt(e),e.input.length>e.position&&(n+=Tt(e));else{if(!Ft(t)&&"-"!==t&&"_"!==t&&":"!==t)break;n+=Tt(e)}}Ot(e,xt.SELECTOR,n,t)}}function Lt(e){const t=e.position;if(_t(e))return void function(e,t){const n=e.input;let r="",i=0,s="";for(;n.length>e.position;){const t=n[e.position];if(s)r+=Tt(e),t===s&&(s="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===n[e.position+1]){for(;n.length>e.position&&">"!==n[e.position];)r+=Tt(e);if(n.length>e.position&&(r+=Tt(e)),i--,0>=i)break;continue}let t=!1,s="";for(;n.length>e.position;){const i=n[e.position];if(s)r+=Tt(e),i===s&&(s="");else if('"'!==i&&"'"!==i){if(">"===i){t="/"===n[e.position-1],r+=Tt(e);break}r+=Tt(e)}else s=i,r+=Tt(e)}if(t||i++,0>=i)break;continue}r+=Tt(e)}else s=t,r+=Tt(e)}Ot(e,xt.SELECTOR,r,t)}(e,t);let n="";for(n+=Tt(e);e.input.length-1>e.position;){const t=e.input[e.position],r=e.input[e.position+1];if(n+=Tt(e),"/"===t&&">"===r){n+=Tt(e);break}}Ot(e,xt.SELECTOR,n,t)}function Mt(e){const t=e.position;let n=Tt(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!Ft(t)&&"_"!==t&&"-"!==t)break;n+=Tt(e)}Ot(e,xt.SYMBOL,n,t)}function Dt(e){const t=e.position;let n="";const r=e.input[e.position];if(("'"===r||"'"===r)&&"s"===At(e,1))return n="'s",Tt(e),Tt(e),void Ot(e,xt.OPERATOR,n,t);const i=e.input.substring(e.position,e.position+2),s=e.input.substring(e.position,e.position+3);["===","!=="].includes(s)?(n=s,Tt(e),Tt(e),Tt(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,Tt(e),Tt(e)):n=Tt(e),Ot(e,xt.OPERATOR,n,t)}function Pt(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+=Tt(e)}if(r>e.position&&"."===n[e.position]&&(e.position+1>=r||"."!==n[e.position+1]))for(i+=Tt(e);r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=Tt(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]:"",s=r>e.position+2?n[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">s||s>"9"))for(i+=Tt(e),"+"!==n[e.position]&&"-"!==n[e.position]||(i+=Tt(e));r>e.position;){const t=n[e.position];if("0">t||t>"9")break;i+=Tt(e)}}}const s=e.position;let o="";for(;r>e.position;){const t=n[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;o+=Tt(e)}St.has(o)?Ot(e,xt.TIME,i+o,t):(e.position=s,Ot(e,xt.NUMBER,i,t))}function qt(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+=Tt(e)}const s=function(e,t,n){const r=t.toLowerCase(),i=e.position;if("'s"===t||"'s"===t)return!1;const s=e.tokens[e.tokens.length-1];if(s&&(s.kind===xt.IDENTIFIER||s.kind===xt.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}Ct(e);let o="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;o+=Tt(e)}if(o){const t=o.toLowerCase(),i=`${r} ${t}`,s=function(e,t,n,r){const i=t.toLowerCase(),s=n.toLowerCase();if("at"===i){const t=e.position;if("the"===s){Ct(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+=Tt(e)}const i=n.toLowerCase();if("start"===i||"end"===i){Ct(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+=Tt(e)}if("of"===t.toLowerCase())return Ot(e,xt.IDENTIFIER,`at the ${i} of`,r),!0}return e.position=t,!1}if("start"===s||"end"===s){Ct(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+=Tt(e)}return"of"===n.toLowerCase()?(Ot(e,xt.IDENTIFIER,`at ${s} of`,r),!0):(e.position=t,!1)}}return!1}(e,r,t,n);if(s)return!0;const a=function(e,t,n){const r=e.position;let i=`${t} ${n}`,s=e.position;const o=[t,n];for(;8>o.length&&(Ct(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+=Tt(e)}if(!t)break;o.push(t.toLowerCase());const n=o.join(" ");V.has(n)&&(i=n,s=e.position)}return V.has(i)&&i!==`${t} ${n}`?(e.position=s,i):(e.position=r,null)}(e,r,t);if(a)return Ot(e,xt.OPERATOR,a,n),!0;if(V.has(i))return Ot(e,xt.OPERATOR,i,n),!0}return V.has(r)?(e.position=i,Ot(e,xt.OPERATOR,t,n),!0):(e.position=i,!1)}(e,i,t);if(s)return;const o=function(e){const t=e.toLowerCase();return"include"===t||"includes"===t||B.has(t)||kt.has(e)||kt.has(t)||V.has(t)?xt.OPERATOR:xt.IDENTIFIER}(i);Ot(e,o,i,t)}function Bt(e){const t=e.position,n=e.input,r=n.length;Tt(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+=Tt(e)}Ot(e,xt.IDENTIFIER,i,t)}function Vt(e){return/[a-zA-Z]/.test(e)}function Ft(e){return/[a-zA-Z0-9]/.test(e)}function _t(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 Ht(e){if(_t(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(Ft(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 Ut(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const zt=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}(),Wt=zt,Jt=zt,Zt=zt,Kt=zt,Xt=(...e)=>{Wt&&console.log("\ud83d\udd27",...e)},Gt=(...e)=>{Jt&&console.log("\ud83c\udfaf",...e)},Yt=(...e)=>{Zt&&console.log("\ud83d\udcdd",...e)},Qt=(...e)=>{Kt&&console.log("\ud83d\ude80",...e)};let en=!1,tn=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(en=!0,tn=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let nn={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class rn{constructor(e){this.analyzer=e.analyzer,this.language=e.language,this.confidenceThreshold=e.confidenceThreshold??.5,this.debugEnabled=e.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(e){const t=e.trim().split(/\s+/)[0]?.toLowerCase();if(rn.SKIP_SEMANTIC_COMMANDS.has(t))return!0;const n=e.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[a-zA-Z]/.test(e)}trySemanticParse(e){const t=performance.now();if(this.shouldSkipSemantic(e))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const r=this.analyzer.analyze(e,this.language),i=performance.now()-t;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:e,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const s=r.confidence>=this.confidenceThreshold&&!!r.command,o=!s&&r.confidence>0;if(en){const t={};if(r.command?.roles)for(const[e,n]of r.command.roles)t[e]=n.value;const a={input:e.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:s,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(t).length>0?t:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(e){if(!en)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",n=Math.round(100*e.confidence),r=Math.round(100*e.threshold),i=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),e.command&&console.log("Command: "+e.command),e.roles&&Object.keys(e.roles).length>0&&console.log("Roles:",e.roles),e.duration&&console.log(`Duration: ${e.duration.toFixed(2)}ms`),e.errors?.length&&console.log("Errors:",e.errors),console.groupEnd(),tn){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});tn.dispatchEvent(t)}}(a),n=a,nn.totalParses++,n.semanticSuccess?nn.semanticSuccesses++:n.fallbackTriggered?nn.semanticFallbacks++:nn.traditionalParses++,nn.confidenceHistory.push(n.confidence),nn.confidenceHistory.length>100&&nn.confidenceHistory.shift(),nn.averageConfidence=nn.confidenceHistory.reduce((e,t)=>e+t,0)/nn.confidenceHistory.length}return s?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(e){return{success:!1,confidence:0,errors:[e instanceof Error?e.message:e+""]}}var n}buildCommandNode(e){const{command:t}=e;if(!t)throw Error("Cannot build command node without command data");if("repeat"===t.name)return this.buildRepeatCommandNode(t);if("for"===t.name)return this.buildRepeatCommandNode(t);if("set"===t.name)return this.buildSetCommandNode(t);if("if"===t.name||"unless"===t.name)return this.buildIfCommandNode(t);const n=[],r={};for(const[e,i]of t.roles){const s=this.semanticValueToExpression(i);switch(e){case"patient":case"event":n.push(s);break;case"destination":"put"===t.name?r.into=s:"add"===t.name||"append"===t.name||"prepend"===t.name?r.to=s:r.on=s;break;case"source":"fetch"===t.name?n.push(s):r.from=s;break;case"quantity":r.by=s;break;case"duration":r.over=s;break;case"responseType":r.as=s;break;case"style":r.with=s;break;case"condition":r.when=s;break;default:r[e]=s}}return{type:"command",name:t.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(e){const t=[],n={},r=e.roles.get("loopType");r&&t.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const i=e.roles.get("patient");"for"==(r?r.value+"":"")&&i&&t.push({type:"identifier",name:"expression"===i.type&&i.raw||i.value+"",start:0,end:0,line:1,column:0});const s=e.roles.get("event");s&&t.push({type:"string",value:s.value+"",start:0,end:0,line:1,column:0});const o=e.roles.get("source");o&&t.push(this.semanticValueToExpression(o));const a=e.roles.get("quantity");a&&t.push(this.semanticValueToExpression(a));const c=e.roles.get("condition");return c&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:t,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(e){const t=[],n=e.roles.get("destination");if(n)if("property-path"===n.type){const e=n;t.push({type:"possessiveExpression",object:this.semanticValueToExpression(e.object),property:this.createPropertyNode(e.property),start:0,end:0,line:1,column:0})}else t.push(this.semanticValueToExpression(n));t.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=e.roles.get("patient");return r&&t.push(this.semanticValueToExpression(r)),{type:"command",name:"set",args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(e){return e.startsWith("*")?{type:"cssProperty",name:e.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:e,start:0,end:0,line:1,column:0}}buildIfCommandNode(e){const t=[],n=e.roles.get("condition");return n&&t.push(this.semanticValueToExpression(n)),{type:"command",name:e.name,args:t,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(e){switch(e.type){case"selector":return{type:"selector",value:e.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:e.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof e.value&&e.value.includes("${")&&e.value.includes("}")?{type:"templateLiteral",value:e.value,start:0,end:0,line:1,column:0}:{type:"literal",value:e.value,raw:e.raw??e.value,start:0,end:0,line:1,column:0};case"property-path":{const t=e;return{type:"memberExpression",object:this.semanticValueToExpression(t.object),property:{type:"identifier",name:t.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(e.raw||"")}}parseExpressionString(e){let t=0;const n=()=>{for(;e.length>t&&/\s/.test(e[t]);)t++},r=()=>{n();const r=t;for(;e.length>t&&/[a-zA-Z0-9_$]/.test(e[t]);)t++;return e.slice(r,t)},i=()=>{const r=[];if(t++,n(),")"!==e[t])for(r.push(s()),n();","===e[t];)t++,n(),r.push(s()),n();return")"===e[t]&&t++,r},s=()=>{n();const s=r();if(!s)return{type:"identifier",name:e.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:s,start:0,end:0,line:1,column:0};for(;e.length>t;){n();const s=e[t];if("."===s){t++;const e=r();e&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:e,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==s)break;o={type:"callExpression",callee:o,arguments:i(),start:0,end:0,line:1,column:0}}}return o};return s()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function sn(e){return e.kind===xt.IDENTIFIER&&C.has(e.value.toLowerCase())}function on(e){return e.kind===xt.IDENTIFIER&&_.has(e.value.toLowerCase())}function an(e){return e.kind===xt.IDENTIFIER&&F.has(e.value.toLowerCase())}function cn(e){return e.kind===xt.IDENTIFIER&&q.has(e.value.toLowerCase())}function ln(e){return V.has(e.value.toLowerCase())}function un(e){return e.kind===xt.IDENTIFIER}function fn(e){return e.kind===xt.SELECTOR}function dn(e){return e.kind===xt.SELECTOR&&!e.value.startsWith("<")}function hn(e){return e.kind===xt.STRING||e.kind===xt.NUMBER||e.kind===xt.TEMPLATE}function mn(e){return e.kind===xt.IDENTIFIER}function pn(e){return e.kind===xt.TIME}function yn(e){return e.kind===xt.SYMBOL}function gn(e){return e.kind===xt.COMMENT}function vn(e){if(e.kind!==xt.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(C.has(t)||_.has(t)||F.has(t)||q.has(t))}function bn(e){return e.kind===xt.STRING}function wn(e){return e.kind===xt.NUMBER}function En(e){if(e.kind===xt.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function xn(e){return e.kind===xt.TEMPLATE}function kn(e){return e.kind===xt.SELECTOR&&e.value.startsWith("<")}function Sn(e){return e.kind===xt.SELECTOR&&e.value.startsWith("#")}function An(e){return e.kind===xt.SELECTOR&&e.value.startsWith(".")}function Tn(e){return e.kind===xt.SELECTOR&&!e.value.startsWith("#")&&!e.value.startsWith(".")}function Cn(e){if(e.kind!==xt.OPERATOR)return!1;const t=e.value.toLowerCase();return!B.has(t)&&!V.has(t)}function On(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function Nn(e,t,n){return{type:"literal",value:e,raw:t,start:n.start,end:n.end,line:n.line,column:n.column}}function jn(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function $n(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 In(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Rn(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Ln(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Mn(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Dn(e,t,n){return{type:"propertyOfExpression",property:e,target:t,start:n.start,end:n.end,line:n.line,column:n.column}}function Pn(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}}rn.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const qn=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function Bn(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const Vn=[o,l,a,c];function Fn(e,t=[]){if(e.isAtEnd())return!0;for(const t of Vn)if(e.check(t))return!0;for(const n of t)if(e.check(n))return!0;return!!e.checkIsCommand()}function _n(e,t=[]){if(!Fn(e,t))return e.parseExpression()}function Hn(e,t,n){return!!e.check(t)&&(e.advance(),n.push(e.createIdentifier(t)),!0)}function Un(e,t,n){for(const r of t)if(e.check(r))return e.advance(),n.push(e.createIdentifier(r)),r;return null}function zn(e,t){return!!e.check(t)&&(e.advance(),!0)}function Wn(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 Jn{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new Jn(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 Jn(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 Jn(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 Jn(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 Zn(e,t){const n=[];let r="";const i=e.peek().start||0,s=e.peek().line||1,o=e.peek().column||1;if(e.checkIdentifierLike()){for(r=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),r+=":",e.checkIdentifierLike()&&(r+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:n,value:r}=Wn(e);if(t.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),n.push({type:"functionCall",name:r,args:t,start:i,end:e.getPosition().end,line:s,column:o})}else n.push({type:"string",value:r,start:i,end:e.getPosition().end,line:s,column:o})}const a=[...n];for(;!Fn(e);){if(e.check("on")||e.check("to")){const t=e.advance().value;a.push(e.createIdentifier(t));continue}a.push(e.parsePrimary())}return Jn.fromIdentifier(t).withArgs(...a).endingAt(e.getPosition()).build()}function Kn(e,t){const n=[];if(e.check(A)){const t=e.advance();if(n.push({type:"identifier",name:A,start:t.start,end:t.end,line:t.line,column:t.column}),e.check(x)){const t=e.advance();n.push({type:"identifier",name:x,start:t.start,end:t.end,line:t.line,column:t.column})}}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Xn(e,t){const n=[];let r=!1;const i=e.savePosition();for(let t=0;500>t&&!e.isAtEnd();t++){const t=e.peek();if(t.value===o){r=!0;break}if(t.value===c||t.value===k||"def"===t.value||t.value===E)break;e.advance()}e.restorePosition(i);let s=!1;if(!r){const n=e.savePosition(),r=t.line,i=100;for(;!e.isAtEnd()&&i>e.current-n;){const t=e.peek(),n=t.value?.toLowerCase();if(n===k||"def"===n||n===E)break;if(n===a||n===c){t.line===r&&(s=!0);break}if((e.checkIsCommand()||e.isCommand(n))&&void 0!==t.line&&t.line!==r){s=!0;break}e.advance()}e.restorePosition(n)}const l=r||s;let u;if(l)u=e.parseExpression();else{const n=[],r=20;let i=0;for(;!e.isAtEnd()&&!e.checkIsCommand()&&!e.isCommand(e.peek().value)&&!e.check(o)&&r>i;){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");u=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(u),l){r&&e.advance();const i=[];for(;!e.isAtEnd()&&!e.check(a)&&!e.check(c)&&(e.checkIsCommand()||e.isCommand(e.peek().value));){e.advance();const t=e.parseCommand();t&&i.push(t)}if(0===i.length&&e.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");n.push(In(i,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}));let s=!1;if(e.check(a))if(e.advance(),e.check("if")){const t=e.peek();e.advance();const r=Xn(e,t);n.push(In([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column})),s=!0}else{const r=[];for(;!e.isAtEnd()&&!e.check(c)&&(e.checkIsCommand()||e.isCommand(e.peek().value));){e.advance();const t=e.parseCommand();t&&r.push(t)}n.push(In(r,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}s||e.consume(c,"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(In([r],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}}return Jn.from(t).withArgs(...n).endingAt(e.getPosition()).build()}function Gn(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=Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}function Yn(e,t){const n=[],r=_n(e,[v]);r&&n.push(r),Hn(e,v,n);const i=_n(e);return i&&n.push(i),Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function Qn(e,t){const n=[];if(e.check("between")){e.advance(),n.push(e.createIdentifier("between"));const r=_n(e,[l]);if(r&&"binaryExpression"===r.type&&"and"===r.operator)r.left&&n.push(r.left),n.push(e.createIdentifier("and")),r.right&&n.push(r.right);else{r&&n.push(r),Hn(e,l,n);const t=_n(e,[v,E,u]);t&&n.push(t)}if(Un(e,[v,E],n)){const t=_n(e);t&&n.push(t)}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}const r=_n(e,[v,E]);if(r&&n.push(r),Un(e,[v,E],n)){const t=_n(e);t&&n.push(t)}return e.check("modal")&&(e.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function er(e,t){const n=e.parseExpression();if(!n)return e.addError("Put command requires content expression"),null;const r=e.peek();if(!r||!$.includes(r.value))return e.addError(`Expected operation keyword (${$.join(", ")}) after put expression, got: ${r?.value}`),null;let i=e.advance().value;const s=i.toLowerCase();"at start of"===s||"at the start of"===s?i=N:"at end of"===s||"at the end of"===s?i=j:"at"===i&&(e.check(T)||e.check(A)?(zn(e,A),e.check(T)&&(e.advance(),e.check(w)&&(e.advance(),i=N))):e.check(c)&&(e.advance(),e.check(w)&&(e.advance(),i=j)));const o=e.parseExpression();return o?Jn.fromIdentifier(t).withArgs(n,e.createIdentifier(i),o).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const tr=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function nr(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(S)&&!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===w){const e=n.left,t=n.right;return Dn(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(o)||e.check(l)||e.check(a)||e.check(c));)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")===w){const n=t[1],r=t[3];return{expression:Dn(jn(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 s=e.parseExpression()??e.parsePrimary();let u;var f;e.check(E)&&(f=e.peekAt(1))&&("selector"===f.kind||f.value.startsWith("<")||rr.has(f.value))&&(e.advance(),u=_n(e));const d=[];r?d.push(r):i.length>0&&d.push(...i),d.push(e.createIdentifier(g)),s&&d.push(s);const h=Jn.fromIdentifier(t).withArgs(...d);return u&&h.withModifier("on",u),h.endingAt(e.getPosition()).build()}const rr=new Set(["me","my","it","its","you","your","yourself"]),ir=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]),sr=new Set(["in","then","and","else","end","otherwise","when","where","catch","finally"]);function or(e){return e.isAtEnd()||sr.has(e.peek().value)}function ar(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function cr(e,t){const n=[];for(;!Fn(e,["catch","finally"])&&(e.checkIdentifierLike()||e.checkSelector()||e.checkLiteral()||e.checkTimeExpression()||e.match("<"));)n.push(e.parsePrimary());return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}function lr(e){if(e.isAtEnd())return!0;const t=e.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(t)||Fn(e)}function ur(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}function fr(e,t=lr){const n=e.savePosition();let r="";for(;!e.isAtEnd()&&!t(e);)r+=e.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:n,end:e.savePosition()}:(e.restorePosition(n),null)}function dr(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function hr(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 mr=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class pr{constructor(e,t,n){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,t?.semanticAnalyzer&&t?.language&&(this.semanticAdapter=new rn({analyzer:t.semanticAnalyzer,language:t.language,confidenceThreshold:t.semanticConfidenceThreshold??.5})),this.originalInput=n||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors]),e}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}const e=this.peek(),t=e&&re(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!==re(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?re(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")){Yt("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const t=[e];Yt(`\u2705 PARSER: Starting with ${t.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){Yt(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const e=this.parseEventHandler();if(Yt("\u2705 PARSER: parseEventHandler returned:",e?`type=${e.type}, event=${e.event}`:"null"),e&&(t.push(e),n++,Yt(`\u2705 PARSER: Added event handler, now have ${t.length} statements total`)),Yt(`\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 Yt("\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};Yt("\u2705 PARSER: No more event handlers, at end of input");break}}return Yt(`\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=pr.PRATT_TABLE.get(r.value);let s;if(i?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();s=i.prefix.handler(e,this.makePrattContext())}else s=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(s,t);if(e){s=e;continue}}const n=pr.PRATT_TABLE.get(t.value);if(!n?.infix){if(H.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){Yt("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}`),s}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}`),s}const i=this.advance();if(this.isAtEnd()&&!pr.POSTFIX_UNARY_OPERATORS.has(i.value))return this.addError(`Expected expression after '${i.value}' operator`),s;s=n.infix.handler(s,i,this.makePrattContext())}return this.prattCache.set(t,{node:s,endPos:this.current}),s}tryParseStringPostfix(e,t){const n=t.value;let r=null;if(mr.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const i=this.advance();return{type:"stringPostfix",expression:e,unit:r,start:e.start,end:i.end,line:e.line,column:e.column}}canStartOperand(e){if(!e)return!1;const t=e.value;return!H.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||H.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):R(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):M(e)}createCommandFromIdentifier(e){const t=[],n=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(n))return this.parseCompoundCommand(e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)t.push(this.parsePrimary());return{type:"command",name:e.name,args:t,isBlocking:!1,...void 0!==e.start&&{start:e.start},end:this.getPosition().end,...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}isCompoundCommand(e){return L(e)}parseCompoundCommand(e){return function(e,t){switch(t.name.toLowerCase()){case"put":return er(e,t);case"trigger":case"send":return Zn(e,t);case"remove":return Yn(e,t);case"toggle":return Qn(e,t);case"set":return nr(e,t);case"halt":return Kn(e,t);case"measure":return Gn(e,t);case"js":return function(e,t){const n=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&n.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const 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(c)&&e.peek().start<i;)e.advance();e.consume(c,"Expected end after js code body");const s={type:"literal",value:e.getInputSlice(r,i).trim(),start:t.start,end:e.getPosition().end},o={type:"arrayLiteral",elements:n.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return Jn.fromIdentifier(t).withArgs(s,o).endingAt(e.getPosition()).build()}(e,t);case"go":return function(e,t){const n=[];for(;!Fn(e,["when","where","catch","finally"]);){const t=e.peek(),r=e.resolveKeyword(t.value).toLowerCase();if(ir.has(r)){e.advance(),n.push(ar(r,t));continue}if(ur(e)){const r=fr(e,or);if(r){n.push(r);continue}e.advance(),n.push(ar(t.value,t));continue}if("+"===t.value||"-"===t.value){e.advance(),n.push(ar(t.value,t));continue}if("number"===t.kind){e.advance();const r=e.peek();if(e.isAtEnd()||"px"!==r.value||r.start!==t.end)n.push({type:"literal",value:Number(t.value),raw:t.value,start:t.start,end:t.end,line:t.line,column:t.column});else{const r=e.advance();n.push(ar(t.value+"px",{...t,end:r.end}))}continue}const i=e.current;if(n.push(e.parsePrimary()),e.current===i)break}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(e,t);case"tell":return function(e,t){const n=e.parseExpression();if(!n)throw Error("tell command requires a target expression");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(l))continue;if(e.check(o)||e.check(a)||e.check(c))break;if(e.checkIsCommand())continue;break}break}if(0===r.length)throw Error("tell command requires at least one command after the target");return Jn.fromIdentifier(t).withArgs(n,...r).endingAt(e.getPosition()).build()}(e,t);case"pick":return function(e,t){const n=Jn.fromIdentifier(t);zn(e,A);const r=e.peek().value,i=e=>({type:"literal",value:e,start:t.start,end:t.end}),s=()=>{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=s();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=s();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=s(),o=n.withArgs(r).withModifier("variant",i("random"));return t&&o.withModifier("count",t),o.endingAt(e.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let t,r;e.advance(),e.match("at","from"),t=e.match("start")?i("start"):e.parsePrimary();let o=!1;(e.match("to")||e.match(".."))&&(e.match("end")?o=!0:r=e.parsePrimary());let a="default";e.match("inclusive")?a="inclusive":e.match("exclusive")&&(a="exclusive");const c=s(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",t).withModifier("rangeMode",i(a));return o?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 o;e.matchOperator("|")&&(o=e.advance().value);const a=s(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",t);return o&&c.withModifier("flags",i(o)),c.endingAt(e.getPosition()).build()}return cr(e,t)}(e,t);case"start":return function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const n={};if(e.match("using")){const t=e.parsePrimary();n.transitionName=t}const r=e.parseCommandListUntilEnd();return Jn.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(e,t);case"swap":case"morph":return function(e,t){const n=[];let r=null;if(!e.isAtEnd()){const t=e.peek();if(t&&t.value){const i=t.value.toLowerCase();tr.includes(i)&&(r=i,e.advance(),n.push(e.createIdentifier(r)))}}if("delete"===r){const r=e.parseExpression();return r&&n.push(r),Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}!e.isAtEnd()&&e.check(w)&&(e.advance(),n.push(e.createIdentifier("of")));const i=e.parseExpression();if(i&&n.push(i),!e.isAtEnd()&&e.check(b)){e.advance(),n.push(e.createIdentifier("with"));const t=e.parseExpression();t&&n.push(t)}return Jn.fromIdentifier(t).withArgs(...n).endingAt(e.getPosition()).build()}(e,t);default:return cr(e,t)}}(this.getContext(),e)}parsePutCommand(e){return er(this.getContext(),e)}parseSetCommand(e){return nr(this.getContext(),e)}parseHaltCommand(e){return Kn(this.getContext(),e)}parseMeasureCommand(e){return Gn(this.getContext(),e)}parseTriggerCommand(e){return Zn(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],n=()=>this.check("end")||e.some(e=>this.check(e));for(Yt("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",e.join(","),")");!this.isAtEnd()&&!n();){Yt("\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){Yt(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&&(Yt("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(Yt("\u2705 Parsed command:",r.name),t.push(r),e=!0)}catch(e){Yt("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",e instanceof Error?e.message:e+""),this.error=n}}else this.checkIdentifier()&&Yt("\u274c IDENTIFIER is not a command:",this.peek().value);if(!e){Yt("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(Yt("\ud83d\udccd After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)Yt("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))Yt("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){Yt("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}Yt("\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=""),Yt("\u2705 parseCommandListUntilTerminator: parsed",t.length,"commands (terminator:",r,")"),{commands:t,terminator:r}}parseCommandListUntilEnd(){const{commands:e}=this.parseCommandListUntilTerminator([]);if(Yt('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw Yt('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return Yt('\u2705 Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),n="else"===t;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:n}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const n=[];let r="forever",i=null,s=null,o=null,a=null,c=null,l=null;if(e.check(u)){e.advance(),r=u;const t=e.peek();un(t)&&(c=t.value,e.advance()),e.check(y)&&(e.advance(),a=e.parseExpression())}else if(e.check(y))e.advance(),r=u,c="it",a=e.parseExpression();else if(e.check(f))e.advance(),r=f,o=e.parseExpression();else if(e.check(d))if(e.advance(),r=d,e.check(x)){e.advance(),r="until-event";const t=e.peek();if(Yt("\ud83d\udccd Parsing event name, current token:",{value:t.value,kind:t.kind}),!un(t)&&!an(t))throw Error('Expected event name after "event"');if(i=t.value,e.advance(),Yt("\u2705 Got event name:",i,"Next token:",e.peek().value),Yt('\ud83d\udd0d Checking for "from", current token:',e.peek().value),e.check(v)){Yt('\u2705 Found "from", advancing...'),e.advance(),Yt('\ud83d\udccd After consuming "from", current token:',e.peek().value),zn(e,A)&&Yt('\u2705 Found "the", advancing...');const t=e.peek();Yt("\ud83d\udd0d Before parsePrimary for event target:",{value:t.value,kind:t.kind,position:t.start}),s=e.parsePrimary(),Yt("\u2705 After parsePrimary, eventTarget:",s)}else Yt('\u274c No "from" found, skipping target parsing')}else o=e.parseExpression();else e.check(h)?(e.advance(),r=h):(l=e.parseExpression(),e.check(m)&&(e.advance(),r=m));let g,w=null;if(e.check(b)){const t=e.peekAt(1);t&&t.value.toLowerCase()===p&&(e.advance(),e.advance(),w=p)}else if(e.check(p)){e.advance();const t=e.peek();un(t)?(w=t.value,e.advance()):w=p}let E=null,k=!1;if(r===h){const t=e.parseRepeatBody();if(g=t.commands,"else"===t.terminator)e.advance(),E=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(k=!0,r=t.terminator,e.advance(),o=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();g=t.commands,t.hasElse&&(e.advance(),E=e.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column});const S={start:t.start,end:t.end,line:t.line,column:t.column};c&&n.push(Rn(c,S)),a&&n.push(a),o&&n.push(o),l&&n.push(l),i&&n.push(Rn(i,S)),s&&n.push(s),w&&n.push(Rn(w,S)),n.push(In(g,{...S,end:S.end||0})),null!==E&&n.push(In(E,{...S,end:S.end||0}));const T=Jn.from(t).withArgs(...n);return k&&T.withModifier("bottomTested",{type:"literal",value:!0,...S}),T.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 s=e.peek();if(!un(s))throw Error('Expected variable name after "for"');if(r=s.value,e.advance(),!e.check(y))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 o=null;if(e.check(b)){const t=e.peekAt(1);t&&t.value.toLowerCase()===p&&(e.advance(),e.advance(),o=p)}else if(e.check(p)){e.advance();const t=e.peek();un(t)?(o=t.value,e.advance()):o=p}const a=e.parseCommandListUntilEnd();n.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return n.push(Rn(r,c)),n.push(i),o&&n.push(Rn(o,c)),n.push(In(a,{...c,end:c.end||0})),Jn.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")&&!Fn(e)){const r=e.parseExpression();return n.push(r),Jn.from(t).withArgs(...n).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const r=[];do{const t=e.peek();if(!un(t))throw Error('Expected event name 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(!un(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({name:n,params:i}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let i=null;e.check(v)&&(e.advance(),zn(e,A),i=e.parsePrimary());const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};n.push(Mn(r.map(e=>Ln([{key:jn("name",s),value:Nn(e.name,`"${e.name}"`,s)},{key:jn("args",s),value:Mn(e.params.map(e=>Nn(e,`"${e}"`,s)),s)}],s)),s)),i&&n.push(i)}return Jn.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(jn(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(Wn(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(Ln(r.map(e=>({key:e.name?jn(e.name,i):Nn("_positional","_positional",i),value:e.value})),i))}}return Jn.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const n=[],r={};let i=null;const s=e.peek();if(un(s)||"*"===s.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:s.start||0,end:e.getPosition().end,line:s.line,column:s.column})}if(!i)throw Error("Transition command requires a CSS property");if(n.push(i),!e.check(g))throw Error('Expected "to" keyword after property in transition command');e.advance();const o=e.parsePrimary();if(r.to=o,e.check("over")){e.advance();const t=e.parsePrimary();r.over=t}if(e.check(b)){e.advance();const t=e.parsePrimary();r.with=t}return Jn.from(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return function(e,t){const n=[];if(e.match("{"))n.push(e.parseCSSObjectLiteral());else{const t=_n(e,[g]);t&&n.push(t)}if(e.check(g)){e.advance();const t=_n(e);t&&n.push(t)}return Jn.from(t).withArgs(...n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseIfCommand(e){return Xn(this.getContext(),e)}parseRemoveCommand(e){return Yn(this.getContext(),e)}parseToggleCommand(e){return Qn(this.getContext(),e)}parseRegularCommand(e){return cr(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):yn(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()&&un(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}}{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}}}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(vn)||this.matchPredicate(on)||this.matchPredicate(cn)||this.matchPredicate(sn)||this.matchPredicate(an))){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(yn(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{type:"dollarExpression",expression:t,raw:`$${e.value}${this.previous().value||""}`,line:e.line,column:e.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.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(vn))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(vn)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",n=!0,this.checkPredicate(vn)&&(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(vn))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,s=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==s||!this.check(";")&&!this.check("}"));){const e=this.advance();r.push(e.value),0>o&&"number"==typeof e.start&&(o=e.start),"number"==typeof e.end&&(a=e.end),"$"===e.value&&this.check("{")&&(i=!0),"{"===e.value&&s++,"}"===e.value&&s--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,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:s,finallyHandler:o}=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!==s&&{errorHandler:s},...void 0!==o&&{finallyHandler:o},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(!(pr.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||vn(r)&&!this.isCommand(r.value)||cn(r)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let i,s;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}}),pr.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{s=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,e,i,s,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(Yt("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=e),t}catch(t){return Yt("\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(),s=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);e[n]=s,Yt(`\ud83d\udd27 parseEventHandler: Parsed '${t} at ${i.value}' (${s}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);e[n]=r,Yt(`\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(){Yt("\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,Yt("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(n),Yt("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),Yt("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t),Yt("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+t)}let r;if(Yt("\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,Yt(`\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"),Yt("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const s={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)s.once=!0,Yt("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===e)s.prevent=!0,Yt("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===e)s.stop=!0,Yt("\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?(s.debounce=n,Yt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(s.throttle=n,Yt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${e} delay`)}}else Yt(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${e}'`)}let o,a,c,l;if(this.parseTemporalKeywordModifiers(s),t&&(s.once=!0),Object.keys(s).length>0&&Yt("\ud83d\udd27 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();a=e.value,Yt(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${e.kind})`),this.parseTemporalKeywordModifiers(s)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value,Yt("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(Yt("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),Yt("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(Yt(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(Yt(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){Yt("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())Yt("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){Yt("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){Yt(`\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.parseCommandWithErrorRecovery();e&&(u.push(e),Yt("\u2705 parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const e=this.peek();if(this.isCommand(e.value)){const e=this.parseCommandWithErrorRecovery();e&&u.push(e)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){Yt("\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)break;{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name))break;{const n={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};u.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}let f,d,h;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:f,errorHandler:d,finallyHandler:h}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const m=this.getPosition(),p={type:"eventHandler",event:1===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},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:m.start,end:m.end,line:m.line,column:m.column};return Yt(`\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 n=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");n.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let s;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();vn(e)?(n.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=r.has(t.value);this.checkIsCommand()&&!n||(e.push(t.value),s=t.value,this.advance())}}const{commands:o,terminator:a}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const f={type:"eventHandler",event:t,commands:o,...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:l},...void 0!==u&&{finallyHandler:u},...void 0!==s&&{target:s},...n.length>0&&{args:n},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};i.push(f)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}s={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:t,parameters:n,eventHandlers:i,...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")||(Yt("\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"));)Yt("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){Yt('\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=Pn(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)}getMultiWordPattern(e){return function(e){return qn.find(t=>t.command===e.toLowerCase())||null}(e)}isTokenKeyword(e,t){return Bn(e,t)}parseMultiWordCommand(e,t){return function(e,t,n){const r=e.getMultiWordPattern(n);if(!r)return null;const i=[],s={};for(;!Fn(e,["catch","finally",...r.keywords])&&!Bn(e.peek(),r.keywords);){const t=e.parsePrimary();if(!t)break;if(i.push(t),!e.match(",")&&Bn(e.peek(),r.keywords))break}for(;!e.isAtEnd()&&Bn(e.peek(),r.keywords);){const t=e.advance().value,n=e.parseExpression();if(n&&(s[t]=n),!Bn(e.peek(),r.keywords))break}const o=Jn.from(t).withArgs(...i).endingAt(e.getPosition());return Object.keys(s).length>0&&o.withModifiers(s),o.build()}(this.getContext(),e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();t.push(e)}}return t}trySemanticParse(e){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const t=this.semanticAdapter.trySemanticParse(e);return t.success&&t.node?(Yt(`[Semantic] Successfully parsed with confidence ${t.confidence}:`,t.node.name),t.node):(Yt(`[Semantic] Low confidence (${t.confidence}), falling back to traditional parser`),null)}catch(e){return Yt("[Semantic] Error during semantic parse:",e),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(e=>e.value).join(" ");const e=this.current>0?this.tokens[this.current-1]:this.tokens[0];return e&&void 0!==e.start?this.originalInput.slice(e.start):this.originalInput}skipToCommandBoundary(){const e=["then","and","else","end"];for(;!this.isAtEnd();){const t=this.peek(),n=t.value.toLowerCase();if(e.includes(n))break;if(sn(t))break;this.advance()}}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 t=e.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch"].includes(t.toLowerCase())){const e=this.getRemainingInput(),t=this.trySemanticParse(e);if(t)return this.skipToCommandBoundary(),t}if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return function(e,t){const n={};let r=null;if(!e.isAtEnd()&&ur(e)&&(r=fr(e)),r||(r=e.parsePrimary()),!r)return e.addError("fetch requires a URL"),Jn.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(n.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||n.as){if(!e.check("with")||n.with){if(e.check("do")&&!n.doNotThrow){const t=e.peekAt(1),r=e.peekAt(2);if("not"===t?.value&&"throw"===r?.value){const t=e.advance();e.advance();const r=e.advance();n.doNotThrow={type:"literal",value:!0,start:t.start,end:r.end,line:t.line,column:t.column};continue}}break}e.advance(),n.with=dr(e)?hr(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||zn(e,"a")||zn(e,"an"),n.as=e.parsePrimary();const i=Jn.from(t).withArgs(r).endingAt(e.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}(this.getContext(),e);const n=this.parseMultiWordCommand(e,t);if(n)return n;const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||function(e,t){return{type:"command",name:e,args:[],partial:!0,start:t.start,end:t.end,line:t.line,column:t.column}}(r,this.getPosition());const i=[];if(("increment"===t||"decrement"===t)&&!this.isAtEnd())return function(e,t){const n=t.value,r="increment"===n?"+":"-";let i=!1;e.check(S)&&(i=!0,e.advance());const s=e.parseExpression();if(!s)throw Error("Expected variable or expression after "+n);let o;if(e.check("by")){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${n} command`);o=t}else o=Nn(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let a=s;i&&"identifier"===s.type&&(a={...s,scope:"global"});const c={start:t.start,end:e.previous().end,line:t.line,column:t.column},l=$n(r,s,o,c);l.coerceNumeric=!0;const u=[a,jn(g,c),l];return Jn.from(t).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:e.previous().end}).build()}(this.getContext(),e);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const e=this.parseExpression();if(i.push(e||this.parsePrimary()),this.match(","))continue;const t=["into","from","to","with","by","at","before","after","over"];if(t.some(e=>this.check(e)))continue;const n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!t.includes(n.name??n.value))break}const s=this.getPosition();return{type:"command",name:t,args:i,isBlocking:!1,start:s.start,end:s.end,line:s.line,column:s.column}}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:n,start:r.start,end:r.end,line:r.line,column:r.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=[];if(this.match("of"))t.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(e));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||t.push(this.parsePrimary())}const n=this.createCallExpression(this.createIdentifier(e),t);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(n.relativePositional=e)}return n}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){if(this.match("*")){let t="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(""),!1);for(t=this.advance().value;this.check("-")&&!this.isAtEnd();){if(t+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}t+=this.advance().value}const n="*"+t;return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const t=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(e),{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column},!0)}if(yn(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}const t=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(this.createIdentifier(e),this.createIdentifier(t.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;D(t)&&Yt(`\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 Nn(e,t,this.getPosition())}createIdentifier(e){return jn(e,this.getPosition())}createBinaryExpression(e,t,n){return $n(e,t,n,this.getPosition())}createUnaryExpression(e,t,n){return function(e,t,n,r){return{type:"unaryExpression",operator:e,argument:t,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createCallExpression(e,t){return function(e,t,n){return{type:"callExpression",callee:e,arguments:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createMemberExpression(e,t,n){return function(e,t,n,r){return{type:"memberExpression",object:e,property:t,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,n,this.getPosition())}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,n){return{type:"possessiveExpression",object:e,property:t,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return t}})}createProgramNode(e){return function(e){if(Yt(`\u2705 createProgramNode: Called with ${e.length} statements`),0===e.length)return Yt("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return Yt(`\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 Yt(`\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!(!Cn(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(dn)}matchSelector(){return this.matchPredicate(dn)}checkAnySelector(){return this.checkPredicate(fn)}checkLiteral(){return this.checkPredicate(hn)}checkIdentifierLike(){return this.checkPredicate(un)}checkIsCommand(){return this.checkPredicate(sn)}checkCommandTerminator(){return this.checkPredicate(On)}checkReference(){return this.checkPredicate(mn)}checkTimeExpression(){return this.checkPredicate(pn)}checkEvent(){return this.checkPredicate(an)}checkContextVar(){return this.checkPredicate(cn)}checkComment(){return this.checkPredicate(gn)}checkIdentifier(){return this.checkPredicate(vn)}checkKeyword(){return this.checkPredicate(on)}checkString(){return this.checkPredicate(bn)}matchString(){return this.matchPredicate(bn)}checkNumber(){return this.checkPredicate(wn)}matchNumber(){return this.matchPredicate(wn)}checkBoolean(){return this.checkPredicate(En)}matchBoolean(){return this.matchPredicate(En)}checkTemplateLiteral(){return this.checkPredicate(xn)}matchTemplateLiteral(){return this.matchPredicate(xn)}checkQueryReference(){return this.checkPredicate(kn)}matchQueryReference(){return this.matchPredicate(kn)}checkIdSelector(){return this.checkPredicate(Sn)}checkClassSelector(){return this.checkPredicate(An)}checkCssSelector(){return this.checkPredicate(Tn)}checkBasicOperator(){return this.checkPredicate(Cn)}matchBasicOperator(){return this.matchPredicate(Cn)}matchTimeExpression(){return this.matchPredicate(pn)}matchIdentifierLike(){return this.matchPredicate(un)}matchComparisonOperator(){return this.matchPredicate(ln)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(vn,e)}consumeIdentifierLike(e){return this.consumePredicate(un,e)}consumeEvent(e){return this.consumePredicate(an,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)}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;Yt("\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 s="["+i+"]";return{type:"literal",value:s,raw:s,start:e,end:this.previous().end,line:t,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),i=this.tokens[this.current],s=this.tokens[this.current+1];if("identifier"===i?.kind&&("]"===s?.value||s&&r.has(s.value)&&"string"===this.tokens[this.current+2]?.kind)){let e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,n=this.advance().value;e+=t+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:e,end:this.previous().end,line:t,column:n}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>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 yr(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&&(Ct(t),n>t.position);){const n=e[t.position];if("-"!==n||"-"!==At(t,1))if('"'!==n){if("'"===n||"'"===n){const e=At(t,1),n=t.tokens[t.tokens.length-1];if("s"!==e||!n||/\s/.test(t.input[t.position-1]??" ")||n.kind!==xt.IDENTIFIER&&n.kind!==xt.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)$t(t);else{const e=t.position;Tt(t),Tt(t),Ot(t,xt.OPERATOR,"'s",e)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===At(t,1)){const e=t.position;Tt(t),Tt(t),Ot(t,xt.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===xt.IDENTIFIER&&C.has(e.value.toLowerCase()),i=e&&e.kind===xt.IDENTIFIER&&n.has(e.value.toLowerCase());if((!e||e.kind===xt.OPERATOR&&")"!==e.value&&"]"!==e.value||r||i||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&(!e||e.end!==t.position)&&(Vt(At(t))||"{"===At(t)||"-"===At(t))){Rt(t);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const e=t.tokens[t.tokens.length-1],n=e&&e.kind===xt.IDENTIFIER&&F.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;(!e||e.kind!==xt.IDENTIFIER&&")"!==e.value&&"]"!==e.value||n)&&n?(Ot(t,xt.SYMBOL,"["),Tt(t)):(Ot(t,xt.OPERATOR,"["),Tt(t));continue}if("]"!==n){if("$"===n){const e=At(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){Bt(t);continue}}Ut(n)?Dt(t):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(Ot(t,xt.UNKNOWN,n),Tt(t)):qt(t):Pt(t)}else Ot(t,xt.OPERATOR,"]"),Tt(t)}else Ot(t,xt.OPERATOR,"}"),Tt(t);else Ot(t,xt.OPERATOR,"{"),Tt(t);else Mt(t)}else Rt(t);else Ht(t)?Lt(t):Dt(t);else It(t)}else $t(t);else jt(t)}return t.tokens}(e);return new pr(n,t,e).parse()}function gr(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 vr(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}async function br(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 Tr(e,t);const n=e;switch(e.type){case"literal":return function(e){return e.value}(n);case"identifier":return Tr(n,t);case"binaryExpression":return async function(e,t){const n=e.operator,r=e.right,i=e.left;if("="===n){const n=await br(e.right,t);if("identifier"===i?.type&&"string"==typeof i.name){const e=i.name;return e.startsWith("$")?ce(t,e.slice(1),n):"global"===i.scope?ce(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 br(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 br(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 br(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 br(e.right,t);return gr(t,"styleRef").evaluate(t,i.value.slice(1),n)}if("of"===n){const n=Cr(e.left);if(n){const r=await br(e.right,t);let i=r;for(const e of n){if(null==i)return;i=je(i)?Me(i,e):i[e]}return"function"==typeof i?i.bind(r):i}}const s=await br(e.left,t);if("and"===n){if(!s)return s;const n=await br(e.right,t);return gr(t,"and").evaluate(t,s,n)}if("or"===n){if(s)return s;const n=await br(e.right,t);return gr(t,"or").evaluate(t,s,n)}const o=await br(e.right,t),a=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?a(s):s,l=e.ignoringCase?a(o):o;switch(n){case"+":{let n=s,r=o;return e.coerceNumeric&&("string"==typeof n&&(n=be(n)),"string"==typeof r&&(r=be(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:vr(await gr(t,"addition").evaluate(t,{left:n,right:r}))}case"-":return vr(await gr(t,"subtraction").evaluate(t,{left:s,right:o}));case"*":return vr(await gr(t,"multiplication").evaluate(t,{left:s,right:o}));case"/":return vr(await gr(t,"division").evaluate(t,{left:s,right:o}));case"%":case"mod":return vr(await gr(t,"modulo").evaluate(t,{left:s,right:o}));case"^":case"**":return vr(await gr(t,"power").evaluate(t,{left:s,right:o}));case">":case"is greater than":return gr(t,"greaterThan").evaluate(t,s,o);case"<":case"is less than":return gr(t,"lessThan").evaluate(t,s,o);case">=":case"is greater than or equal to":return gr(t,"greaterThanOrEqual").evaluate(t,s,o);case"<=":case"is less than or equal to":return gr(t,"lessThanOrEqual").evaluate(t,s,o);case"==":return gr(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=jr(e,s,o);return void 0!==n?n:gr(t,"equals").evaluate(t,c,l)}case"!=":return gr(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const n=jr(e,s,o);return void 0!==n?!n:gr(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return gr(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return gr(t,"strictNotEquals").evaluate(t,c,l);case"as":return gr(t,"as").evaluate(t,s,Ir(o));case"contains":case"contain":case"includes":case"include":return gr(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return gr(t,"doesNotContain").evaluate(t,c,l);case"starts with":return gr(t,"startsWith").evaluate(t,c,l);case"ends with":return gr(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await gr(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await gr(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return gr(t,"matches").evaluate(t,c,Nr(e.right,l));case"does not match":case"do not match":return!await gr(t,"matches").evaluate(t,c,Nr(e.right,l));case"in":case"is in":case"am in":return Or(s,o);case"is not in":case"am not in":return!Or(s,o);case"of":return o&&"object"==typeof o?o[s]:void 0;case"precedes":return $r(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!$r(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return $r(s,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!$r(s,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,t);case"asExpression":return async function(e,t){const n=await br(e.expression,t),r=Ir(e.targetType);return gr(t,"as").evaluate(t,n,r)}(n,t);case"betweenExpression":return async function(e,t){const n=await br(e.value,t),r=await br(e.min,t),i=await br(e.max,t),s=e=>"string"==typeof e?e.toLowerCase():e,[o,a,c]=e.ignoringCase?[s(n),s(r),s(i)]:[n,r,i],l=await gr(t,"between").evaluate(t,o,a,c);return e.negated?!l:l}(n,t);case"typeCheckExpression":return async function(e,t){const n=function(e,t,n){if(null==e&&n)return!0;if(Object.prototype.toString.call(e).slice(8,-1)===t)return!0;const r=globalThis[t];return"function"==typeof r&&e instanceof r}(await br(e.value,t),e.typeName+"",!1!==e.nullOk);return e.negated?!n:n}(n,t);case"collectionExpression":return async function(e,t){const n=await br(e.collection,t);if(null==n)return n;const r=async(e,n)=>br(e,{...t,it:n});switch(e.operator){case"where":return async function(e,t,n){const r=Et(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=[...Et(e)],s=await Promise.all(i.map(e=>r(t,e))),o=i.map((e,t)=>t);o.sort((e,t)=>{const n=s[e],r=s[t];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.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=Et(e);return Promise.all(r.map(e=>n(t,e)))}(n,e.right,r);case"split by":return s=await br(e.right,t),null==(i=n)?[]:(i+"").split(null==s?"":s+"");case"joined by":return function(e,t){const n=null==t?"":t+"";return Et(e).map(e=>null==e?"":e+"").join(n)}(n,await br(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var i,s}(n,t);case"unaryExpression":return async function(e,t){const n=e.operand??e.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const r=await br(n,t);switch(e.operator){case"not":case"!":return gr(t,"not").evaluate(t,r);case"no":return gr(t,"no").evaluate(t,r);case"-":return-r;case"+":return+r;case"exists":case"some":return gr(t,"exists").evaluate(t,r);case"does not exist":return gr(t,"doesNotExist").evaluate(t,r);case"is empty":return gr(t,"isEmpty").evaluate(t,r);case"is not empty":return gr(t,"isNotEmpty").evaluate(t,r);default:throw Error("Unknown unary operator: "+e.operator)}}(n,t);case"memberExpression":return async function(e,t){const n=await br(e.object,t);if(e.computed){const r=await br(e.property,t);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return Dr(n,e.property.name,t)}(n,t);case"propertyAccess":return async function(e,t){let n=await br(e.object,t);for(const r of(e.property+"").split(".")){if(null==n)return;n=await Dr(n,r,t)}return n}(n,t);case"callExpression":return async function(e,t){const n=await br(e.callee,t);if(e.isConstructor&&"function"==typeof n)return new n(...await Promise.all(e.arguments.map(e=>br(e,t))));if("identifier"===e.callee.type){const r=e.callee.name,i=await async function(e,t,n){return Pr.has(t)?Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:br(e,n))):Promise.all(e.map(e=>br(e,n)))}(e.arguments,r,t);switch(r){case"closest":return gr(t,"closest").evaluate(t,...i);case"previous":case"next":{const n=e.relativePositional;if(n){const e=n.from?qr(await br(n.from,t)):t.me,s=n.within?qr(await br(n.within,t)):void 0,o=n.inElt?await br(n.inElt,t):void 0;return gr(t,r).evaluate(t,i[0],e,{within:s,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return gr(t,r).evaluate(t,...i)}case"first":return gr(t,"first").evaluate(t,...i);case"last":return gr(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=>br(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const i=await br(e.callee.object,t);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(n,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 gr(t,"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=Hr(e),r=await Promise.all(n.filter(e=>"expr"in e).map(e=>kr(e.expr,t)));return Ur(n,r)}(n,t),s=Fr(e,r);i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await gr(t,"elementWithSelector").evaluate(t,s)}finally{i.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!e.fromQuery&&n.includes("{")&&(n=await function(e,t){return Mr(e,/\{([^}]*)\}/g,async(e,n)=>(await kr(n.trim(),t)??"")+"")}(n,t));const r="string"==typeof n?Fr(e,n):n,i=await gr(t,"elementWithSelector").evaluate(t,r);return!e.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(i)?i[0]??null:i}(n,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return gr(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return gr(t,"me").evaluate(t);case"your":case"yourself":return gr(t,"you").evaluate(t);case"its":return gr(t,"it").evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??gr(t,"me").evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return gr(t,"document").evaluate(t);case"window":return gr(t,"window").evaluate(t);default:return}}(n,t);case"possessiveExpression":return async function(e,t){const n=await br(e.object,t),r=e.property.name;return gr(t,"possessive").evaluate(t,n,r)}(n,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async n=>{const r={...t,event:n,target:n.target,currentTarget:n.currentTarget};for(const t of e.commands)await br(t,r)}}}(n,t);case"conditionalExpression":return async function(e,t){return await br(e.test,t)?br(e.consequent,t):e.alternate?br(e.alternate,t):void 0}(n,t);case"string":return n.value;case"arrayLiteral":return async function(e,t){const n=[];for(const r of e.elements)n.push(await br(r,t));return n}(n,t);case"objectLiteral":return async function(e,t){const n={};for(const r of e.properties){const e=r.key;let i;i="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await br(e,t)+"",n[i]=await br(r.value,t)}return n}(n,t);case"attributeAccess":return async function(e,t){const n=e.attributeName;return t.me&&t.me instanceof Element?t.me.getAttribute(n):"@"+n}(n,t);case"propertyOfExpression":return async function(e,t){const n=e.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await br(e.target,t);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return gr(t,"possessive").evaluate(t,i,r)}(n,t);case"templateLiteral":return async function(e,t){let n=e.value;return n=await Mr(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=Lr(e[0],t);for(let t=1;e.length>t&&null!=r;t++)r=r[e[t]];return(r??"")+""}return(Lr(n,t)??"")+""}catch{return""}}),n=await Mr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,n,r)=>{const i=n||r;try{return await kr(i,t)+""}catch{return"undefined"}}),n}(n,t);case"stringPostfix":return async function(e,t){return`${await br(e.expression,t)}${e.unit}`}(n,t);case"blockLiteral":return Rr(n,t);default:{const n=G.get(e.type);if(n)return n(e,t);throw Error("Unknown AST node type: "+e.type)}}}pr.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),pr.PRATT_TABLE=K,pr.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class wr extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function Er(e,t){const n=e;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(e,t){const n=e.value;if("string"!=typeof n)throw new wr("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new wr("selector");if(e.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(e,t){const n=Hr(e),r=n.filter(e=>"expr"in e).map(e=>xr(e.expr,t));return Ur(n,r)}(n,t),s=Fr(e,r),o=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new wr("selector");i.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(o.querySelectorAll(s))}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)=>(xr(n.trim(),t)??"")+"")}(n,t):n,i=Fr(e,r),s=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new wr("selector");const o=Array.from(s.querySelectorAll(i));return!e.fromQuery&&r.startsWith("#")?o[0]??null:o}(n,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:"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)):void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(n.name,t,n.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 wr("contextReference")}}(n.contextType,t);case"arrayLiteral":return n.elements.map(e=>Er(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:Er(e,t)+"",n[i]=Er(r.value,t)}return n}(n,t);case"asExpression":return pt(Er(n.expression,t),Ir(n.targetType),t);case"stringPostfix":return`${Er(n.expression,t)}${n.unit}`;case"blockLiteral":return Rr(n,t);case"memberExpression":{const e=Er(n.object,t);if(null==e)return;if(e instanceof Element||Array.isArray(e)||"undefined"!=typeof Node&&e instanceof Node)throw new wr("memberExpression");const r=e[n.computed?Er(n.property,t)+"":n.property?.name];return"function"==typeof r?r.bind(e):r}default:throw new wr(n?.type??"unknown")}}function xr(e,t){const n=yr(e);if(!n.success||!n.node){const e=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return Er(n.node,t)}async function kr(e,t){const n=yr(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 Ar()};return br(n.node,r)}let Sr=null;async function Ar(){if(!Sr){const e=await Promise.resolve().then(function(){return xs});Sr=e.createFullExpressionRegistry()}return Sr}async function Tr(e,t){const n=e.name;return"me"===n||"my"===n||"I"===n?gr(t,"me").evaluate(t):"you"===n||"your"===n||"yourself"===n?gr(t,"you").evaluate(t):"it"===n||"its"===n?gr(t,"it").evaluate(t):"window"===n?gr(t,"window").evaluate(t):"document"===n?gr(t,"document").evaluate(t):"global"===e.scope&&t.globals?.has(n)?(se(n,t),t.globals.get(n)):"element"===e.scope?he(t,n):t.locals&&t.locals.has(n)?(ae(n,t),t.locals.get(n)):t.globals&&t.globals.has(n)?(n.startsWith("$")&&se(n.slice(1),t),t.globals.get(n)):n.startsWith("$")&&t.globals&&t.globals.has(n.slice(1))?(se(n.slice(1),t),t.globals.get(n.slice(1))):void 0!==t[n]?t[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function Cr(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=Cr(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 Or(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 Nr(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function jr(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 $r(e,t,n){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&n)}function Ir(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 Rr(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 s={...t,locals:i};try{return Er(e.body,s)}catch(t){if(t instanceof wr)return br(e.body,s);throw t}}}function Lr(e,t){return t.locals?.has(e)?(ae(e,t),t.locals.get(e)):"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function Mr(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 s=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,replacement:i}=r[e];s=s.substring(0,t)+i+s.substring(t+n)}return s}function Dr(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?Me(e,t):bt(e)&&!(t in e)?gr(n,"possessive").evaluate(n,e,t):e?.[t]}const Pr=new Set(["closest","previous","next"]);function qr(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const Br=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"),Vr=/[:&()[\]/]/g;function Fr(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace(Br,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(Vr,"\\$&")}(t)}const _r=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Hr(e){const t=[];let n,r=0;for(_r.lastIndex=0;null!==(n=_r.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 Ur(e,t){let n="";const r=[];let i=0;for(const s of e){if("lit"in s){n+=s.lit;continue}const e=t[i++];je(e)?(n+=`[data-hs-query-id='${r.length}']`,r.push(e)):n+=(e??"")+""}return{selector:n,elements:r}}class zr{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&&Qt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&Qt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&Qt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&Qt("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&&Qt("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&&Qt(`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&&Qt("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&Qt(`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&&Qt("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&Qt(`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 s of this.globalCleanups)switch(s.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 Wr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const n=e.toLowerCase();this.sources.has(n)&&Qt("[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 Qt("[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()}}class Jr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,n){const r=e.toLowerCase();this.providers.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}registerGlobal(e,t,n){const r=e.toLowerCase();this.globalProviders.set(r,"function"==typeof t?{name:r,provide:t,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,n){const r=this.get(e);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const e of r.dependencies)await this.resolve(e,t,n);const s=await r.provide(t);return r.cache&&n&&n.set(i,s),s}resolveSync(e,t,n){const r=this.get(e);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);const s=r.provide(t);if(s instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,s),s}enhance(e){const t=this,n=new Map;return new Proxy(e,{get(e,r,i){if("string"==typeof r&&t.get(r))try{return t.resolveSync(r,e,n)}catch{return t.resolve(r,e,n)}return Reflect.get(e,r,i)},has:(e,n)=>!("string"!=typeof n||!t.has(n))||Reflect.has(e,n)})}async resolveAll(e){const t=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,s]of r)try{n[i]=await this.resolve(i,e,t)}catch(e){Qt(`[ContextProviderRegistry] Failed to resolve '${i}':`,e),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Zr={evaluate:(e,t)=>br(e,t)};class Kr{static toTyped(e){return{me:e.me,...void 0!==e.owner&&{owner:e.owner},it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},...void 0!==e.registry&&{registry:e.registry},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class Xr{constructor(e,t,n){this.impl=e,this.hookRegistry=n??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,n={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:n,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:Array.isArray(e)?e.join(" | "):e||""}}async execute(e,...t){const n=t[0],r=this.createHookContext(e,t,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(Xt(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void Xt(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Kr.toTyped(e);let s,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(Xt(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const t=n.modifiers,r=t?.when||t?.where;if(r&&!await br(r,e))return void Xt(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);s=await this.impl.parseInput({args:n.args||[],modifiers:t||{},commandName:n.commandName},Zr,e)}else s=t;else Xt(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),s=t;if(Xt("CommandAdapterV2: Calling execute with parsed input:",s),2===this.impl.execute.length)o=await this.impl.execute(s,i);else{const e=Array.isArray(s)?s:[s];o=await this.impl.execute(i,...e)}return Xt("CommandAdapterV2: Command result:",o),Object.assign(e,Kr.fromTyped(i,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(e){if(ni(e)||Xt(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(r,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class Gr{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);Qt(`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();Qt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,e);const r=new Xr(e,void 0,this.hookRegistry);this.adapters.set(n,r),C.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),C.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 Yr=null;function Qr(){return Yr||(Yr=function(e){const t=e?.commands??new Gr,n=e?.eventSources??new Wr,r=e?.context??new Jr,i=new Set,s={commands:t,eventSources:n,context:r,use(e){if(i.has(e.name))Qt(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const n of e.commands)t.register(n);if(e.eventSources)for(const t of e.eventSources)n.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:n,options:i}of e.contextProviders)r.register(t,n,i);e.setup?.(s),i.add(e.name)}},reset(){i.clear()}};return s}()),Yr}class ei{constructor(e={}){this.contextCache=new WeakMap;const t=Qr();this.options={enableContextProviders:e.enableContextProviders??!0,enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.contextRegistry=this.options.registry.context??t.context,this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources,Qt(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(e){if(!this.options.enableContextProviders)return e;const t=this.contextCache.get(e);if(t)return t;try{const t=this.contextRegistry.enhance(e);return this.contextCache.set(e,t),Qt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return Qt("[RegistryIntegration] Failed to enhance context: "+(t instanceof Error?t.message:t+"")),e}}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return Qt(`[RegistryIntegration] Found event source for '${e}'`),t;const n=this.eventSourceRegistry.findSourceForEvent(e);if(n){const t=this.eventSourceRegistry.get(n);return Qt(`[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 Qt(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,Qt("[RegistryIntegration] Destroyed")}}function ti(e){const t=Error(e.type.toUpperCase()+"_EXECUTION");return t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}function ni(e){return e instanceof Error&&(null!==n(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function ri(e){if(void 0===e)return;let t=e;if(t&&"object"==typeof t){const e=t;if("result"in e&&"wasAsync"in e)t=e.result;else if("result"in e&&"executed"in e){if(t=e.result,e.preserveArrayResult)return void 0!==t?t:void 0}else if("lastResult"in e&&"type"in e)t=e.lastResult;else if("conditionResult"in e&&"executedBranch"in e){if(void 0===e.result)return;t=e.result}else"value"in e&&1===Object.keys(e).length||"value"in e&&"target"in e&&"targetType"in e?t=e.value:"data"in e&&"status"in e&&"headers"in e&&(t=e.data)}return Array.isArray(t)&&t.length>0&&(t=t[0]),t}function ii(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const si=new WeakMap;class oi{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=le,this.hookRegistry=new t,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new zr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new ei("object"==typeof e.registryIntegration?e.registryIntegration:{}),Qt("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&&Qt(`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(),Qt("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){Qt(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.registry||(t.registry=this.expressionRegistry),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,n)=>this.execute(e,n||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return Qt("\u26a0\ufe0f RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern){const n=await this.processCommandWithResult(e,t);if(!s(n)){if("return"===n.error.type){const e=n.error.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw ti(n.error)}return n.value}try{return await this.processCommand(e,t)}catch(e){const r=n(e);if(r?.isReturn){const e=r.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}throw e}case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const n={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(n,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const n=e,r=await this.executeCommandSequenceWithResult(n.commands||[],t);if(!s(r))throw ti(r.error);return r.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(e,t);if(!s(n))throw ti(n.error);return n.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:n,args:r,modifiers:i}=e,s=n.toLowerCase();if(Xt(`RUNTIME BASE: Processing command '${s}'`),this.registry.has(s)){const e=await this.registry.getAdapter(s);if(!e)throw Error(`Command '${s}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:r||[],modifiers:i||{},commandName:s,runtime:this})}catch(e){throw ni(e)||this.logError(`Error executing command '${s}':`,e),e}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(e){const t=n(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:n,args:s,modifiers:o}=e,a=n.toLowerCase();if(Xt(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const c=await this.registry.getAdapter(a);if(!c)throw Error(`Command '${a}' is registered but failed to load adapter.`);try{return r(await c.execute(t,{args:s||[],modifiers:o||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return i(t);throw this.logError(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const i of e){if(this.hasErrorDiagnostics(i)){const e=i.diagnostics?.[0];Qt("\u26a0\ufe0f RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===i.type){const e=await this.processCommandWithResult(i,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}),r(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(i,t);if(!s(e))return e;n=e.value}}return r(n)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},r=await br(e,n);return ii(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},o=await async function(e,t){try{return r(await br(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return i({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return i({type:"exit",returnValue:t.returnValue});if(t.isBreak)return i({type:"break"});if(t.isContinue)return i({type:"continue"});if(t.isReturn)return i({type:"return",returnValue:t.returnValue})}throw e}}(e,n);if(!s(o))return o;const a=o.value;if(ii(a)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:a.command,args:[{type:"literal",value:a.selector}]},t);try{return r(await this.executeCommandFromPattern(a.command,a.selector,t))}catch(e){const t=this.toSignal(e);if(t)return i(t);throw e}}return r(a)}async executeCommandFromPattern(e,t,n){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},n)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let n;const r=[],i=[],s=[];for(const t of e.statements)"eventHandler"===t.type?r.push(t):"initBlock"===t.type?i.push(t):s.push(t);for(const e of r)try{await this.execute(e,t)}catch(e){if(ni(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{n=await this.execute(e,t)}catch(e){if(ni(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of s)try{n=await this.execute(e,t)}catch(e){if(ni(e)&&(e.isHalt||e.isExit))break;throw e}return n}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const n of e.commands)try{await this.execute(n,t)}catch(e){if(ni(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let n;for(const r of e.commands)try{n=await this.execute(r,t)}catch(e){if(ni(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return n}async executeObjectLiteral(e,t){const n={};if(!e.properties)return n;for(const r of e.properties){let e;e="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,t)+"";const i=await this.execute(r.value,t);n[e]=i}return n}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:s}=e,o=e.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),Qt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:s}),Qt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(e,t,n){Qt("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&&(Qt(`BEHAVIOR: Installing imperative behavior '${e}'`),r.install(t,n),Qt(`BEHAVIOR: Finished installing imperative behavior '${e}'`)));Qt("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,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},s=this.enhanceContext(i);if(r.parameters)for(const e of r.parameters)s.locals.set(e,e in n?n[e]:void 0);for(const[e,t]of Object.entries(n))r.parameters?.includes(e)||s.locals.set(e,t);if(r.initBlock){Qt("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),Qt("BEHAVIOR: Init block completed for "+e)}catch(t){if(Qt(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&ni(t)))throw t}}if(Qt(`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,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}Qt("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:n,events:r,commands:i,target:s,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u,errorSymbol:f,errorHandler:d,finallyHandler:h}=e,m=r&&r.length>0?r:[n];Qt(`BEHAVIOR: executeEventHandler: event='${n}', target='${s}'`);let p=[],y=null;if(s){const e="string"==typeof s?s.toLowerCase():"";if("window"===e||"the window"===e)y=window;else if("document"===e||"the document"===e||"body"===e)y=document;else if("me"===e||"myself"===e)p=t.me?[t.me]:[];else if("string"==typeof s&&t.locals.has(s)){const e=t.locals.get(s);Qt(`BEHAVIOR: Target resolution: found local '${s}', isElement: ${this.isElement(e)}`),this.isElement(e)?p=[e]:Array.isArray(e)?p=e.filter(e=>this.isElement(e)):"string"==typeof e&&(p=this.queryElements(e,t))}else Qt(`BEHAVIOR: Target resolution: querying for '${s}'`),p=this.queryElements(s,t)}else p=t.me?[t.me]:[];if(0===p.length&&!y)return void Qt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(p,c,i,t);if("change"===n&&l)return void this.setupChangeObserver(l,i,t);const g=e.customEventSource;if(g&&this.registryIntegration){Qt(`BEHAVIOR: executeEventHandler - Using custom event source '${g}' for event '${n}'`);const e=async e=>{const r=new Map(t.locals),s={...t,locals:r,it:e,event:e},o=this.enhanceContext(s);Qt(`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:s,selector:a},t);Qt(`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=oi.createEventHandler(this,i,t,a,o,{errorSymbol:f,errorHandler:d,finallyHandler:h});let b,w=null;if(u){let e=v;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let n;b=r=>{n&&clearTimeout(n),n=setTimeout(()=>e(r),t)},w=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const t=u.throttle;let n=0;b=r=>{const i=Date.now();t>i-n||(n=i,e(r))}}else b=e}else b=v;const E=u?.once?{once:!0}:void 0;if(y){for(const e of m)y.addEventListener(e,b,E),p.length>0?this.cleanupRegistry.registerListener(p[0],y,e,b):this.cleanupRegistry.registerGlobal(()=>y.removeEventListener(e,b),"listener",`Global ${e} listener`);w&&(p.length>0?this.cleanupRegistry.registerCustom(p[0],w,"debounce-timeout"):this.cleanupRegistry.registerGlobal(w,"timeout","debounce-timeout"))}else for(const e of p){for(const t of m){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,b(e),E?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,b,E),this.cleanupRegistry.registerListener(e,e,t,b)}w&&this.cleanupRegistry.registerCustom(e,w,"debounce-timeout")}}static createEventHandler(e,t,n,r,i,s){return async o=>{const a=si.get(o)??0;if(a>=100)return;if(si.set(o,a+1),r&&o.target instanceof Element)try{if(!o.target.matches(r)&&!o.target.closest(r))return}catch{Qt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const c=new Map(n.locals),l={...n,locals:c,it:o,event:o};c.has("target")||l.locals.set("target",o.target);const u=e.enhanceContext(l);if(i&&i.length>0){const e=o,t=e.detail;for(const n of i)u.locals.set(n,e[n]??t?.[n]??null)}const f=async t=>{for(const n of t)try{const t=ri(await e.execute(n,u));void 0!==t&&Object.assign(u,{it:t,result:t})}catch(t){if(ni(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(u,{it:t.returnValue,result:t.returnValue});break}}throw e.logError("COMMAND FAILED:",t),t}},d=s?.errorHandler,h=s?.finallyHandler;if(d||h)try{await f(t)}catch(e){if(!d||ni(e))throw e;s?.errorSymbol&&u.locals.set(s.errorSymbol,e),await f(d)}finally{h&&await f(h)}else await f(t)}}setupMutationObserver(e,t,n,r){Qt(`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 s of e)if("attributes"===s.type&&s.attributeName===t){Gt(`MUTATION DETECTED: attribute '${t}' changed on`,i);const e={...r,me:i,it:s,locals:new Map(r.locals)},o=s.oldValue,a=i.getAttribute(t);e.locals.set("oldValue",o),e.locals.set("newValue",a);const c=this.enhanceContext(e);for(const e of n)try{await this.execute(e,c)}catch(e){if(ni(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing mutation handler command:",e)}}});e.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(i,e),Qt("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${t}'`)}}async setupChangeObserver(e,t,n){Qt("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))),Qt(`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){Gt("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 s=i.oldValue,o=e.textContent;null!==s&&r.locals.set("oldValue",s),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const e of t)try{await this.execute(e,a)}catch(e){if(ni(e)){if(e.isHalt||e.isExit||e.isReturn)break}else this.logError("Error executing change handler command:",e)}}});r.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,r),Qt("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 Qt(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}function ai(...e){const t=new Map;for(const n of e)for(const[e,r]of Object.entries(n))t.set(e,r);return t}const ci=Ye({selector:Ke().min(1),single:Ge().optional().default(!1)});function li(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]}new class extends rt{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=nt(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.me,i=this.isElement(r)?r:null,s=this.success(i,"element");return this.trackPerformance(e,t,s,n),s}catch(r){const i=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends rt{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=nt(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.you,i=this.isElement(r)?r:null,s=this.success(i,"element");return this.trackPerformance(e,t,s,n),s}catch(r){const i=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends rt{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=nt(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=e.it,i={success:!0,value:r,type:this.inferType(r)};return this.trackPerformance(e,t,i,n),i}catch(r){const i=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,i,n),i}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends rt{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=ci,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const n=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,r,n),r}let r;if(t.single)r=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));r=e.length>0?e:null}const i={success:!0,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(e,t,i,n),i}catch(r){const i=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=t.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}};const ui={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:Fe},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:Fe},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Fe},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:Fe},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:Fe},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=>Be(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=>Be(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=>Be(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=>Be(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:Fe},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Fe},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Fe},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=>Be(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 li(i,n)},validate:e=>He(e,1,2,"styleRef","property, optional element")??qe(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 li(i,r)},validate:e=>Pe(e,2,"possessiveStyleRef","possessor, property")??qe(e,0,"possessiveStyleRef","possessor")??qe(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 li(i,n)},validate:e=>Pe(e,2,"ofStyleRef","property, reference")??qe(e,0,"ofStyleRef","property")??qe(e,1,"ofStyleRef","reference")}};class fi{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 di=new class{constructor(){this.domQueryCache=new fi(200,3e3),this.exprResultCache=new fi(500,2e3),this.cssMatchCache=new fi(100,5e3),this.formValueCache=new fi(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)})})}};"undefined"!=typeof window&&setInterval(()=>{di.cleanup()},1e4);const hi=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=di.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 mi(){di.cleanup(),hi.getMetrics().memoryUsage>52428800&&hi.reset()}let pi=null;function yi(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 yi(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 gi(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 vi(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 bi(e){try{return yi(e,"_"),!0}catch{return!1}}function wi(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=gi(e),r=gi(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 Ei(e,t);case"!=":return!Ei(e,t);default:return!1}}function Ei(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?Ei(e?1:0,t):"boolean"==typeof t?Ei(e,t?1:0):e+""==t+""}function xi(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function ki(e,t,n=[],r="error"){return{type:e,message:t,suggestions:n,severity:r}}function Si(e,t,n,r,i,s=!0,o){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:s,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(e=3e4){pi&&clearInterval(pi),pi=setInterval(mi,e)}();const Ai=Ye({left:et().describe("Left operand value"),right:et().describe("Right operand value")}).strict(),Ti=Ye({operand:et().describe("Operand value to negate")}).strict();function Ci(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}new class extends rt{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=Ai,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.toBoolean(t.left);if(!i)return this.trackSimple(e,n,!0,"boolean"),this.success(!1,"boolean");const s=this.toBoolean(t.right),o=i&&s;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=Ai,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.toBoolean(t.left);if(i)return this.trackSimple(e,n,!0,"boolean"),this.success(!0,"boolean");const s=this.toBoolean(t.right),o=i||s;return this.trackSimple(e,n,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=Ti,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=!this.toBoolean(t.operand);return this.trackSimple(e,n,!0,"boolean"),this.success(i,"boolean")}catch(t){return this.trackSimple(e,n,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Oi=Qe([et(),et()]),Ni=Qe([et(),Ke()]),ji={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,n){const r=Date.now();try{return Si(this,e,[t,n],t==n,r)}catch(i){throw Si(this,e,[t,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:e=>Ve(e,"equals"),inputSchema:Oi,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},$i={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,n){const r=e.evaluationHistory,i=t===n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"strictEquals")},Ii={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,n){const r=e.evaluationHistory,i=t!=n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"notEquals")},Ri={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,n){const r=e.evaluationHistory,i=t!==n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"strictNotEquals")},Li={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,"<");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"lessThan")},Mi={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,"<=");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"lessThanOrEqual")},Di={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,">");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"greaterThan")},Pi={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=wi(t,n,">=");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Ve(e,"greaterThanOrEqual")},qi={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,n){const r=Date.now();try{return Si(this,e,[t,n],t&&n,r)}catch(i){throw Si(this,e,[t,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:e=>Ve(e,"and"),inputSchema:Oi,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},Bi={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,n){const r=e.evaluationHistory,i=t||n;return r&&Si(this,e,[t,n],i,r?Date.now():0),i},validate:e=>Ve(e,"or")},Vi={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const n=e.evaluationHistory,r=!t;return n&&Si(this,e,[t],r,n?Date.now():0),r},validate:e=>Pe(e,1,"not","operand")},Fi={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let i;return i=null==t||(Se(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!Ce(t)||0!==Object.keys(t).length)),n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"isEmpty","value")},_i={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0;let i;return i=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:(Se(t),!1)),n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"no","value")},Hi={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=!await Fi.evaluate(e,t);return n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"isNotEmpty","value")},Ui={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=zi(t);return n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"exists","value")};function zi(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const Wi={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const n=e.evaluationHistory,r=n?Date.now():0,i=!zi(t);return n&&Si(this,e,[t],i,r),i},validate:e=>Pe(e,1,"doesNotExist","value")},Ji={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0;let s;if(t&&n){if(Ci(t)&&Ci(n))return s=t.contains(n),r&&Si(this,e,[t,n],s,i),s;if(Se(t)&&t.match(/^[.#][\w-]+$/)){const o=document.querySelector(t);if(o&&Ci(n))return s=o.contains(n),r&&Si(this,e,[t,n],s,i),s;if(o&&Se(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return s=!!a&&o.contains(a),r&&Si(this,e,[t,n],s,i),s}}if(Se(n)&&n.match(/^[.#][\w-]+$/)&&Ci(t)){const o=document.querySelector(n);return s=!!o&&t.contains(o),r&&Si(this,e,[t,n],s,i),s}}if(Se(t)&&Se(n))s=t.includes(n);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);s=e.includes(n)||n instanceof Node&&e.some(e=>e instanceof Node&&e.contains(n))}else s=!(!Ce(t)||!Se(n))&&n in t;return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"contains","container, value")},Zi={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=!await Ji.evaluate(e,t,n);return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"doesNotContain","container, value")},Ki={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=null!=t&&null!=n&&(t+"").startsWith(n+"");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"startsWith","str, prefix")},Xi={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=null!=t&&null!=n&&(t+"").endsWith(n+"");return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"endsWith","str, suffix")},Gi={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,n,r){const i=e.evaluationHistory;let s=n,o=r;if(null!=s&&null!=o&&s>o){const e=s;s=o,o=e}const a=null!=s&&null!=o&&t>=s&&o>=t;return i&&Si(this,e,[t,n,r],a,i?Date.now():0),a},validate:e=>Pe(e,3,"between","value, min, max")},Yi={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,n){const r=Date.now();try{let i;if(t instanceof Element&&Se(n)){const e=n;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{i=function(e,t){return di.matches(e,t)}(t,e)}catch(e){i=!1}else i=!1}else if(Se(t)&&Se(n)){const e=t,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(e)}catch(t){i=e.includes(r)}}else i=!1;return Si(this,e,[t,n],i,r)}catch(i){throw Si(this,e,[t,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:e=>Pe(e,2,"matches","element, selector"),inputSchema:Ni,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},Qi={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0;let s=!1;if(t instanceof Element&&Se(n)){const e=n;e.startsWith(".")?s=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(s=t.hasAttribute(e.slice(1,-1)))}return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"has","element, selector")},es={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,n){const r=e.evaluationHistory,i=r?Date.now():0,s=!await Qi.evaluate(e,t,n);return r&&Si(this,e,[t,n],s,i),s},validate:e=>Pe(e,2,"doesNotHave","element, selector")},ts={equals:ji,strictEquals:$i,notEquals:Ii,strictNotEquals:Ri,lessThan:Li,lessThanOrEqual:Mi,greaterThan:Di,greaterThanOrEqual:Pi,and:qi,or:Bi,not:Vi,no:_i,isEmpty:Fi,isNotEmpty:Hi,exists:Ui,doesNotExist:Wi,contains:Ji,doesNotContain:Zi,startsWith:Ki,endsWith:Xi,between:Gi,matches:Yi,has:Qi,doesNotHave:es},ns=Ye({value:Ke().describe("String literal value")}).strict(),rs=Ye({value:Xe().describe("Number literal value")}).strict(),is=Ye({value:Ge().describe("Boolean literal value")}).strict(),ss=Ye({left:et().describe("Left operand"),right:et().describe("Right operand")}).strict();const os={stringLiteral:new class extends rt{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=ns,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 s=this.success(i,"string");return this.trackSimple(e,n,!0,i),s}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)?(ae(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}},numberLiteral:new class extends rt{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=rs,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 rt{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=is,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);return r.isValid?(this.trackSimple(e,n,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(t){return this.trackSimple(e,n,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends rt{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=ss,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=yi(t.left,"left operand")+yi(t.right,"right operand");return this.trackSimple(e,n,!0,i),this.success(i,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends rt{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=ss,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=ss.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(Se(e))return e;if(Ae(e))return""+e;if(Te(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}},multiplication:new class extends rt{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=ss,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return this.trackSimple(e,n,!1),this.failure("ValidationError","validation-error",r.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=yi(t.left,"left operand")*yi(t.right,"right operand");return this.trackSimple(e,n,!0,i),this.success(i,"number")}catch(t){return this.trackSimple(e,n,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}},as={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},cs=Ye({collection:et().describe("Collection to operate on (array, NodeList, or string)")}).strict(),ls=Ye({collection:et().describe("Collection to access"),index:Xe().describe("Index position to access")}).strict(),us=Ye({collection:et().describe("Collection to select random item from")}).strict();new class extends rt{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=cs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),s=i.length>0?i[0]:void 0,o={success:!0,value:s,type:as[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=cs,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),s=i.length>0?i[i.length-1]:void 0,o={success:!0,value:s,type:as[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends rt{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=ls,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection),s=this.normalizeIndex(t.index,i.length),o=s>=0&&i.length>s?i[s]:void 0,a={success:!0,value:o,type:as[this.inferEvaluationType(o)]};return this.trackPerformance(e,t,a,n),a}catch(r){const i=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid at input: "+e.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(e,t){return 0>e?t+e:e}},new class extends rt{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=us,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const n=Date.now();try{const r=this.validate(t);if(!r.isValid)return{success:!1,error:r.errors[0]};const i=this.normalizeCollection(t.collection);if(0===i.length){const r={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,r,n),r}const s=i[this.getSecureRandomIndex(i.length)],o={success:!0,value:s,type:as[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,o,n),o}catch(r){const i=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,i,n),i}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid random input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(e){if("undefined"!=typeof crypto&&crypto.getRandomValues){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}return Math.floor(Math.random()*e)}};const fs={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:Se(n)?n.length>0?n[0]:null:Ce(n)&&"length"in n&&Ae(n.length)&&n.length>0?n[0]:null},validate:e=>_e(e,1,"first","collection")},ds={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 Se(n)?n.length>0?n[n.length-1]:null:Ce(n)&&"length"in n&&Ae(n.length)&&n.length>0?n[n.length-1]:null},validate:e=>_e(e,1,"last","collection")},hs={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[n,r]=t;if(!Ae(n))throw Error("Index must be a number");const i=n,s=void 0!==r?r:e.it;if(null==s)return null;if(Array.isArray(s)){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}if(s instanceof NodeList||s instanceof HTMLCollection){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}if(s instanceof Element){const e=s.children,t=0>i?e.length+i:i;return t>=0&&e.length>t?e[t]:null}if(Se(s)){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}if(Ce(s)&&"length"in s&&Ae(s.length)){const e=0>i?s.length+i:i;return e>=0&&s.length>e?s[e]:null}return null},validate:e=>He(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)};function ms(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?ms(r,t):null}function ps(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?ps(r,t):null}function ys(e,t,n,r){if(n.inSearch){if(null==n.inElt)return;return function(e,t,n,r){const i=Array.from(t??[]),s=[];for(const t of i)(t.matches&&t.matches(n)||t===e)&&s.push(t);for(let t=0;s.length-1>t;t++)if(s[t]===e)return s[t+1];if(r){const e=s[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 gs(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 vs={first:fs,last:ds,at:hs,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[n,r,i]=t,s=r||e.me;return s&&s instanceof Element?n?i?ys(s,n,i,!0):ms(s,n):s.nextElementSibling:null},validate:e=>_e(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,s=r||e.me;return s&&s instanceof Element?n?i?ys(s,n,i,!1):ps(s,n):s.previousElementSibling:null},validate:e=>_e(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,s=i||e.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=gs(e);for(const e of r)if(gs(e)>i)return e;return null}(s,n,o):null},validate:e=>He(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,s=i||e.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(e,t,n){const r=Array.from(n.querySelectorAll(t)),i=gs(e);for(let e=r.length-1;e>=0;e--){const t=r[e];if(i>gs(t))return t}return null}(s,n,o):null},validate:e=>He(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")}};class bs{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=yi(e,"left operand");return{success:!0,value:vi(r+yi(n,"right operand"),"addition"),type:"number"}}catch(e){return{success:!1,errors:[ki("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 xi([ki("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return xi([ki("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"),xi([ki("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 bi(n)?bi(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[ki("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[ki("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const ws={addition:new bs,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=yi(e,"left operand");return{success:!0,value:vi(r-yi(n,"right operand"),"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).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=yi(e,"left operand");return{success:!0,value:vi(r*yi(n,"right operand"),"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).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}(yi(e,"left operand"),yi(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).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}(yi(e,"left operand"),yi(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(e){return{success:!1,errors:[ki("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 bs).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=yi(e,"left operand"),i=yi(n,"right operand");return{success:!0,value:vi(Math.pow(r,i),"power"),type:"number"}}catch(e){return{success:!1,errors:[ki("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new bs).validate(e)}}};function Es(){return ai(ui,ts,yt,vs,wt,os,ws)}var xs=Object.freeze({__proto__:null,conversion:yt,conversionExpressions:yt,createCommonRegistry:function(){return ai(ui,ts,os,yt,vs)},createCoreRegistry:function(){return ai(ui,ts,os)},createExpressionRegistry:ai,createFullExpressionRegistry:Es,createFullRegistry:function(){return ai(ui,ts,os,yt,vs,wt)},logical:ts,logicalExpressions:ts,positional:vs,positionalExpressions:vs,properties:wt,propertiesExpressions:wt,references:ui,referencesExpressions:ui,special:os,specialExpressions:os});function ks(e,t,n,r,i,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),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");s.push(o(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=o(y.get))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&i.unshift(a)}else(a=o(y))&&("field"===c?i.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),d=!0}function Ss(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 As(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"==typeof SuppressedError&&SuppressedError;const Ts=Symbol("command:name"),Cs=Symbol("command:category"),Os=Symbol("command:metadata");function Ns(e){return function(t,n){const r=t;r[Ts]=e.name,r[Cs]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function js(e){return function(t,n){const r=t,i=r[Cs];if(!i)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const s={description:e.description,syntax:e.syntax,examples:e.examples,category:i,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};r[Os]=s,Object.defineProperty(t,"metadata",{value:s,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>s,enumerable:!0,configurable:!1})}}function $s(e){return()=>new e}function Is(e,t){return e?`[${e}] ${t}`:t}function Rs(e,t,n){if(ge(e))return e;if(!e){const e=t.me;if(!e)throw Error(Is(n,"No target element \u2014 provide explicit target or ensure context.me is set"));return Ms(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error(Is(n,'Context reference "me" is not available'));return Ms(t.me)}if("it"===r){if(!ge(t.it))throw Error(Is(n,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===r){if(!t.you)throw Error(Is(n,'Context reference "you" is not available'));return Ms(t.you)}const i=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw Error(Is(n,"DOM not available \u2014 cannot resolve element selector"));const s=i.querySelector(r);if(!s)throw Error(Is(n,"Element not found with selector: "+r));if(!ge(s))throw Error(Is(n,"Element found but is not an HTMLElement: "+r));return s}throw Error(Is(n,"Invalid target type: "+typeof e))}function Ls(e,t){if(Array.isArray(e))return e.filter(ge);if(ve(e))return Array.from(e).filter(ge);if(ge(e))return[e];if(!e){const e=t.me;return e&&ge(e)?[e]:[]}if("string"==typeof e){const n=e.trim();if("me"===n)return t.me&&ge(t.me)?[t.me]:[];if("it"===n)return ge(t.it)?[t.it]:[];if("you"===n)return t.you&&ge(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(ge)}}return[]}function Ms(e){if(ge(e))return e;throw Error("Value is not an HTMLElement")}function Ds(e,t,n){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(Is(n,'No "me" element in context'));if(!ge(t.me))throw Error(Is(n,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(Is(n,'No "it" value in context'));if(!ge(t.it))throw Error(Is(n,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(Is(n,'No "you" element in context'));if(!ge(t.you))throw Error(Is(n,"context.you is not an HTMLElement"));return t.you;default:throw Error(Is(n,"Unknown possessive: "+e))}}const Ps=["on","from","to","in","with","at"];async function qs(e,t,n,r,i={},s){let o=e;if(i.filterPrepositions&&e&&(o=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!Ps.includes(t.name.toLowerCase())})),(!o||0===o.length)&&i.fallbackModifierKey&&s){const e=s[i.fallbackModifierKey];e&&(o=[e])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!ge(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const e of o){const i=await t.evaluate(e,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(ge(i))a.push(i);else if(ve(i)){const e=Array.from(i).filter(ge);a.push(...e)}else if(Array.isArray(i)){const e=i.filter(ge);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),s=Array.from(r).filter(ge);a.push(...s)}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(!ge(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}class Bs{async parseInput(e,t,n){const{targets:r}=await async function(e,t,n,r){return{targets:await qs(e.args,t,n,r)}}(e,t,n,this.mode);return{targets:r,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>ge(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 Vs=(()=>{let e,t,n=[js({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Ns({name:"hide",category:"dom"})],r=[],i=Bs;return t=class extends i{constructor(){super(...arguments),this.mode="hide"}async execute(e,t){for(const t of e.targets)this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>ge(e))}},As(t,"HideCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Fs=$s(Vs);let _s=(()=>{let e,t,n=[js({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Ns({name:"show",category:"dom"})],r=[],i=Bs;return t=class extends i{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const n=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,n)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>ge(e))&&"string"==typeof t.defaultDisplay}},As(t,"ShowCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Hs=$s(_s);function Us(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function zs(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 Ws(e,t){for(const n of e)t(n);return e}function Js(e,t,n){for(const r of e)for(const e of t)n(r,e);return e}function Zs(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 Ks(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&&Gs(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&&Gs(e));const t=(e+"").trim(),n=t.startsWith(".")?t.substring(1):t;return n.length>0&&Gs(n)?[n]:[]}function Xs(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Gs(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Xs(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Ys(e,t){return e.map(e=>{if(Xs(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+"":(Xt(`Dynamic class variable '${n}' not found in context`),"")}return e}).filter(e=>e.length>0)}function Qs(e){return"string"==typeof e&&e.trim().startsWith("*")}function eo(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 to(e,t,n){e.style.setProperty(t,n)}const no=["dialog","details","summary","select"];function ro(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 io(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=ro(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=ro(e);return"string"==typeof n&&n.startsWith("*")}(e)?{value:ro(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=ro(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(r=e,"attributeAccess"===r.type?"@"+r.attributeName:ro(r)),extractedFromNode:!0}:{value:await t.evaluate(e,n),extractedFromNode:!1};var r}class so{async resolveTargets(e,t,n,r){return qs(e,t,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(e,t,n){return io(e,t,n)}parseClassNames(e){return Ks(e)}isAttribute(e){return Us(e.trim())}isCSSProperty(e){return Qs(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>ge(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 oo=(()=>{let e,t,n=[js({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"]}),Ns({name:"add",category:"dom"})],r=[],i=so;return t=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:s}=function(e){const t=zs(e);return{name:t.name,value:t.value??""}}(i);return{type:"attribute",name:r,value:s,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const s=await t.evaluate(e.args[1],n);return{type:"styles",styles:{[r]:s+""},targets:await this.resolveTargets(e.args.slice(2),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(e.args.slice(1),t,n,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const n=Ys(e.classes,t);n.length>0&&Js(e.targets,n,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":n=e.name,r=e.value,Ws(e.targets,e=>{e.setAttribute(n,r)});break;case"styles":!function(e,t){Js(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}},As(t,"AddCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const ao=$s(oo);function co(e){return!!e.parentNode&&(e.remove(),!0)}let lo=(()=>{let e,t,n=[js({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"]}),Ns({name:"remove",category:"dom"})],r=[],i=so;return t=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,n){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(e.args[0],t,n);if(ge(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&ge(r[0]))return{type:"element",targets:r.filter(e=>ge(e))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:zs(i).name,targets:await this.resolveTargets(e.args.slice(1),t,n,e.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),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(e.args.slice(1),t,n,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const n=Ys(e.classes,t);n.length>0&&Js(e.targets,n,(e,t)=>{e.classList.remove(t)});break}case"attribute":n=e.name,Ws(e.targets,e=>{e.removeAttribute(n)});break;case"styles":!function(e,t){Js(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)co(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}},As(t,"RemoveCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const uo=$s(lo);function fo(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 ho(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const n=fo(e);return n?n.milliseconds:t}return t}function mo(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=fo(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function po(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 yo(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 go(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function vo(e){return"DIALOG"===e.tagName}function bo(e){return"DETAILS"===e.tagName}function wo(e,t,n){return()=>{"class"===t?e.classList.toggle(n):"attribute"===t&&Zs(e,n)}}function Eo(e,t,n,r){const i=wo(e,t,n),s=setTimeout(i,r);return()=>{clearTimeout(s)}}function xo(e,t,n,r){const i=wo(e,t,n),s=()=>{i(),e.removeEventListener(r,s)};return e.addEventListener(r,s,{once:!0}),()=>{e.removeEventListener(r,s)}}function ko(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 So(e){return null==e||""===e}const Ao=/^the\s+(.+?)\s+of\s+(.+)$/i,To=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 Co(e){return"string"==typeof e&&Ao.test(e)}function Oo(e,t){const n=e.match(Ao);if(!n)return null;try{return{element:Rs(n[2].trim(),t),property:n[1].trim()}}catch{return null}}async function No(e,t,n){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,n){const r=e.property?.name;if(!r)return null;let i=await t.evaluate(e.target,n);return Array.isArray(i)&&(i=i[0]),ge(i)?{element:i,property:r}:null}(e,t,n);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,n){const r="string"==typeof e.property?e.property:e.property?.name;if(!r)return null;let i=await t.evaluate(e.object,n);return Array.isArray(i)&&(i=i[0]),ge(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 s=await t.evaluate(e,n);if(Array.isArray(s)&&(s=s[0]),!ge(s))return null;const o=i?.name||i?.value;return o?{element:s,property:o}:null}return null}function jo(e,t){const{element:n,property:r}=e;r.startsWith("*")?to(n,r.substring(1),t+""):ko(n,r,t)}async function $o(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?ho(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 Io(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 no.includes(t)}(t)}(t);if(ge(e)||Array.isArray(e)&&e.every(e=>ge(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 no.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const Ro=$s((()=>{let e,t,n=[js({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),Ns({name:"toggle",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(e){if(!e||"asExpression"!==e.type)return!1;const t=e.targetType,n="string"==typeof t?t:t?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(e.args[0])){r=!0;const t=e.args[0].expression;e={...e,args:[t,...e.args.slice(1)]}}const i=e.args[0],s=i?.name;if("between"===s&&e.args.length>=4){const{duration:r,untilEvent:i}=await $o(e.modifiers,t,n),s=async e=>{const r=e;return"selector"===r?.type?r.value:t.evaluate(e,n)},o=await s(e.args[1]),a=await s(e.args[3]),c=[];for(let t=4;e.args.length>t;t++){const n=e.args[t]?.name;"on"!==n&&"from"!==n&&c.push(e.args[t])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await qs(c,t,n,"toggle",l,e.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:i}}const o=await No(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,s=1;if("*"===r&&e.args.length>1&&"identifier"===e.args[1].type&&(r="*"+e.args[1].name,s=2),"*"===r&&e.modifiers?.on){const i=e.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:s,untilEvent:o}=await $o(e.modifiers,t,n),a=eo(r);if(a){const e=n.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:s,untilEvent:o}}}}const o=eo(r);if(o){const{duration:r,untilEvent:i}=await $o(e.modifiers,t,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await qs(e.args.slice(s),t,n,"toggle",a,e.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await $o(e.modifiers,t,n),{value:l}=await io(i,t,n);if(Co(l)){const e=Oo(l,n);if(e)return{type:"property",target:e}}const{type:u,expression:f}=Io(l,i),d={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:i}=zs(f);return{type:"attribute",name:r,value:i,targets:await qs(e.args.slice(1),t,n,"toggle",d,e.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=eo(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await qs(e.args.slice(1),t,n,"toggle",d,e.modifiers)}}case"element":{let s;if(ge(l))s=[l];else if(Array.isArray(l)&&l.every(e=>ge(e)))s=l;else if(f){const e=document.querySelectorAll(f);s=Array.from(e).filter(e=>ge(e))}else s=await qs([i],t,n,"toggle",d,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}}(s);if("dialog"===o){const i=r?"modal":await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await n.evaluate(e[1],r);if("string"==typeof t){const i=t.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&e.length>=3){const t=await n.evaluate(e[2],r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,n);return{type:"dialog",mode:i,targets:s}}return"details"===o?{type:"details",targets:go(s)}:"select"===o?{type:"select",targets:s}:{type:"classes",classes:Ks(f),targets:s,duration:a,untilEvent:c}}default:{const r=Ks(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await qs(e.args.slice(1),t,n,"toggle",d,e.modifiers),duration:a,untilEvent:c}}}}async execute(e,t){switch(e.type){case"classes":{const n=Ys(e.classes,t);if(0===n.length)return[...e.targets];if(Js(e.targets,n,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&n.length)for(const t of e.targets)e.duration&&Eo(t,"class",n[0],e.duration),e.untilEvent&&xo(t,"class",n[0],e.untilEvent);return[...e.targets]}case"attribute":if(n=e.name,r=e.value,Ws(e.targets,e=>{Zs(e,n,r)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Eo(t,"attribute",e.name,e.duration),e.untilEvent&&xo(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return Ws(e.targets,t=>function(e,t){const n=window.getComputedStyle(e);switch(t){case"display":"none"===n.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=n.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:n}=e;return n.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,n.substring(1)):Me(t,n)}(e),n=e.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof t||To.has(r)||To.has(r.toLowerCase())){const n=!t;return jo(e,n),n}if("number"==typeof t){const n=0===t?1:0;return jo(e,n),n}if("string"==typeof t){const r="__ht_"+n,i=e.element[r];return""===t&&void 0!==i?(jo(e,i),i):(e.element[r]=t,jo(e,""),"")}jo(e,!t)}(e.target),[e.target.element];case"dialog":return Ws(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 Ws(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return Ws(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&&Eo(t,"class",e.classA,e.duration),e.untilEvent&&xo(t,"class",e.classA,e.untilEvent);return[...e.targets]}var n,r}},As(t,"ToggleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());const Lo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"put",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("put requires arguments");const r=e=>e?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let s=-1,o=null;for(let t=0;e.args.length>t;t++){const n=e.args[t],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&i.includes(c)){s=t,o=c;break}}let a=null,c=null;if(-1===s){const t=i.find(t=>e.modifiers[t]);if(t)a=e.args[0],o=t,c=e.modifiers[t];else if(3>e.args.length){if(2>e.args.length)throw Error("put requires content and position");a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||"into"}else a=e.args[0],o=e.args[1]?.value||e.args[1]?.name||null,c=e.args[2]}else a=e.args.slice(0,s)[0]||null,c=e.args.slice(s+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await t.evaluate(a,n),u=this.mapPosition(o);let f,d,h=null;if(c){const e=r(c),i=await No(c,t,n);if(i)return{value:l,targets:[i.element],position:"replace",memberPath:i.property};if("memberExpression"===e){const e=c.object,r=c.property;if("selector"===e?.type)h=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:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===i||"it"===i){const e=await t.evaluate(c,n);"string"==typeof e&&(h=e)}else h=i}if(h&&r?.name)f=r.name;else if(!h&&!f){const e=await t.evaluate(c,n);"string"==typeof e&&(h=e)}}else if("identifier"===e&&"me"===c.name)h=null;else if("selector"===e||"cssSelector"===e)h=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&Co(e)){const t=Oo(e,n);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?h=e:d=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))h=e;else{const r=await t.evaluate(c,n),i=this.resolveEvaluatedAsElements(r);if(i)return{value:l,targets:i,position:u,memberPath:f};d=e}}else{const e=await t.evaluate(c,n),r=this.resolveEvaluatedAsElements(e);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?h=e:d=e)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(h,n),position:u,memberPath:f}}async execute(e,t){const{value:n,targets:r,position:i,memberPath:s,variableName:o}=e;if(o)return t.locals&&t.locals.set(o,n),t[o]=n,void Object.assign(t,{it:n});if(s)for(const e of r)this.setProperty(e,s,n);else for(const e of r){const t=this.parseValue(n);this.insertContent(e,t,i)}return r}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!ge(t.me))throw Error("put: no target and context.me is null");return[t.me]}const n=Array.from(document.querySelectorAll(e)).filter(e=>ge(e));if(!n.length)throw Error(`No elements: "${e}"`);return n}parseValue(e){return ge(e)?e:null==e?"":e+""}insertContent(e,t,n){if("replace"!==n)if(ge(t)){const r=t;switch(n){case"beforebegin":e.parentElement?.insertBefore(r,e);break;case"afterbegin":e.insertBefore(r,e.firstChild);break;case"beforeend":e.appendChild(r);break;case"afterend":e.parentElement?.insertBefore(r,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t);else ge(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(ge(e))return[e];if(Array.isArray(e)){const t=e.filter(ge);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(ge);return t.length>0?t:null}return null}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,n){const r=t.split(".");let 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}},As(t,"PutCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Mo={"&":"&","<":"<",">":">",'"':""","'":"'"};function Do(e){return e.replace(/[&<>"']/g,e=>Mo[e])}let Po=(()=>{let e,t,n=[js({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"]}),Ns({name:"make",category:"dom"})],r=[];return t=class{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 s="string"==typeof i&&i.startsWith("<")?i:await t.evaluate(r,n);if(null==s)throw Error("Make command requires class name or DOM element expression");"string"==typeof s&&s.startsWith("<")&&(s=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 kr(i[1].trim(),t);null!=n&&(e=Do(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:e})}let s=e;for(let e=r.length-1;e>=0;e--){const{index:t,length:n,text:i}=r[e];s=s.slice(0,t)+i+s.slice(t+n)}return s}(s,n));const o=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:o,expression:s,constructorArgs:a,variableName:c}}async execute(e,t){const{expression:n,constructorArgs:r=[],variableName:i}=e,s="string"==typeof n&&n.startsWith("<"),o=s&&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 s=document.createElement(n),o=r.split(/(?=[.#])/);for(const e of o)if(e.startsWith("#")){const t=e.slice(1);t&&(s.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&s.classList.add(t)}return s}(n):s&&/<\/[a-zA-Z]/.test(n)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content.firstElementChild;if(n&&ge(n))return n;const r=document.createElement("div");r.innerHTML=e.trim();const i=r.firstElementChild;return i&&ge(i)?i:r}(n):function(e,t,n){if(ge(e))return e;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:o}),i&&Ee(i,o,t),o}},As(t,"MakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const qo=$s(Po),Bo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"empty",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ge(e))}},As(t,"EmptyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Vo(e){return e.hasAttribute("popover")}const Fo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"open",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){const r=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const n=t.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=go(await qs(r,t,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)),s=await async function(e,t,n,r){if(t?.as){const e=await n.evaluate(t.as,r);if("string"==typeof e){const t=e.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}for(let t=0;e.length-1>t;t++){const 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:s}}async execute(e,t){for(const t of e.targets)if(vo(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(bo(t))t.open=!0;else if(Vo(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=>ge(e))||"modal"!==t.dialogMode&&"non-modal"!==t.dialogMode)}},As(t,"OpenCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function _o(e){return e.hasAttribute("popover")}const Ho=$s((()=>{let e,t,n=[js({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"]}),Ns({name:"close",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:go(await qs(e.args,t,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(vo(t))t.open&&t.close();else if(bo(t))t.open=!1;else if(_o(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=>ge(e))}},As(t,"CloseCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Uo(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const zo=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"select",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(Uo(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=>ge(e))}},As(t,"SelectCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Wo(e){return"FORM"===e.tagName}const Jo=$s((()=>{let e,t,n=[js({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"]}),Ns({name:"reset",category:"dom"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)Wo(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=>ge(e))}},As(t,"ResetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function Zo(e,t,n,r){return e?new Promise(n=>{const i=()=>{s({event:null,timedOut:!1,cancelled:!0})},s=Xo(()=>{e.removeEventListener(t,o),r&&r.removeEventListener("abort",i)},n),o=e=>{s({event:e,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,o),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function Ko(e){return new Promise(t=>setTimeout(t,e))}function Xo(e,t){let n=!1;return r=>{n||(n=!0,e(),t(r))}}const Go=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"wait",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,n);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n);const r=e.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,e.args[1],t,n):this.parseTimeWait(e.args[0],t,n)}async execute(e,t){const n=Date.now();if("time"===e.type)return await Ko(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-n};if("event"===e.type){const r=e.target??t.me??document,i=(await Zo(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:mo(await t.evaluate(e,n))}}async parseEventWait(e,t,n,r){const i=await n.evaluate(e,r);if("string"!=typeof i)throw Error("wait for: event name must be a string");const s=i.match(/^(\w+)\(([^)]+)\)$/),o=s?s[1]:i,a=s?s[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await n.evaluate(t,r);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(e,t,n,r){const i=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",n=[];for(const r of e.properties){const e=r.key?.name||r.key?.value;"name"===e&&r.value?t=r.value.value||"":"args"===e&&r.value?.elements&&(n=r.value.elements.map(e=>e.value||e.name||""))}t&&i.push({name:t,params:n})}}let s;if(t){const e=await n.evaluate(t,r);e&&"object"==typeof e&&"addEventListener"in e&&(s=e)}return s||(s=r.me??void 0),1===i.length?{type:"event",eventName:i[0].name,target:s,destructure:i[0].params.length>0?i[0].params:void 0}:{type:"race",conditions:i.map(e=>({type:"event",eventName:e.name,target:s,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,n){const r=[];e.modifiers.for?r.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,n)):e.args[0]&&r.push(await this.parseTimeWait(e.args[0],t,n));const i=await t.evaluate(e.modifiers.or,n),s=Array.isArray(i)?i:[i];for(const e of s)try{r.push({type:"time",milliseconds:mo(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);r.push(t?{type:"event",eventName:t[1],target:n.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(e,t){const n=new AbortController,r=n.signal,i=e.map(e=>"time"===e.type?Ko(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Zo(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()}}},As(t,"WaitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Yo=new Map;let Qo=[/^4\d{2}$/,/^5\d{2}$/],ea=(()=>{let e,t,n=[js({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),Ns({name:"fetch",category:"async"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(e.args[0],t,n),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:s}=e,o=new AbortController;let a;t.me&&(a=()=>o.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...s,signal:o.signal},l=Yo.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;s.timeout&&(u=setTimeout(()=>o.abort(),s.timeout));try{let s=await fetch(r,c);if(t.me){const e={response:s};this.dispatchEvent(t.me,"fetch:afterResponse",e),s=e.response}if(e.throwOnError&&function(e){const t=e+"";return Qo.some(e=>e.test(t))}(s.status)){const e=Error(`Fetch failed for ${r}: HTTP ${s.status} ${s.statusText}`.trim());throw e.response=s,e.isFetchStatusError=!0,e}const o=await this.handleResponse(s,i,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:o});const a={status:s.status,statusText:s.statusText,headers:s.headers,data:o,url:s.url,duration:Date.now()-n};return Object.assign(t,{it:o}),a}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+r);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${r}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,n){const r=await t.evaluate(e,n);if("string"!=typeof r||!r){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(Yo.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=Yo.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&&ge(n.firstChild)?n.firstChild:n}dispatchEvent(e,t,n){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0}))}},As(t,"FetchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const ta=$s(ea),na=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"set",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("set command requires a target");const r=e.args[0],i=r?.name||r?.value,s=r?.scope,o=r?.type;if(o){const i=ie(o);if(i)return{type:"node-write",node:r,value:await this.extractValue(e,t,n),writer:i}}const a=await this.resolveAttributeWriteTarget(r,e,t,n);if(a){const r=await this.extractValue(e,t,n);return{type:"attribute",elements:a.elements,name:a.name,value:r}}const c=await No(r,t,n);if(c){const r=await this.extractValue(e,t,n);if(c.property.startsWith("*")){const e=c.property.substring(1);return{type:"style",element:c.element,property:e,value:r+""}}return{type:"property",element:c.element,property:c.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,e,t,n);if(i)return i}let l;if(l="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(ge(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(l))return{type:"object-literal",properties:l,targets:await this.resolveTargets(e.modifiers.on,t,n)};if(Co(l)){const r=Oo(l,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(l,e,t,n)}if("string"==typeof l&&Qs(l)){const r=l.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 l&&Us(l)){const r=l.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 l){const r=l.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=Ds(r[1],n),s=await this.extractValue(e,t,n);return{type:"property",element:i,property:r[2],value:s}}}if(ge(l))return{type:"property",element:l,property:"textContent",value:await this.extractValue(e,t,n)};if(Array.isArray(l)&&l.length>0&&ge(l[0])){const r=await this.extractValue(e,t,n);return{type:"property",element:l[0],property:"textContent",value:r}}if("string"!=typeof l)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===l?"null":typeof l} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:l,value:await this.extractValue(e,t,n),scope:"element"===s||"global"===s?s:void 0}}async execute(e,t){switch(e.type){case"variable":return"element"===e.scope?me(t,e.name,e.value):"global"===e.scope?Ee(e.name,e.value,t,"global"):Ee(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 ko(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return to(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))ko(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 resolveAttributeWriteTarget(e,t,n,r){const i=e;if("attributeAccess"===i?.type)return{elements:await this.resolveTargets(t.modifiers.on,n,r),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const e=await this.evaluateToElement(i.right,n,r);if(e)return{elements:[e],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const e=await this.evaluateToElement(i.object,n,r);if(e)return{elements:[e],name:i.property.attributeName}}return null}async evaluateToElement(e,t,n){const r=await t.evaluate(e,n),i=Array.isArray(r)?r[0]:r;return ge(i)?i:null}async tryParseMemberExpression(e,t,n,r){const i=e.object,s=e.property;if(i?.name&&s?.name){const e=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const i=Ds(e,r),o=await this.extractValue(t,n,r);return{type:"property",element:i,property:s.name,value:o}}}const o=e.object,a=e.computed;if(o){const i=o;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(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const i=a?await n.evaluate(e.property,r)+"":s?.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.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(r>=0&&e.args.length>r+1)return t.evaluate(e.args[r+1],n);if(e.args.length>=2)return t.evaluate(e.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,n){return Rs(e?await t.evaluate(e,n):void 0,n)}async resolveTargets(e,t,n){return Ls(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[,s,o]=i,a=Rs(o,r),c=await this.extractValue(t,n,r);return{type:"property",element:a,property:s.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(ge)&&"value"in t;case"property":return"string"==typeof t.property&&ge(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&ge(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}}},As(t,"SetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),ra=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"get",category:"data"})],r=[];return t=class{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}},As(t,"GetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function ia(e){return e&&"object"==typeof e&&e.type||"unknown"}let sa=(()=>{let e,t,n=[js({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"]}),Ns({name:"increment",category:"data"})],r=[];return t=class{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 s,o,a;const c=ia(i);if("identifier"===c)s=i.name,i.scope&&(o=i.scope);else if("literal"===c)s=i.value;else{const e=ie(c);if(e){const r=await t.evaluate(i,n),o="number"==typeof r?r:null==r?0:Number(r)||0;s=o,a={node:i,writer:e,currentValue:o}}else{const e=await t.evaluate(i,n);s=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=o;for(let r=1;e.args.length>r;r++){const i=e.args[r];if(i&&"literal"===i.type){const e=i.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(i&&"literal"!==i.type){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"===ia(f)&&"number"==typeof e)l=e;else if("literal"!==ia(f)){const e=await t.evaluate(f,n);"number"==typeof e&&(l=e)}}return{target:s,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:s=1,operation:o="increment",customWrite:a}=e;if(a){const e=isFinite(s)?s:1,n="increment"===o?a.currentValue+e:a.currentValue-e;return await a.writer(a.node,n,t),Object.assign(t,{it:n}),n}const c=function(e,t,n,r){if("number"==typeof e)return e;if(ge(e)){const n=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?be(n.getAttribute(t)):be(n[t]):be(n.value||n.textContent)}return"string"==typeof e?"element"===n?be(we(e,r,"element")):"global"===n?be(we(e,r,"global")):e.includes(".")?function(e,t){const n=e.split("."),r=n[1],i=xe(n[0],t);return i?be(i[r]):0}(e,r):be("me"===e&&r.me?r.me.value||0:"it"===e?r.it||0:"you"===e&&r.you?r.you.value||0:we(e,r)):be(e)}(n,r,i,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(s)?s:1;l="increment"===o?c+e:c-e}return function(e,t,n,r,i){if(ge(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 Ee(e,r,i,"element");if("global"===n)return void Ee(e,r,i,"global");if(e.includes("."))return void function(e,t,n){const r=e.split("."),i=r[1],s=xe(r[0],n);s&&(s[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);Ee(e,r,i)}}(n,r,i,l,t),Object.assign(t,{it:l}),l}},As(t,"NumericModifyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const oa=$s(sa),aa=$s(sa),ca=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"default",category:"data"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("default command requires a target");const r=await t.evaluate(e.args[0],n);let i;if(e.modifiers?.to)i=await t.evaluate(e.modifiers.to,n);else{if(2>e.args.length)throw Error('default command requires a value (use "to <value>")');i=await t.evaluate(e.args[1],n)}return{target:r,value:i}}async execute(e,t){const{target:n,value:r}=e;if("string"==typeof n){if(n.startsWith("@"))return this.defaultAttribute(t,n.substring(1),r);const e=n.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,n,i]=e;return this.defaultElementProperty(t,n,i,r)}return this.defaultVariable(t,n,r)}if(ge(n))return this.defaultElementValue(t,n,r);throw Error("Invalid target type: "+typeof n)}defaultVariable(e,t,n){const r=we(t,e);return null!=r?{target:t,value:n,wasSet:!1,existingValue:r,targetType:"variable"}:(Ee(t,n,e),Object.assign(e,{it:n}),{target:t,value:n,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,n){if(!e.me)throw Error("No element context available for attribute default");const r=e.me.getAttribute(t);return null!==r?{target:"@"+t,value:n,wasSet:!1,existingValue:r,targetType:"attribute"}:(e.me.setAttribute(t,n+""),Object.assign(e,{it:n}),{target:"@"+t,value:n,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,n,r){const i=Ds(t,e,"default"),s=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]}(i,n),o=`${t} ${n}`;return So(s)?(ko(i,n,r),Object.assign(e,{it:r}),{target:o,value:r,wasSet:!0,targetType:"property"}):{target:o,value:r,wasSet:!1,existingValue:s,targetType:"property"}}defaultElementValue(e,t,n){const r=function(e){return"value"in e?e.value:e.textContent}(t);return So(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"}}},As(t,"DefaultCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function la(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const ua=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"clear",category:"data"})],r=[];return t=class{async parseInput(e,t,n){const r=e.args?.[0],i=r?.type,s=r?.name;if(r&&("variable"===i||"identifier"===i&&"string"==typeof s))try{const e=await t.evaluate(r,n);if(!ge(e)&&!Array.isArray(e))return{type:"variable",name:s}}catch{return{type:"variable",name:s}}return{type:"form-fields",targets:await qs(e.args,t,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return t.locals.set(e.name,null),void Object.assign(t,{it:null});for(const t of e.targets)la(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=>ge(e))}return!1}},As(t,"ClearCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function fa(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 da=(()=>{let e,t,n=[js({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),Ns({name:"trigger",category:"event"})],r=[];return t=class{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 s=e=>e?.type||"unknown",o=e.args[0];let a,c,l;if("functionCall"===s(o)||"callExpression"===s(o)){a=o.name||o.callee?.name;const e=o.args||o.arguments;e?.length&&(c=await this.parseEventDetail(e,t,n))}else if("identifier"===s(o)||"keyword"===s(o))a=o.name;else{const e=await t.evaluate(o,n);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,n,i);else{const r=e.args.findIndex((e,t)=>{if(0===t)return!1;const n=e.name||e.value;return"on"===n||"to"===n});if(-1!==r&&e.args.length-1>r){const s=e.args.slice(r+1),o=s.findIndex(e=>"with"===(e.name||e.value)),a=-1===o?s:s.slice(0,o);l=await this.resolveTargets(a,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.args,t,n),mode:r}}async execute(e,t){const n=function(e,t,n={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(n);t.it=n}async resolveTargets(e,t,n,r){const 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(ge(e))i.push(e);else if(e instanceof NodeList)i.push(...Array.from(e).filter(ge));else if(Array.isArray(e))i.push(...e.filter(ge));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(ge));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()]=fa(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},i=e.findIndex(e=>"with"===(e.name||e.value));if(-1===i)return r;for(const s of e.slice(i+1)){const e=await t.evaluate(s,n);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?r.bubbles=!0:"nobubbles"===t?r.bubbles=!1:"cancelable"===t?r.cancelable=!0:"nocancelable"===t?r.cancelable=!1:"composed"===t&&(r.composed=!0)}}return r}},As(t,"EventDispatchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const ha=$s(da),ma=$s(da),pa=$s((()=>{let e,t,n=[js({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),Ns({name:"go",category:"navigation"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{args:[]}}async execute(e,t){const{args:n}=e;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,t),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}findBareUrl(e){for(const t of e)if("to"!==t&&"the"!==t)return"string"==typeof t&&this.isBareUrl(t)?t:null;return null}async navigateToBareUrl(e,t){if(t.includes("new")&&t.includes("window")){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e));return e}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const n=e.findIndex(e=>"url"===e),r=e[n+1];if(!r)throw Error('URL is required after "url" keyword');const i="string"==typeof r?r:r+"",s=e.includes("new")&&e.includes("window");if(!this.isValidUrl(i))throw Error(`Invalid URL: "${i}"`);if(s){if("undefined"!=typeof window&&window.open){const e=window.open(i,"_blank");e?.focus&&e.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const n=this.parseScrollPosition(e),r=this.parseScrollTarget(e),i=this.parseScrollOffset(e),s=!e.includes("instantly"),o=this.resolveScrollTarget(r,t);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const e=s?"smooth":"instant",t=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){o.scrollIntoView?.({behavior:e,block:t,inline:r});const{x:s,y:a}=this.calculateScrollPosition(o,n,i);window.scrollTo?.({left:s,top:a,behavior:e})}else o.scrollIntoView?.({behavior:e,block:t,inline:r})}return o}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,s=!1;for(const o of e)"string"==typeof o&&(n.includes(o)?(t.vertical=o,i=!0):r.includes(o)&&(t.horizontal=o,s=!0));return s&&!i&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let n=e[t+1];return"the"===n&&e.length>t+2&&(n=e[t+2]),n}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!n.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const n=e[t];if("string"==typeof n){const e=n.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===n||"-"===n)&&e.length>t+1){const r=e[t+1],i="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const n="string"==typeof e?e:e+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&ge(t.me))return t.me;if("it"===n&&ge(t.it))return t.it;if("you"===n&&ge(t.you))return t.you;const r=we(n,t);if(ge(r))return r;if("undefined"!=typeof document)try{const e=document.querySelector(n);if(e)return e}catch{try{const e=document.getElementsByTagName(n);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,n){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const r=e.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,s=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=i,l=s;switch(t.horizontal){case"left":c=r.left+i;break;case"center":c=r.left+i+r.width/2-o/2;break;case"right":c=r.right+i-o}switch(t.vertical){case"top":l=r.top+s+n;break;case"middle":l=r.top+s+r.height/2-a/2+n;break;case"bottom":l=r.bottom+s-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}},As(t,"GoCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());function ya(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=we(e,t);return void 0!==n?!!n:!!e}return!!e}const ga=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"if",category:"control-flow"})],r=[];return t=class{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,s;if("unless"===r){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");i=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(i=e.args[1],s=3>e.args.length?void 0:e.args[2]):e.modifiers?.then&&(i=e.modifiers.then,s=e.modifiers.else),!i)throw Error('if command requires "then" branch with commands');return{mode:r,condition:await t.evaluate(e.args[0],n),thenCommands:i,elseCommands:s}}async execute(e,t){const{mode:n,condition:r,thenCommands:i,elseCommands:s}=e,o=ya(r,t);let a,c;return("unless"===n?!o:o)?(a="then",c=await this.executeCommandsOrBlock(i,t),"unless"===n&&Object.assign(t,{it:c})):s&&"if"===n?(a="else",c=await this.executeCommandsOrBlock(s,t)):a="none",{mode:n,conditionResult:o,executedBranch:a,result:c}}async executeCommandsOrBlock(e,t){return"block"===e?.type?this.executeBlock(e,t):Array.isArray(e)?this.executeCommands(e,t):e}async executeBlock(e,t){const n=t.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let r;if(e.commands?.length)for(const i of e.commands)r=await n(i,t);return r}async executeCommands(e,t){let n;for(const r of e)n=r?.execute?await r.execute(t):"function"==typeof r?await r():r;return n}},As(t,"ConditionalCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),va=ga,ba=ga;let wa=(()=>{let e,t,n=[js({description:"Iteration in hyperscript - for-in, counted, conditional, event-driven, and infinite loops",syntax:["repeat for <var> in <collection> { <commands> }","repeat <count> times { <commands> }","repeat while <condition> { <commands> }","repeat until <condition> { <commands> }","repeat forever { <commands> }"],examples:["repeat for item in items { log item }",'repeat 5 times { log "hello" }'],sideEffects:["iteration","conditional-execution"]}),Ns({name:"repeat",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){let r;if(e.modifiers?.index){const i=await t.evaluate(e.modifiers.index,n);"string"==typeof i&&(r=i)}let i,s=e.modifiers?.block||e.modifiers?.commands;if(!s){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(r),2===t.length))break}2===t.length?(s=t[0],i=t[1]):1===t.length&&(s=t[0])}const o=e.args[0],a="identifier"===o?.type?o.name:null,c=!!e.modifiers?.bottomTested&&await t.evaluate(e.modifiers.bottomTested,n);if("for"===a||e.modifiers?.for){const o=e.args[1],a=o?.value||o?.name,c=e.args[2]?await t.evaluate(e.args[2],n):void 0;if(!a||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:a,collection:Array.isArray(c)?c:[c],indexVariable:r,commands:s,elseCommands:i}}if("times"===a||e.modifiers?.times){const o=e.args[1],a=o?await t.evaluate(o,n):void 0,c="number"==typeof a?a:parseInt(a+"",10);if(isNaN(c))throw Error("times loops require a count number");return{type:"times",count:c,indexVariable:r,commands:s,elseCommands:i}}if("while"===a||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw Error("while loops require a condition");return{type:"while",condition:t,indexVariable:r,commands:s,elseCommands:i,bottomTested:c}}if("until"===a&&e.modifiers?.from||"until-event"===a){const o=e.args[1],a=o?.value||o?.name;if(!a)throw Error("until-event loops require an event name");let c=n.me;if(e.args[2]){const r=e.args[2];if("identifier"===r?.type&&"document"===r.name)c=document;else if("identifier"===r?.type&&"window"===r.name&&"undefined"!=typeof window)c=window;else{const r=await t.evaluate(e.args[2],n);r instanceof EventTarget?c=r:"document"===r?c=document:"undefined"!=typeof window&&r===window&&(c=window)}}return{type:"until-event",eventName:a,eventTarget:c,indexVariable:r,commands:s,elseCommands:i}}if("until"===a||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw Error("until loops require a condition");return{type:"until",condition:t,indexVariable:r,commands:s,elseCommands:i,bottomTested:c}}if("forever"===a||e.modifiers?.forever)return{type:"forever",indexVariable:r,commands:s,elseCommands:i};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:n,variable:r,collection:i,condition:s,count:o,indexVariable:a,commands:c,elseCommands:l,bottomTested:u,eventName:f,eventTarget:d}=e;let h,m;switch(n){case"for":({config:h,iterCtx:m}=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}}}(i,r,a));break;case"times":({config:h,iterCtx:m}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(o,a));break;case"while":({config:h,iterCtx:m}=function(e,t,n,r){return{config:{type:"while",shouldContinue:()=>t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(s,ya,t,a));break;case"until":({config:h,iterCtx:m}=function(e,t,n,r){return{config:{type:"until",shouldContinue:()=>!t(e,n)},iterCtx:{index:0,conditionExpr:e,indexVariable:r}}}(s,ya,t,a));break;case"until-event":({config:h,iterCtx:m}=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}}(f,d,a));break;case"forever":({config:h,iterCtx:m}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(a));break;default:throw Error("Unknown repeat type: "+n)}if(u){const e=h.shouldContinue;h.shouldContinue=async t=>0===t.index||await e(t)}try{const e=await async function(e,t,n,r,i){const s=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(;s>a&&await e.shouldContinue(r);){e.beforeIteration&&await e.beforeIteration(r,n),r.indexVariable&&n.locals&&n.locals.set(r.indexVariable,a);try{o=await i(t,n)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){c=!0;break}if(t.message.includes("CONTINUE")){a++,r.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}a++,r.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!r.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:a,lastResult:o,interrupted:c}}(h,c,t,m,this.executeCommands.bind(this));if(0===e.iterations&&!e.interrupted&&l){const e=await this.executeCommands(l,t);return Object.assign(t,{it:e}),{type:n,iterations:0,completed:!0,lastResult:e}}return Object.assign(t,{it:e.lastResult}),{type:n,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:n,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const n=e,r=t.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let i;if(n.commands)for(const e of n.commands)i=await r(e,t);return i}if(Array.isArray(e)){let n;for(const r of e)n="function"==typeof r?await r(t):r&&"function"==typeof r.execute?await r.execute(t):r;return n}return"function"==typeof e?await e(t):e}},As(t,"RepeatCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const Ea=$s(wa);class xa{async parseInput(e,t,n){return{signalType:this.signalType}}async execute(e,t){const n=Error(this.errorMessage);throw n[this.errorFlag]=!0,"exit"===this.signalType&&(n.returnValue=void 0,n.timestamp=Date.now()),n}}let ka=(()=>{let e,t,n=[js({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"]}),Ns({name:"break",category:"control-flow"})],r=[],i=xa;return t=class extends i{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},As(t,"BreakCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Sa=$s(ka);let Aa=(()=>{let e,t,n=[js({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"]}),Ns({name:"continue",category:"control-flow"})],r=[],i=xa;return t=class extends i{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},As(t,"ContinueCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const Ta=$s(Aa),Ca=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"halt",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(e.args&&e.args.length>0){const r=e.args[0];return!r||"the"!==r.name&&"the"!==r.value?{target:await t.evaluate(e.args[0],n)}:{target:n.event}}return{}}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}}"halted"in t&&(t.halted=!0);const r=Error("HALT_EXECUTION");throw r.isHalt=!0,r}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},As(t,"HaltCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Oa=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"return",category:"control-flow"})],r=[];return t=class{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;"returnValue"in t&&(t.returnValue=n),Object.assign(t,{it:n});const r=Error("RETURN_VALUE");throw r.isReturn=!0,r.returnValue=n,r}},As(t,"ReturnCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());let Na=(()=>{let e,t,n=[js({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"]}),Ns({name:"exit",category:"control-flow"})],r=[],i=xa;return t=class extends i{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},As(t,"ExitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:s},null,r),t=e.value,s&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),Ss(t,r)})(),t})();const ja=$s(Na),$a=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"throw",category:"control-flow"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],n)}}async execute(e,t){const{message:n}=e;let r;throw r=n instanceof Error?n:Error("string"==typeof n?n:n+""),r}},As(t,"ThrowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ia=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"call",category:"execution"})],r=[];return t=class{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 br(n,t);let s,o,a=!1;return"function"==typeof i?(o="function",s=i(),s instanceof Promise&&(a=!0,s=await s)):i instanceof Promise?(o="promise",a=!0,s=await i):(o="value",s=i),Object.assign(t,{it:s,result:s}),{result:s,wasAsync:a,expressionType:o}}},As(t,"CallCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());class Ra{constructor(){this.name="pseudo-command"}get metadata(){return Ra.metadata}async parseInput(e,t,n){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const r=e.args[0].properties||[];let i,s,o="",a=[];for(const e of r){const r=e.value;switch(e.key?.name||e.key?.value){case"methodName":o=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":s=await t.evaluate(r,n)}}if(!o)throw Error("pseudo-command requires method name");if(null==s)throw Error("pseudo-command requires a target expression");return{methodName:o,methodArgs:a,preposition:i,targetExpression:s}}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 s,o;const a=["from","on","with","into","at","to"];for(const r of a)if(e.modifiers?.[r]){o=r,s=await t.evaluate(e.modifiers[r],n);break}if(s||3>e.args.length||(s=await t.evaluate(e.args[2],n)),!s)throw Error("pseudo-command requires a target expression");return{methodName:r,methodArgs:i,preposition:o,targetExpression:s}}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 s=this.resolveMethod(e,n);if(!s)throw Error(`Method "${n}" not found on target object`);if("function"!=typeof s)throw Error(`"${n}" is not a function (it's a ${typeof s})`);const o=await this.executeMethod(s,e,r);return t.locals.set("result",o),Object.assign(t,{it:o}),{result:o,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+""))}}}Ra.metadata={description:"Treat a method on an object as a top-level command",syntax:["<method>(<args>) [(to|on|with|into|from|at)] <expression>"],examples:['getElementById("d1") from the document',"reload() the location of the window",'setAttribute("foo", "bar") on me',"foo() on me"],category:"execution",sideEffects:["method-execution"]};const La=$s((()=>{let e,t,n=[js({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"]}),Ns({name:"focus",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ge(e))}},As(t,"FocusCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ma=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"blur",category:"execution"})],r=[];return t=class{async parseInput(e,t,n){return{targets:await qs(e.args,t,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>ge(e))}},As(t,"BlurCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Da=$s((()=>{let e,t,n=[js({description:"Add content to the end of a string, array, or HTML element",syntax:["append <content>","append <content> to <target>"],examples:['append "Hello"','append "World" to greeting',"append item to myArray",'append "<p>New</p>" to #content'],sideEffects:["data-mutation","dom-mutation"]}),Ns({name:"append",category:"content"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("append requires content");const r=await t.evaluate(e.args[0],n);let i;if(e.modifiers?.to){const r=e.modifiers.to,s=r.type;i="identifier"!==s&&"variable"!==s&&"symbol"!==s||"string"!=typeof r.name?await t.evaluate(e.modifiers.to,n):r.name}else e.target&&(i=e.target);return{content:r,target:i}}async execute(e,t){const{content:n,target:r}=e,i=n+"";if(!r)return Object.assign(t,void 0===t.it?{it:i}:{it:t.it+""+i}),{result:t.it,targetType:"result"};if("string"==typeof r){if(r.startsWith("#")||r.startsWith(".")||r.includes("[")){const e=this.resolveDOMElement(r);return e.innerHTML+=i,{result:e,targetType:"element",target:e}}if("me"===r||"it"===r||"you"===r){const e=this.resolveContextRef(r,t);if(ge(e))return e.innerHTML+=i,{result:e,targetType:"element",target:e}}const e=we(r,t);if(void 0!==e){if(ge(e))return e.innerHTML+=i,{result:e,targetType:"element",target:e};if(Array.isArray(e))return e.push(n),{result:e,targetType:"array",target:r};const s=(null==e?"":e+"")+i;return Ee(r,s,t),{result:s,targetType:"variable",target:r}}return Ee(r,i,t),{result:i,targetType:"variable",target:r}}if(Array.isArray(r))return r.push(n),{result:r,targetType:"array"};if(ge(r))return r.innerHTML+=i,{result:r,targetType:"element",target:r};{const e=r+""+i;return Object.assign(t,{it:e}),{result:e,targetType:"string"}}}resolveDOMElement(e){if("undefined"==typeof document)throw Error("DOM not available");const t=document.querySelector(e);if(!t)throw Error("Element not found: "+e);return t}resolveContextRef(e,t){switch(e){case"me":return t.me;case"it":return t.it;case"you":return t.you;default:throw Error("Unknown context ref: "+e)}}},As(t,"AppendCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Pa=$s((()=>{let e,t,n=[js({description:"Animate CSS properties using CSS transitions",syntax:"transition <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"]}),Ns({name:"transition",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){if(!e.args?.length)throw Error("transition requires property and value");let r,i;const s=await t.evaluate(e.args[0],n);if(ge(s)||"string"==typeof s&&/^[#.]|^(?:me|it|you)$/.test(s)?(i=s,r=await t.evaluate(e.args[1],n)+""):r=s+"",!r)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let o=await t.evaluate(e.modifiers.to,n);void 0===o&&"identifier"===e.modifiers.to.type&&(o=e.modifiers.to.name);const a={property:r,value:o};return void 0!==i&&(a.target=i),e.modifiers?.over&&(a.duration=await t.evaluate(e.modifiers.over,n)),e.modifiers?.with&&(a.timingFunction=await t.evaluate(e.modifiers.with,n)+""),a}async execute(e,t){let{property:n}=e;const{target:r,value:i,duration:s,timingFunction:o}=e;n.startsWith("*")&&(n=n.substring(1)),n=n.replace(/([A-Z])/g,"-$1").toLowerCase();const a=Rs(r,t,"transition"),c=ho(s,300),l=getComputedStyle(a).getPropertyValue(n),u=a.style.transition,f=`${n} ${c}ms ${o||"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&&o({completed:!0,cancelled:!1})},s=n=>{n.target===e&&n.propertyName===t&&o({completed:!1,cancelled:!0})},o=Xo(()=>{e.removeEventListener("transitionend",i),e.removeEventListener("transitioncancel",s),clearTimeout(a)},r);e.addEventListener("transitionend",i),e.addEventListener("transitioncancel",s);const a=setTimeout(()=>{o({completed:!0,cancelled:!1})},n+50)})}(a,n,c);return a.style.transition=u,h&&a.style.removeProperty(n),Object.assign(t,{it:a}),{element:a,property:n,fromValue:l,toValue:d,duration:c,completed:m.completed}}},As(t,"TransitionCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),qa=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"measure",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){let r,i,s;if(e.args?.length){const s=e.args[0];if("identifier"===s.type&&s.name){const o=s.name.toLowerCase();if("me"===o||"it"===o||"you"===o){const o=await t.evaluate(s,n);if(ge(o)&&(r=o,e.args.length>1)){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else i=s.name}else{const o=await t.evaluate(s,n);if(ge(o)||"string"==typeof o&&/^[#.]/.test(o)){if(r=o,e.args.length>1){const r=e.args[1];i="identifier"===r.type?r.name:await t.evaluate(r,n)+""}}else"string"==typeof o&&(i=o)}}e.modifiers?.set&&(s=await t.evaluate(e.modifiers.set,n)+"");const o={};return void 0!==r&&(o.target=r),void 0!==i&&(o.property=i),void 0!==s&&(o.variable=s),o}async execute(e,t){const n=Rs(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(),s={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(s[r])return{value:s[r](),unit:"px"};const o=n.getPropertyValue(t),a=parseFloat(o);if(!isNaN(a)){const e=o.match(/([a-zA-Z%]+)$/);return{value:a,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},As(t,"MeasureCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ba=$s((()=>{let e,t,n=[js({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),Ns({name:"settle",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){let r,i;if(e.args&&e.args.length>0){const i=await t.evaluate(e.args[0],n);(ge(i)||"string"==typeof i&&(i.startsWith("#")||i.startsWith(".")||"me"===i||"it"===i||"you"===i))&&(r=i)}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=Rs(n,t,"settle"),s=ho(r,5e3),o=Date.now(),a=getComputedStyle(i),c=po(a.transitionDuration),l=po(a.transitionDelay),u=po(a.animationDuration),f=po(a.animationDelay),d=yo(c,l),h=yo(u,f),m=Math.max(d,h),p=await(y=i,g=m,v=s,g>0?new Promise(e=>{const t=e=>{e.target===y&&r({completed:!0,type:"transition"})},n=e=>{e.target===y&&r({completed:!0,type:"animation"})},r=Xo(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",n),clearTimeout(i),clearTimeout(s)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",n);const i=setTimeout(()=>{r({completed:!0,type:"timeout"})},g+50),s=setTimeout(()=>{r({completed:!1,type:"timeout"})},v)}):Promise.resolve({completed:!0,type:"timeout"}));var y,g,v;const b=Date.now()-o;return Object.assign(t,{it:i}),{element:i,settled:p.completed,timeout:s,duration:b}}},As(t,"SettleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());const Va=$s((()=>{let e,t,n=[js({description:"Move classes, attributes, and properties from one element to another",syntax:["take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"]}),Ns({name:"take",category:"animation"})],r=[];return t=class{async parseInput(e,t,n){if(3>e.args.length)throw Error('take requires property, "from", and source');const r=await t.evaluate(e.args[0],n)+"";if("from"!==await t.evaluate(e.args[1],n))throw Error("take syntax: take <property> from <source>");const i=await t.evaluate(e.args[2],n);let s;if(8>e.args.length)e.args.length>3&&(s=await t.evaluate(e.args[3],n));else{const r=await Promise.all([3,4,5,6].map(r=>t.evaluate(e.args[r],n)));"and"===r[0]&&"put"===r[1]&&"it"===r[2]&&"on"===r[3]&&e.args[7]&&(s=await t.evaluate(e.args[7],n))}return!s&&e.modifiers?.on&&(s=await t.evaluate(e.modifiers.on,n)),{property:r,source:i,target:s}}async execute(e,t){const n=Rs(e.source,t,"take"),r=Rs(e.target?e.target:void 0,t,"take"),i=this.takeProperty(n,e.property);return this.putProperty(r,e.property,i),{targetElement:r,property:e.property,value:i}}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 s=e.getAttribute(t);return null!==s?(e.removeAttribute(t),s):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 s=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());r.includes("-")||s in e.style||r in e.style?s in e.style?e.style[s]=n+"":r in e.style?e.style[r]=n+"":e.style.setProperty(r,n+""):e.setAttribute(t,n+"")}},As(t,"TakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Fa=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"js",category:"advanced"})],r=[];return t=class{async parseInput(e,t,n){let r,i;if(0===e.args.length)throw Error("js command requires JavaScript code");const s=e.args[0],o=e.args[1];if(s&&"literal"===s.type&&"string"==typeof s.value)r=s.value;else{if(!s||void 0===s.value)throw Error("js command requires JavaScript code");r=s.value+""}o&&"arrayLiteral"===o.type&&Array.isArray(o.elements)&&(i=o.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),s=await i(...Object.values(e));return void 0!==s&&Object.assign(t,{it:s}),{result:s,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},{})}}},As(t,"JsCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),_a=$s((()=>{let e,t,n=[js({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),Ns({name:"async",category:"advanced"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:n}=e,r=Date.now();try{const e=await this.executeCommandsAsync(t,n),i=Date.now()-r;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:n.length,results:e,executed:!0,duration:i}}catch(e){throw Error("Async command execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}async executeCommandsAsync(e,t){const n=[];for(let r=0;t.length>r;r++){const i=t[r];try{const t=await this.executeCommand(i,e);n.push(t),Object.assign(e,{it:t})}catch(e){const n=this.getCommandName(i);throw Error(`Command '${n}' (${r+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return n}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"execute"in e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},As(t,"AsyncCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ha=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"log",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,n)))}:{values:[]}}async execute(e,t){const n="undefined"!=typeof window?window.console:console;0===e.values.length?n.log():n.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},As(t,"LogCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ua=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"tell",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],n),commands:e.args.slice(1)}}async execute(e,t){const{target:n,commands:r}=e,i=Ls(n,t);if(0===i.length)throw Error("tell command found no target elements");const s=t.locals.get("_runtimeExecute"),o=[];for(const e of i){const n={...t,me:e,you:e};for(const e of r)try{const t=await this.executeCommand(e,n,s);o.push(t),Object.assign(n,{it:t})}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}}return{targetElements:i,commandResults:o,executionCount:i.length*r.length}}async executeCommand(e,t,n){if(e&&"object"==typeof e&&"command"===e.type&&n)return await n(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}},As(t,"TellCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());let za=(()=>{let e,t,n=[js({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"]}),Ns({name:"copy",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){if(1>e.args.length)throw Error("copy command requires a source (text or element)");const r=await t.evaluate(e.args[0],n);let i="text";if(e.modifiers?.format){const r=await t.evaluate(e.modifiers.format,n);"html"!==r&&"text"!==r||(i=r)}return{source:r,format:i}}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(ge(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===n.me&&ge(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(ge(e.me)){const r=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!1});e.me.dispatchEvent(r)}}},As(t,"CopyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})();const Wa=$s(za);const Ja=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"pick",category:"utility"})],r=[];return t=class{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),s=await t.evaluate(e.modifiers.count,n);if(!Array.isArray(r))throw Error(`pick ${i}: source must be an array, got ${typeof r}`);if("number"!=typeof s||!Number.isFinite(s))throw Error(`pick ${i}: count must be a number, got ${typeof s}`);return{variant:i,array:r,count:s}}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,s="start"===i?.value?"start":await t.evaluate(e.modifiers.rangeStart,n),o="start"===s?"start":Number(s);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:o,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 s=await t.evaluate(e.modifiers.regex,n),o="string"==typeof s?s:s+"",a=e.modifiers.flags,c=a?.value;return{variant:i,source:r,regex:o,flags:c}}if(e.modifiers?.from){const r=await t.evaluate(e.modifiers.from,n);if(!Array.isArray(r))throw Error("pick from requires an array");if(0===r.length)throw Error("Cannot pick from empty array");return{variant:"random",array:r}}if(0===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 s=n.slice(r,i);return Object.assign(t,{it:s}),{selectedItem:s,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),s=Array.from(n.matchAll(i));return Object.assign(t,{it:s}),{selectedItem:s,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(),s=[];for(let t=0;e.count>t&&i.length>0;t++){const e=Math.floor(Math.random()*i.length);s.push(i.splice(e,1)[0])}return Object.assign(t,{it:s}),{selectedItem:s,sourceLength:r.length,sourceType:e.items?"items":"array",variant:"random"}}},As(t,"PickCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());const Za=$s((()=>{let e,t,n=[js({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"]}),Ns({name:"beep",category:"utility"})],r=[];return t=class{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":ge(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(ge(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+""}},As(t,"BeepCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})()),Ka=$s((()=>{let e,t,n=[js({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"]}),Ns({name:"breakpoint",category:"utility"})],r=[];return t=class{async parseInput(e,t,n){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}},As(t,"BreakpointCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ks(null,e={value:t},n,{kind:"class",name:t.name,metadata:i},null,r),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),Ss(t,r)})(),t})());class Xa{constructor(){this.name="install"}get metadata(){return Xa.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,s,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}"`);if(e.args.length>=2){const r=await t.evaluate(e.args[1],n);if(r&&"object"==typeof r&&!Array.isArray(r)){s=r;for(const e of Object.keys(s))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(o=await t.evaluate(e.modifiers.on,n)),{behaviorName:i,parameters:s,target:o}}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 s=[];for(const i of e){const e=await this.installBehavior(n,i,r,t);s.push(e)}return{success:!0,behaviorName:n,installedCount:s.length,instances:s}}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(ge(e))return[e];throw Error('No target specified and "me" is not available in context')}if(ge(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>ge(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(ge(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=>ge(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=>ge(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(ge(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")}}Xa.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};class Ga{constructor(){this.name="render"}get metadata(){return Ga.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(e.args.length>=3&&"with"===await t.evaluate(e.args[1],n)){const r=await t.evaluate(e.args[2],n);r&&"object"==typeof r&&(i=r)}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),s=this.createTemplateContext(t,r),o=[],a=await this.processTemplate(i,s,o),c=this.createDOMElement(a);return Object.assign(t,{it:c}),{element:c,rendered:a,directivesProcessed:o}}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 s=0;for(;r.length>s;){const e=r[s].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:o}=await this.processRepeatDirective(r,s,t);i.push(o),s=e,n.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:o}=await this.processIfDirective(r,s,t,n);i.push(o),s=e,n.push("@if")}else if("@else"===e||"@end"===e)s++;else{const n=this.processVariableInterpolation(e,t);i.push(n),s++}}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 s=this.evaluateExpression(i[1],n),{endIndex:o,blockContent:a}=this.extractDirectiveBlock(e,t+1),c=[];if(Array.isArray(s))for(const e of s){const t={...n,locals:new Map([...n.locals.entries(),["it",e]])},r=await this.processTemplate(a.join("\n"),t,[]);c.push(r)}return{nextIndex:o+1,rendered:c.join("\n")}}async processIfDirective(e,t,n,r){const i=e[t].trim(),s=i.match(/^@if\s+(.+)$/);if(!s)throw Error("Invalid @if syntax: "+i);const o=!!this.evaluateExpression(s[1],n),{endIndex:a,blockContent:c,elseContent:l}=this.extractIfElseBlock(e,t+1);let u="";return o?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,s=t,o=!1;for(;e.length>s&&i>0;){const t=e[s].trim();if(t.startsWith("@if "))i++;else{if("@else"===t&&1===i){o=!0,s++;continue}if("@end"===t&&(i--,0===i))break}o?r.push(e[s]):n.push(e[s]),s++}return{endIndex:s,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 Xt(`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:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Ya(){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>')}Ga.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};const Qa=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],ec=function(e,t){const n=new Gr(null);for(const t of e)n.register(t);return new oi({registry:n,expressionRegistry:t.expressionRegistry,enableAsyncCommands:t.enableAsyncCommands??!0,commandTimeout:t.commandTimeout??1e4,enableErrorReporting:t.enableErrorReporting??!0,enableResultPattern:t.enableResultPattern??!0})}([Fs(),Hs(),ao(),uo(),Ro(),Lo(),qo(),Bo(),Fo(),Ho(),zo(),Jo(),Go(),ta(),na(),ra(),oa(),aa(),ca(),ua(),ha(),ma(),pa(),va(),Ea(),Sa(),Ta(),Ca(),Oa(),ja(),ba(),$a(),Ia(),new Ra,La(),Ma(),Da(),Pa(),qa(),Ba(),Va(),Fa(),_a(),Ha(),Ua(),Wa(),Ja(),Za(),Ka(),new Xa,new Ga],{expressionRegistry:Es()}),tc={async execute(e,t,n){const r=Ya(),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 s=r.buildAST(i.node),o=ye(n);return ec.execute(s.ast,o)},parse(e,t){const n=Ya(),r=n.parseSemantic(e,t);return.5>r.confidence||!r.node?null:n.buildAST(r.node).ast},translate:(e,t,n)=>Ya().translate(e,t,n),getAllTranslations:(e,t)=>Ya().getAllTranslations(e,t),createContext:pe,runtime:ec,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","transition","measure","settle","take","js","async","log","tell","copy","pick","beep","install","render"],supportedLanguages:Qa,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await sc():e instanceof HTMLElement&&await ic(e)},process:async e=>tc.processNode(e)},nc=new WeakSet;let rc=null;async function ic(e){if(nc.has(e))return;const t=e.getAttribute("_");if(t)try{const n=function(e){const t=e.getAttribute("data-lang");if(t&&Qa.includes(t))return t;let n=e;for(;n;){const e=n.getAttribute("lang");if(e){const t=e.split("-")[0].toLowerCase();if(Qa.includes(t))return t}n=n.parentElement}return"en"}(e);Yt(`ATTR-ML: Processing element with lang="${n}":`,t.substring(0,60));const r=Ya(),i=r.parseSemantic(t,n);if(.5>i.confidence||!i.node)return void Yt(`ATTR-ML: Low confidence (${i.confidence.toFixed(2)}) for: ${t}`);const s=r.buildAST(i.node),o=ye(e);await ec.execute(s.ast,o),nc.add(e),Yt("ATTR-ML: Successfully processed element")}catch(e){Yt("ATTR-ML: Error processing element:",e.message)}}async function sc(){const e=document.querySelectorAll("[_]");Yt(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(ic(e))}),await Promise.all(t),Yt("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:e.length}}))}function oc(){"undefined"!=typeof MutationObserver&&(rc=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&ic(t).catch(e=>{Yt("ATTR-ML: Error processing dynamic element:",e)});const n=t.querySelectorAll?.("[_]");n?.forEach(e=>{e instanceof HTMLElement&&ic(e).catch(e=>{Yt("ATTR-ML: Error processing dynamic descendant:",e)})})})}),rc.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=tc,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",()=>{sc().then(()=>oc())}):sc().then(()=>oc())),e.default=tc,e.hyperfixi=tc,Object.defineProperty(e,"l",{value:!0}),e}({});
|
|
2
2
|
//# sourceMappingURL=hyperfixi-multilingual.js.map
|