@hyperfixi/core 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/hyperscript-api.d.ts +6 -1
- package/dist/chunks/{bridge-CZfeDyEz.js → bridge-D2DBo02Z.js} +2 -2
- package/dist/chunks/browser-modular-BA3JFmkq.js +2 -0
- package/dist/chunks/index-C6Fn0jGB.js +2 -0
- package/dist/commands/dom/toggle.d.ts +2 -0
- package/dist/commands/index.js +35 -0
- package/dist/commands/index.mjs +35 -0
- package/dist/expressions/index.js +0 -27
- package/dist/expressions/index.mjs +0 -27
- package/dist/hyperfixi-classic-i18n.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/i18n/error-catalog.d.ts +12 -0
- package/dist/index.js +31352 -23495
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +31352 -23495
- 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/lse/index.d.ts +15 -0
- package/dist/lse/index.js +84 -0
- package/dist/lse/index.mjs +71 -0
- package/dist/parser/full-parser.js +596 -240
- package/dist/parser/full-parser.mjs +596 -240
- package/dist/parser/helpers/ast-helpers.d.ts +1 -0
- package/dist/parser/parser-types.d.ts +22 -7
- package/dist/parser/parser.d.ts +7 -0
- package/dist/parser/pratt-parser.d.ts +42 -0
- package/dist/parser/token-consumer.d.ts +1 -2
- package/dist/parser/tokenizer.d.ts +0 -33
- package/dist/registry/index.js +0 -27
- package/dist/registry/index.mjs +0 -27
- package/dist/runtime/runtime-base.d.ts +3 -0
- package/dist/types/base-types.d.ts +11 -0
- package/dist/types/core.d.ts +1 -0
- package/package.json +12 -3
- package/dist/chunks/browser-modular-CwTpxqdt.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 r of this.afterExecuteHooks)await r(e,t)}async runOnError(e,t){let r=t;for(const t of this.onErrorHooks){const n=await t(e,r);n instanceof Error&&(r=n)}return r}shouldIntercept(e,t){for(const r of this.interceptCommandHooks)if(r(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function r(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function n(e){return{ok:!0,value:e}}function o(e){return{ok:!1,error:e}}function i(e){return!0===e.ok}const s=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}(),a=s,c=s,l=s,u=s,f=s,d=(...e)=>{a&&console.log("🔧",...e)},p=(...e)=>{c&&console.log("🎯",...e)},m=(...e)=>{l&&console.log("📝",...e)},h=(...e)=>{u&&console.log("🔍",...e)},y=(...e)=>{f&&console.log("🚀",...e)};class v{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,r,n,o){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,o),this.debugMode&&y(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&y("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&y("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&y("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,r){this.addCleanup(e,{type:"custom",cleanup:t,description:r||"Custom cleanup"})}registerGlobal(e,t="custom",r){this.globalCleanups.push({type:t,cleanup:e,description:r||"Global cleanup"}),this.debugMode&&y("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e);r?r.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&y(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let r=0;for(const e of t){try{e.cleanup(),r++}catch(e){this.debugMode&&y("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&y(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(e){let t=this.cleanupElement(e);const r=e.querySelectorAll("*");for(const e of r)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&y("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&y(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,r=0,n=0,o=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":o++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+o,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const g=new Map;function b(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||g,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function w(e){if(!e)return b();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=b(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}class E{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const r=e.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(r,t)}unregister(e){const t=e.toLowerCase(),r=this.sources.get(t);if(r){for(const[e,r]of this.subscriptions.entries())r.source===t&&(r.unsubscribe(),this.subscriptions.delete(e));return r.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,r){const n=this.get(e);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+e);n.initialize?.();const o=n.subscribe(t,r);return this.subscriptions.set(o.id,o),o}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,r]of this.sources.entries())if(r.supports?.(e)??r.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class x{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,r){const n=e.toLowerCase();this.providers.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}registerGlobal(e,t,r){const n=e.toLowerCase();this.globalProviders.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,r){const n=this.get(e);if(!n)return;const o="__provider_"+n.name;if(n.cache&&r?.has(o))return r.get(o);if(n.dependencies)for(const e of n.dependencies)await this.resolve(e,t,r);const i=await n.provide(t);return n.cache&&r&&r.set(o,i),i}resolveSync(e,t,r){const n=this.get(e);if(!n)return;const o="__provider_"+n.name;if(n.cache&&r?.has(o))return r.get(o);const i=n.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(o,i),i}enhance(e){const t=this,r=new Map;return new Proxy(e,{get(e,n,o){if("string"==typeof n&&t.get(n))try{return t.resolveSync(n,e,r)}catch{return t.resolve(n,e,r)}return Reflect.get(e,n,o)},has:(e,r)=>!("string"!=typeof r||!t.has(r))||Reflect.has(e,r)})}async resolveAll(e){const t=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[o,i]of n)try{r[o]=await this.resolve(o,e,t)}catch(e){console.warn(`[ContextProviderRegistry] Failed to resolve '${o}':`,e),r[o]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const A=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,r]of this.types)if(r.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),r=this.types.get(t);return r?.hyperscriptType??"unknown"}coerce(e,t,r){const n=this.types.get(t);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(n.isType(e))return e;if(this.config.cacheCoercions){const r=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const o=this.inferType(e),i=n.coerceFrom?.[o];if(i){const n=i(e,r);if(this.config.cacheCoercions&&null!==n){const r=`${o}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(e,t){const r=this.types.get(t);if(!r)return!1;if(r.isType(e))return!0;const n=this.inferType(e);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(e,t){const r=this.types.get(t);return r&&(e===t||r.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const r=e;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,r)=>{t[r+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function S(e){const t=A.get("String");return t?t.isType(e):"string"==typeof e}function T(e){const t=A.get("Number");return t?t.isType(e):"number"==typeof e}function N(e){const t=A.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function O(e){const t=A.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function C(e){const t=A.get("Function");return t?t.isType(e):"function"==typeof e}function k(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function j(e){return e instanceof Element}const L=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function I(e,t){return L.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const R={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=>k(e)?e.tabIndex:void 0,hidden:e=>k(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e.getAttribute("name");r&&"value"in e&&t.append(r,e.value)}),t}(e)};function $(e,t){if(t.startsWith("computed-")){const r=t.slice(9);return function(e){return e instanceof HTMLElement}(e)?getComputedStyle(e).getPropertyValue(r):void 0}if(t.startsWith("@"))return I(e,t.slice(1));const r=R[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return I(e,t);const n=e[t];return C(n)?n.bind(e):n}function M(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 D(e){return e.me?.ownerDocument??("undefined"!=typeof document?document:null)}function V(e,t){return t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):t.variables?.has(e)?t.variables.get(e):"me"===e?t.me:"it"===e?t.it:"result"===e?t.result:void 0}async function _(e,t){if(e.includes(".")){const r=e.split(".");let n=V(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return V(e,t)}async function P(e,t){if(h(`RESOLVE: Looking for '${e}' in context`,{hasInLocals:t.locals.has(e),localsKeys:Array.from(t.locals.keys()),value:t.locals.get(e)}),t.locals.has(e)){const r=t.locals.get(e);return h(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return h(`RESOLVE: Found '${e}' in globals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return h(`RESOLVE: Found '${e}' in variables (legacy):`,r),r}const r=Number(e);if(!isNaN(r))return r;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split("."),n=r[0];let o=null;if(t.locals.has(n)?o=t.locals.get(n):t.globals&&t.globals.has(n)?o=t.globals.get(n):t.variables&&t.variables.has(n)&&(o=t.variables.get(n)),null!=o){for(let e=1;r.length>e;e++){if(null==o)return void h(`RESOLVE: Property access failed at '${r[e-1]}'`);o=o[r[e]]}return h(`RESOLVE: Property access '${e}' =`,o),o}}return e}async function B(e,t){h("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,o]=r;h("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:o});const i=await P(e.trim(),t);if(h("EVAL: Ternary condition value:",i),i){const e=await P(n.trim(),t);return h("EVAL: Ternary returned true branch:",e),e}{const e=await P(o.trim(),t);return h("EVAL: Ternary returned false branch:",e),e}}const n=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,e,r,o]=n;h("EVAL: Parsed arithmetic:",{left:e,operator:r,right:o});const i=await P(e.trim(),t),s=await P(o.trim(),t);h("EVAL: Resolved values:",{leftValue:i,rightValue:s});const a=Number(i),c=Number(s);if(!isNaN(a)&&!isNaN(c)){let e;switch(r){case"+":e=a+c;break;case"-":e=a-c;break;case"*":e=a*c;break;case"/":e=a/c;break;case"%":e=a%c;break;default:e=a}return h("EVAL: Arithmetic result:",e),e}}const o=await P(e.trim(),t);return h("EVAL: Fallback result:",o),o}function q(e){if(Array.isArray(e)&&1===e.length&&(e=e[0]),null!==e&&"object"==typeof e&&"string"==typeof e.textContent){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?e:r}return 0}return e}async function F(e,t,r,n,o){try{const i=o(await n(e.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const s=M(e.property);if(!s||"string"!=typeof s)throw Error("Invalid method name: "+s);const a=i[s];if("function"!=typeof a)throw Error(`Property "${s}" is not a function on ${i.constructor?.name||typeof i}`);const c=await Promise.all(t.map(e=>n(e,r)));return a.apply(i,c)}catch(e){if(e instanceof Error)throw e;throw Error("Failed to evaluate method call: "+e)}}class H{constructor(){this.expressionRegistry=new Map}registerCategory(e){Object.entries(e).forEach(([e,t])=>{this.expressionRegistry.set(e,t)})}unwrapSelectorResult(e){if(e instanceof NodeList&&e.length>0)return e[0];if(Array.isArray(e)&&e.length>0){const t=e[0];return"index"in e&&"input"in e?e:t instanceof Element||t instanceof Node?t:e}return e}async evaluate(e,t){if(!e)return h("EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));switch(e.type){case"identifier":return this.evaluateIdentifier(e,t);case"literal":return this.evaluateLiteral(e,t);case"string":return e.value??"";case"memberExpression":return this.evaluateMemberExpression(e,t);case"binaryExpression":return this.evaluateBinaryExpression(e,t);case"unaryExpression":return this.evaluateUnaryExpression(e,t);case"callExpression":return this.evaluateCallExpression(e,t);case"selector":return this.evaluateSelector(e,t);case"dollarExpression":return this.evaluateDollarExpression(e,t);case"possessiveExpression":return this.evaluatePossessiveExpression(e,t);case"templateLiteral":return this.evaluateTemplateLiteral(e,t);case"arrayLiteral":return this.evaluateArrayLiteral(e,t);case"objectLiteral":return this.evaluateObjectLiteral(e,t);case"conditionalExpression":return this.evaluateConditionalExpression(e,t);case"cssSelector":return this.evaluateCSSSelector(e,t);case"propertyAccess":return this.evaluatePropertyAccess(e,t);case"propertyOfExpression":return this.evaluatePropertyOfExpression(e,t);case"contextReference":return this.evaluateContextReference(e,t);case"queryReference":return this.evaluateQueryReference(e,t);case"idSelector":return this.evaluateIdSelector(e,t);case"attributeAccess":return this.evaluateAttributeAccess(e,t);default:throw Error("Unsupported AST node type for evaluation: "+e.type)}}async evaluateWithResult(e,t){try{return n(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return o({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return o({type:"exit",returnValue:t.returnValue});if(t.isBreak)return o({type:"break"});if(t.isContinue)return o({type:"continue"});if(t.isReturn)return o({type:"return",returnValue:t.returnValue})}throw e}}async evaluateArrayLiteral(e,t){const r=e.elements||[],n=[];for(const e of r){const r=await this.evaluate(e,t);n.push(r)}return n}async evaluateObjectLiteral(e,t){const r=e.properties||[],n={};for(const e of r){let r;r="identifier"===e.key.type?e.key.name:"literal"===e.key.type?e.key.value+"":await this.evaluate(e.key,t)+"";const o=await this.evaluate(e.value,t);n[r]=o}return n}async evaluateConditionalExpression(e,t){return await this.evaluate(e.test,t)?this.evaluate(e.consequent,t):e.alternate?this.evaluate(e.alternate,t):void 0}async evaluateTemplateLiteral(e,t){return async function(e,t){let r=e.value||"";h("TEMPLATE LITERAL: Evaluating",{template:r,node:e});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,o=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&o.push({match:i[0],varName:i[1],index:i.index});for(let e=o.length-1;e>=0;e--){const{match:n,varName:i,index:s}=o[e],a=await _(i,t);h(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,s)+((a??"")+"")+r.slice(s+n.length)}let s="",a=0;for(;r.length>a;){const e=r.indexOf("${",a);if(-1===e){s+=r.slice(a);break}s+=r.slice(a,e);let n=1,o=e+2;for(;r.length>o&&n>0;)"{"===r[o]&&n++,"}"===r[o]&&n--,n>0&&o++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(e+2,o);let c;h("TEMPLATE: Evaluating expression:",i);const l=i.trim();t.locals.has(l)?(c=t.locals.get(l),h(`TEMPLATE: Found in locals: ${l} =`,c)):t.globals&&t.globals.has(l)?(c=t.globals.get(l),h(`TEMPLATE: Found in globals: ${l} =`,c)):t.variables&&t.variables.has(l)?(c=t.variables.get(l),h(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await B(i,t),h(`TEMPLATE: Evaluated expression "${i}" =`,c)),s+=c+"",a=o+1}return s}(e,t)}async evaluateSimpleExpression(e,t){return B(e,t)}async resolveValue(e,t){return P(e,t)}async evaluateIdentifier(e,t){const{name:r,scope:n}=e;if("me"===r||"my"===r||"I"===r)return t.me;if("you"===r||"your"===r)return t.you;if("it"===r||"its"===r)return t.it;if("result"===r)return t.result;if("event"===r)return t.event;const o=this.expressionRegistry.get(r);return o?o.evaluate(t):"local"===n?t.locals?.has(r)?t.locals.get(r):void 0:"global"===n?t.globals?.has(r)?t.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:t.locals?.has(r)?t.locals.get(r):t.globals?.has(r)?t.globals.get(r):t.variables?.has(r)?t.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(e,t){return e.value}async evaluateContextReference(e,t){const{contextType:r}=e;switch(r){case"me":return t.me;case"it":return t.result;case"you":return t.you;case"event":return t.event;case"body":return t.meta?.ownerDocument?.body||document?.body;case"detail":return t.event?.detail;case"target":return t.you||t.event?.target;case"sender":return t.event?.target;default:return t.locals&&t.locals.has(r)?t.locals.get(r):void h("Unknown context reference type: "+r)}}async evaluateMemberExpression(e,t){const{object:r,property:n,computed:o}=e;if("identifier"===r.type&&["add","remove"].includes(r.name)){const e=r.name,o=M(n);if(!t.me)throw Error('Context element "me" is null');return void("add"===e?t.me.classList.add(o):"remove"===e&&t.me.classList.remove(o))}let i=await this.evaluate(r,t);if(o)return i[await this.evaluate(n,t)];{const e=M(n);if(Array.isArray(i)&&"string"==typeof e&&("length"===e||e in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof e){if(e.startsWith("computed-")){const t=e.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(t):void 0}if(e.startsWith("@")){const t=e.substring(1);return i&&"function"==typeof i.getAttribute?I(i,t):void 0}if(i&&i instanceof Element){if("previous"===e||"prev"===e)return i.previousElementSibling;if("next"===e)return i.nextElementSibling}}const t=i?.[e];return"function"==typeof t?t.bind(i):t}}coerceArithmeticOperand(e){return q(e)}async evaluateBinaryExpression(e,t){return async function(e,t,r,n,o){const{operator:i,left:s,right:a}=e;if("in"===i&&"selector"===s.type){let e=s.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const o=n(await r(a,t));if(!o||"function"!=typeof o.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof o})`);const i=o.querySelectorAll(e);return Array.from(i)}if("in"===i&&"queryReference"===s.type){let e=s.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const o=n(await r(a,t));if(!o||"function"!=typeof o.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof o})`);const i=o.querySelectorAll(e);return Array.from(i)}if("in"===i){let e=null,o=null;if("positionalExpression"===s.type){e=s.operator;const n=s.argument;"cssSelector"===n?.type?o=n.selector:"selector"===n?.type?o=n.value:"classSelector"===n?.type?o="."+n.className:"idSelector"===n?.type?o="#"+n.id:n&&(o=await r(n,t)+"")}else if("memberExpression"!==s.type||"identifier"!==s.object?.type||"first"!==s.object.name&&"last"!==s.object.name){if("callExpression"===s.type&&"identifier"===s.callee?.type&&("first"===s.callee.name||"last"===s.callee.name)){e=s.callee.name;const n=s.arguments?.[0];"selector"===n?.type?o=n.value:"cssSelector"===n?.type?o=n.selector:"classSelector"===n?.type?o="."+n.className:"idSelector"===n?.type?o="#"+n.id:n&&(o=await r(n,t)+"")}}else e=s.object.name,"identifier"===s.property?.type&&s.property.name&&(o="."+s.property.name);if(e&&o){const i=n(await r(a,t));if(!i||"function"!=typeof i.querySelectorAll)return;const s=i.querySelectorAll(o),c=Array.from(s);return"first"===e?c.length>0?c[0]:void 0:"last"===e?c.length>0?c[c.length-1]:void 0:c}}if("matches"===i&&("selector"===a.type||"cssSelector"===a.type||"classSelector"===a.type)){const e=await r(s,t),n=a.value||a.selector;if(e&&"function"==typeof e.matches)try{return e.matches(n)}catch{return!1}return!1}const c=await r(s,t),l=await r(a,t);if("has"===i||"have"===i){if(c instanceof Element){if("cssSelector"===a.type&&"class"===a.selectorType||"selector"===a.type&&a.value?.startsWith(".")){const e=a.selector?.slice(1)||a.value?.slice(1)||"";return c.classList.contains(e)}if("attributeAccess"===a.type||"attributeRef"===a.type){const e=a.attributeName||a.name||a.value?.replace(/^@/,"")||"";return c.hasAttribute(e)}if("cssSelector"===a.type&&"attribute"===a.selectorType){const e=(a.selector||a.value||"").replace(/^@/,"");return c.hasAttribute(e)}if("cssSelector"===a.type&&"id"===a.selectorType||"idSelector"===a.type){const e=(a.selector||a.value||"").replace(/^#/,"");return null!==c.querySelector("#"+CSS.escape(e))}if("selector"===a.type||"queryReference"===a.type){let e=a.value||a.selector||"";e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());try{return null!==c.querySelector(e)}catch{return!1}}if("cssSelector"===a.type){const e=a.selector||"";try{return null!==c.querySelector(e)}catch{return!1}}}return Array.isArray(c)?c.includes(l):"string"==typeof c&&c.includes(l+"")}switch(i){case">":case"is greater than":return c>l;case"<":case"is less than":return l>c;case">=":case"is greater than or equal to":return c>=l;case"<=":case"is less than or equal to":return l>=c;case"==":case"equals":case"is equal to":return c==l;case"===":case"is really equal to":case"really equals":return c===l;case"!=":case"is not equal to":return c!=l;case"!==":case"is not really equal to":return c!==l;case"+":{const e=q(c),r=q(l);if("string"==typeof e||"string"==typeof r){const n=o.get("stringConcatenation");if(n){h("Using string concatenation for:",{leftValue:e,rightValue:r});const o=await n.evaluate(t,{left:e,right:r});return o.success?o.value:e+r}}else{const n=o.get("addition");if(n){h("Using numeric addition for:",{leftValue:e,rightValue:r});const o=await n.evaluate(t,{left:e,right:r});return o.success?o.value:e+r}}return e+r}case"-":return q(c)-q(l);case"*":return q(c)*q(l);case"/":return q(c)/q(l);case"%":case"mod":return q(c)%q(l);case"as":const e="string"==typeof l?l:"identifier"===a.type?a.name:"literal"===a.type?a.value:l+"",r=o.get("as");return r?r.evaluate(t,c,e):c;case"&&":case"and":return c&&l;case"||":case"or":return c||l;case"is":return c===l;case"is not":return c!==l;case"is a":case"is an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"==typeof c;case"number":return"number"==typeof c;case"boolean":return"boolean"==typeof c;case"object":return"object"==typeof c&&null!==c;case"array":return Array.isArray(c);case"function":return"function"==typeof c;case"null":return null===c;case"undefined":return void 0===c;default:const e="identifier"===a.type?a.name:l+"";return null!=c&&c.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"!=typeof c;case"number":return"number"!=typeof c;case"boolean":return"boolean"!=typeof c;case"object":return!("object"==typeof c&&null!==c);case"array":return!Array.isArray(c);case"function":return"function"!=typeof c;case"null":return null!==c;case"undefined":return void 0!==c;default:const e="identifier"===a.type?a.name:l+"";return!(null!=c&&c.constructor?.name===e)}case"=":if("identifier"===s.type){const e=s.name;return"result"===e?t.result=l:"it"===e?t.it=l:"you"===e?t.you=l:t.locals.set(e,l),l}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):!(!c||"function"!=typeof c.matches)&&c.matches(l+"");case"match":case"matches":if(c&&"function"==typeof c.matches){const e="string"==typeof l?l:l+"";try{return c.matches(e)}catch{return!1}}return!1;case"in":const n="string"==typeof c?c:c+"",u=l;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(c);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof c&&"string"==typeof l?{command:c,selector:l}:"identifier"===s.type&&"selector"===a.type?{command:s.name,selector:a.value}:l;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(e,t){const{operator:r,argument:n}=e,o=await this.evaluate(n,t);switch(r){case"not":case"!":const e=this.expressionRegistry.get("not");return e?e.evaluate(t,o):!o;case"no":const n=this.expressionRegistry.get("no");return!!n&&n.evaluate(t,o);case"some":return null!=o&&("string"==typeof o||Array.isArray(o)||o instanceof NodeList||o instanceof HTMLCollection?o.length>0:"object"!=typeof o||Object.keys(o).length>0);case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(t,o):null!=o;case"does not exist":const s=this.expressionRegistry.get("doesNotExist");return s?s.evaluate(t,o):null==o;case"-":return-o;case"+":return+o;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(e,t){return async function(e,t,r,n,o,i){const{callee:s,arguments:a,isConstructor:c}=e;if(c){const e=s.name,n=t.globals?.get(e)||window[e];if("function"==typeof n)return new n(...await Promise.all(a.map(e=>r(e,t))));throw Error("Unknown constructor: "+e)}if("memberExpression"===s.type||"propertyAccess"===s.type)return F(s,a,t,r,n);const l=s.name||s,u=o.get(l);if(u){const e=["first","last","random","at"],n=["closest","previous","next"].includes(l),o=e.includes(l),s=await Promise.all(a.map(e=>n&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:n&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:o&&e&&"selector"===e.type&&"string"==typeof e.value?i(e,t):r(e,t)));return u.evaluate(t,...s)}const f=t.globals?.get(l)||window[l];if("function"==typeof f)return f(...await Promise.all(a.map(e=>r(e,t))));throw Error("Unknown function: "+l)}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(e,t,r){return F(e,t,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(e,t){return function(e,t){let r=e.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=D(t);if(!n)return[];const o=n.querySelectorAll(r);return Array.from(o).filter(e=>e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.tagName)}(e,t)}evaluateAttributeAccess(e,t){return t.me&&"function"==typeof t.me.getAttribute?I(t.me,e.attributeName):"@"+e.attributeName}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(e,t){const r=await this.evaluate(e.expression,t);if("identifier"===e.expression.type){const r=e.expression.name;return/^\d+$/.test(r)?r:t.locals?.has(r)?t.locals.get(r):"me"===r&&t.me?t.me:"you"===r&&t.you?t.you:"it"===r&&t.it?t.it:"result"===r&&t.result?t.result:"undefined"!=typeof window&&"window"===r?window:t.globals?.has(r)?t.globals.get(r):void 0}return r}async evaluatePossessiveExpression(e,t){const{object:r,property:n}=e,o=this.unwrapSelectorResult(await this.evaluate(r,t));if(!o)return;const i=M(n);return"string"==typeof i&&j(o)?$(o,i):o[i]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){return function(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=D(t);if(!n)return"id"===e.selectorType?null:[];if("id"===e.selectorType){const e=r.startsWith("#")?r.slice(1):r;return n.getElementById(e)}if("class"===e.selectorType){const e=r.replace(/:/g,"\\:"),t=n.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const o=n.querySelectorAll(r);return Array.from(o).filter(e=>e instanceof HTMLElement)}(e,t)}async evaluateIdSelector(e,t){return function(e,t){const r=D(t);if(!r)return null;const n=e.value.startsWith("#")?e.value.slice(1):e.value;return r.getElementById(n)}(e,t)}async evaluateQueryReference(e,t){return function(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=D(t);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(e,t)}async evaluatePropertyAccess(e,t){const r=await this.evaluate(e.object,t),n=e.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const o=n.name||n.value;if(!o)throw Error("Property name must be an identifier");try{let e;return e=j(r)?$(r,o):r[o],"function"==typeof e?e.bind(r):e}catch(e){throw Error(`Error accessing property "${o}": ${e}`)}}async evaluatePropertyOfExpression(e,t){const r=e.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const o=this.unwrapSelectorResult(await this.evaluate(e.target,t));if(null==o)throw Error(`Cannot access property "${n}" of ${o}`);try{let e;return e=j(o)?$(o,n):o[n],"function"==typeof e?e.bind(o):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const U={1:"one",2:"two",3:"three",4:"four",5:"five"};function W(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${o=t,U[o]??o+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var o;return null}function J(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function z(e,t,r){return W(e,1,t,r)??J(e,0,t,r)}function Z(e,t){return W(e,2,t,"left, right")}function G(){return null}function X(e,t,r,n){return e.length>t?`${r} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${n?` (${n})`:""}`:null}function Y(e,t,r,n,o){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${o?` (${o})`:""}`:null}function K(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const Q="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 ee;function te(){return ee({validate:e=>({success:!0,data:e})})}function re(e,t){if(Q)return te();const r=ee({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:K("type-mismatch","Expected object, received "+typeof r)};const n=r,o={};if(t?.strict){const t=Object.keys(e),r=Object.keys(n).filter(e=>!t.includes(e));if(r.length>0)return{success:!1,error:K("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=n[t];if(!(t in n)&&!r.t)return{success:!1,error:K("missing-argument",`Required field "${t}" is missing`,t)};const i=r.validate(e);if(!i.success)return{success:!1,error:K("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};void 0!==i.data&&(o[t]=i.data)}return{success:!0,data:o}}});return r.strict=()=>re(e,{strict:!0}),r}ee=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 ee(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&e>n.data.length?{success:!1,error:K("runtime-error",`String must be at least ${e} characters long`)}:n}};return ee(r)}),e.max||(e.max=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&n.data.length>e?{success:!1,error:K("runtime-error",`String must be at most ${e} characters long`)}:n}};return ee(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,o:e,i:!0,validate:r=>void 0===r?{success:!0,data:e}:t(r)};return ee(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const r=this.validate.bind(this),n={...this,validate:n=>{const o=r(n);return o.success?e(o.data)?o:{success:!1,error:K("runtime-error",t||"Refinement validation failed")}:o}};return ee(n)}),new Proxy(e,{get:(e,t,r)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,r):function(...e){return r}})};const ne=e=>function(e={}){return Q?te():ee({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:K("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:K("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:K("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:K("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:K("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),oe=e=>function(e={}){return Q?te():ee({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:K("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:K("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:K("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{}),ie=()=>Q?te():ee({validate:e=>"boolean"!=typeof e?{success:!1,error:K("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),se=e=>re(e),ae=e=>function(e){return Q?te():ee({validate:t=>{if(!Array.isArray(t))return{success:!1,error:K("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:K("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const r=[];for(let n=0;e.length>n;n++){const o=e[n].validate(t[n]);if(!o.success)return{success:!1,error:K("runtime-error",o.error.message,o.error.path?`${n}.${o.error.path}`:""+n)};r.push(o.data)}return{success:!0,data:r}}})}(e),ce=()=>te(),le=()=>te(),ue=()=>function(e,t="Custom validation failed"){return Q?te():ee({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:K("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class fe{trackPerformance(e,t,r,n){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(e,t,r,n=(r?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:t,duration:Date.now()-t,success:r})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||T(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,r,n,o=[]){return{success:!1,error:{name:e,type:t,message:r,code:n,suggestions:o}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":O(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":S(e)?"String":T(e)?"Number":N(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):S(e)?e.split(""):null==e?[]:O(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(T(e)&&Number.isFinite(e))return e;if(S(e)){const t=Number(e);return Number.isFinite(t)?t:null}return N(e)?e?1:0:null}}class de extends fe{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=ue(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.me,o=this.isElement(n)?n:null,i=this.success(o,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const o=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,o,r),o}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}}class pe extends fe{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=ue(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.you,o=this.isElement(n)?n:null,i=this.success(o,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const o=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,o,r),o}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}}class me extends fe{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=ue(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.it,o={success:!0,value:n,type:this.inferType(n)};return this.trackPerformance(e,t,o,r),o}catch(n){const o=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,o,r),o}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}}const he=se({selector:ne().min(1),single:ie().optional().default(!1)});class ye extends fe{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=he,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const r=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,n,r),n}let n;if(t.single)n=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));n=e.length>0?e:null}const o={success:!0,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(e,t,o,r),o}catch(n){const o=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=t.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}}new de,new pe,new me,new ye;const ve={name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:G},ge={name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:G},be={name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:G},we={name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:G},Ee={name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:G},xe={name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:e=>z(e,"querySelector","selector")},Ae={name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>z(e,"querySelectorAll","selector")},Se={name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:e=>z(e,"getElementById","ID")},Te={name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:e=>z(e,"getElementsByClassName","className")},Ne={name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let r=t[0];if(r&&"object"==typeof r&&"type"in r){const e=r;"identifier"===e.type&&e.name?r=e.name:"literal"===e.type&&"string"==typeof e.value&&(r=e.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return e.me?e.me.closest(r):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},Oe={name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:G},Ce={name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:G},ke={name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:G},je={name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>z(e,"elementWithSelector","selector")},Le={name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const o=n||e.me;if(o&&o instanceof HTMLElement){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(r)||void 0}},validate:e=>Y(e,1,2,"styleRef","property, optional element")??J(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},Ie={name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let o=null;if("my"===r&&e.me?o=e.me instanceof HTMLElement?e.me:null:"its"===r&&e.it&&(o=e.it instanceof HTMLElement?e.it:null),o){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(n)||void 0}},validate:e=>W(e,2,"possessiveStyleRef","possessor, property")??J(e,0,"possessiveStyleRef","possessor")??J(e,1,"possessiveStyleRef","property")},Re={name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let o=null;if("me"===n&&e.me?o=e.me instanceof HTMLElement?e.me:null:"it"===n&&e.it&&(o=e.it instanceof HTMLElement?e.it:null),o){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(r)||void 0}},validate:e=>W(e,2,"ofStyleRef","property, reference")??J(e,0,"ofStyleRef","property")??J(e,1,"ofStyleRef","reference")},$e={me:ve,you:ge,it:be,its:we,result:Ee,querySelector:xe,querySelectorAll:Ae,getElementById:Se,getElementsByClassName:Te,closest:Ne,parent:Oe,window:Ce,document:ke,elementWithSelector:je,styleRef:Le,possessiveStyleRef:Ie,ofStyleRef:Re};var Me=Object.freeze({__proto__:null,CSSSelectorExpression:ye,ItExpression:me,MeExpression:de,YouExpression:pe,classExpression:Te,closestExpression:Ne,createItExpression:function(){return new me},createMeExpression:function(){return new de},createYouExpression:function(){return new pe},documentExpression:ke,elementWithSelectorExpression:je,idExpression:Se,itExpression:be,itsExpression:we,meExpression:ve,ofStyleRefExpression:Re,parentExpression:Oe,possessiveStyleRefExpression:Ie,querySelectorAllExpression:Ae,querySelectorExpression:xe,referencesExpressions:$e,resultExpression:Ee,styleRefExpression:Le,windowExpression:Ce,youExpression:ge});class De{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.timestamp<=this.ttl)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU();const r={result:t,timestamp:Date.now(),accessCount:1};this.cache.set(e,r),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[r,n]of this.accessOrder)t>n&&(t=n,e=r);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,r)=>e+(t-r.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const Ve=new class{constructor(){this.domQueryCache=new De(200,3e3),this.exprResultCache=new De(500,2e3),this.cssMatchCache=new De(100,5e3),this.formValueCache=new De(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(e);return this.domQueryCache.set(t,n),n}querySelectorAll(e){const t="querySelectorAll:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,n),n}getElementById(e){const t="getElementById:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(e);return this.domQueryCache.set(t,n),n}getElementsByClassName(e){const t="getElementsByClassName:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,n),n}matches(e,t){const r=`matches:${this.getElementCacheKey(e)}:${t}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const o=e.matches(t);return this.cssMatchCache.set(r,o),o}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),r=this.formValueCache.get("formValue:"+t);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(e,t){const r=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+r,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(e.cache.keys()))"string"==typeof r&&r.includes(t)&&e.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),r=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${r}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([r,n])=>{e-n.timestamp>t.ttl&&t.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{Ve.cleanup()},1e4);const _e=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]);var Pe,Be;!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"}(Pe||(Pe={})),function(e){e.KEYWORD="keyword",e.COMMAND="command",e.EXPRESSION="expression",e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.TEMPLATE_LITERAL="template_literal",e.CSS_SELECTOR="css_selector",e.ID_SELECTOR="id_selector",e.CLASS_SELECTOR="class_selector",e.QUERY_REFERENCE="query_reference",e.CONTEXT_VAR="context_var",e.GLOBAL_VAR="global_var",e.EVENT="event",e.OPERATOR="operator",e.LOGICAL_OPERATOR="logical_operator",e.COMPARISON_OPERATOR="comparison_operator",e.TIME_EXPRESSION="time_expression",e.OBJECT_LITERAL="object_literal",e.ARRAY_LITERAL="array_literal",e.SYMBOL="symbol",e.COMMENT="comment",e.IDENTIFIER="identifier",e.UNKNOWN="unknown"}(Be||(Be={}));const qe=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const r=performance.now()-t;return this.startTimes.delete(e),r}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=Ve.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 Fe(){Ve.cleanup(),qe.getMetrics().memoryUsage>52428800&&qe.reset()}let He=null;function Ue(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const r=e.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${t} cannot be converted to number: "${e}"`);return n}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const r=e[0];if(Array.isArray(r))throw Error(t+" is a nested array, cannot convert to number");return Ue(r,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const r=parseFloat(e);if(!isNaN(r))return r}}const r=e.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function We(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?null:r}return"boolean"==typeof e?e?1:0:null==e?0:null}function Je(e,t,r){if("==="===r)return e===t;if("!=="===r)return e!==t;if(null==e||null==t)return function(e,t,r){if(null==e&&null==t)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,r);const[n,o]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const r=parseFloat(e),n=parseFloat(t);return isNaN(r)||isNaN(n)?[e,t]:[r,n]}const r=We(e),n=We(t);return null!==r&&null!==n?[r,n]:[e+"",t+""]}(e,t);switch(r){case">":return n>o;case"<":return o>n;case">=":return n>=o;case"<=":return o>=n;case"==":return ze(e,t);case"!=":return!ze(e,t);default:return!1}}function ze(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const r=parseFloat(t);return!isNaN(r)&&e===r}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);return!isNaN(r)&&r===t}return"boolean"==typeof e?ze(e?1:0,t):"boolean"==typeof t?ze(e,t?1:0):e+""==t+""}function Ze(e,t,r,n,o,i=!0,s){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:r,output:n,timestamp:o,duration:Date.now()-o,success:i,...void 0!==s&&{error:s}}),n}"undefined"!=typeof window&&function(e=3e4){He&&clearInterval(He),He=setInterval(Fe,e)}();const Ge=se({left:ce().describe("Left operand value"),right:ce().describe("Right operand value")}).strict(),Xe=se({operand:ce().describe("Operand value to negate")}).strict();class Ye extends fe{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=Ge,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.toBoolean(t.left);if(!o)return this.trackSimple(e,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),s=o&&i;return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Ke extends fe{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=Ge,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.toBoolean(t.left);if(o)return this.trackSimple(e,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),s=o||i;return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Qe extends fe{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=Xe,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=!this.toBoolean(t.operand);return this.trackSimple(e,r,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function et(){return new Ye}function tt(){return new Ke}function rt(){return new Qe}function nt(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}et(),tt(),rt();const ot=ae([ce(),ce()]),it=ae([ce(),ne()]),st={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return Ze(this,e,[t,r],t==r,n)}catch(o){throw Ze(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>Z(e,"equals"),inputSchema:ot,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"]}},at={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t===r;return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"strictEquals")},ct={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t!=r;return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"notEquals")},lt={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t!==r;return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"strictNotEquals")},ut={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=Je(t,r,"<");return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"lessThan")},ft={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=Je(t,r,"<=");return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"lessThanOrEqual")},dt={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=Je(t,r,">");return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"greaterThan")},pt={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=Je(t,r,">=");return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"greaterThanOrEqual")},mt={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return Ze(this,e,[t,r],t&&r,n)}catch(o){throw Ze(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>Z(e,"and"),inputSchema:ot,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"]}},ht={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t||r;return n&&Ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"or")},yt={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=!t;return r&&Ze(this,e,[t],o,n),o},validate:e=>W(e,1,"not","operand")},vt={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let o;return o=null==t||(S(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!O(t)||0!==Object.keys(t).length)),r&&Ze(this,e,[t],o,n),o},validate:e=>W(e,1,"isEmpty","value")},gt={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let o;return o=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!(S(t)||t instanceof Node||t instanceof Element||!O(t)||0!==Object.keys(t).length)),r&&Ze(this,e,[t],o,n),o},validate:e=>W(e,1,"no","value")},bt={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=!await vt.evaluate(e,t);return r&&Ze(this,e,[t],o,n),o},validate:e=>W(e,1,"isNotEmpty","value")},wt={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=null!=t;return r&&Ze(this,e,[t],o,n),o},validate:e=>W(e,1,"exists","value")},Et={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=null==t;return r&&Ze(this,e,[t],o,n),o},validate:e=>W(e,1,"doesNotExist","value")},xt={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0;let i;if(t&&r){if(nt(t)&&nt(r))return i=t.contains(r),n&&Ze(this,e,[t,r],i,o),i;if(S(t)&&t.match(/^[.#][\w-]+$/)){const s=document.querySelector(t);if(s&&nt(r))return i=s.contains(r),n&&Ze(this,e,[t,r],i,o),i;if(s&&S(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=!!a&&s.contains(a),n&&Ze(this,e,[t,r],i,o),i}}if(S(r)&&r.match(/^[.#][\w-]+$/)&&nt(t)){const s=document.querySelector(r);return i=!!s&&t.contains(s),n&&Ze(this,e,[t,r],i,o),i}}return i=S(t)&&S(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!O(t)||!S(r))&&r in t,n&&Ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"contains","container, value")},At={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!await xt.evaluate(e,t,r);return n&&Ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"doesNotContain","container, value")},St={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!(!S(t)||!S(r))&&t.startsWith(r);return n&&Ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"startsWith","str, prefix")},Tt={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!(!S(t)||!S(r))&&t.endsWith(r);return n&&Ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"endsWith","str, suffix")},Nt={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let o;if(t instanceof Element&&S(r)){const e=r;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{o=function(e,t){return Ve.matches(e,t)}(t,e)}catch(e){o=!1}else o=!1}else if(S(t)&&S(r)){const e=t,n=r;try{o=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(e)}catch(t){o=e.includes(n)}}else o=!1;return Ze(this,e,[t,r],o,n)}catch(o){throw Ze(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>W(e,2,"matches","element, selector"),inputSchema:it,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"]}},Ot={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0;let i=!1;if(t instanceof Element&&S(r)){const e=r;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return n&&Ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"has","element, selector")},Ct={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!await Ot.evaluate(e,t,r);return n&&Ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"doesNotHave","element, selector")},kt={equals:st,strictEquals:at,notEquals:ct,strictNotEquals:lt,lessThan:ut,lessThanOrEqual:ft,greaterThan:dt,greaterThanOrEqual:pt,and:mt,or:ht,not:yt,no:gt,isEmpty:vt,isNotEmpty:bt,exists:wt,doesNotExist:Et,contains:xt,doesNotContain:At,startsWith:St,endsWith:Tt,matches:Nt,has:Ot,doesNotHave:Ct};var jt=Object.freeze({__proto__:null,AndExpression:Ye,NotExpression:Qe,OrExpression:Ke,andExpression:mt,containsExpression:xt,createAndExpression:et,createNotExpression:rt,createOrExpression:tt,doesNotContainExpression:At,doesNotExistExpression:Et,doesNotHaveExpression:Ct,endsWithExpression:Tt,equalsExpression:st,existsExpression:wt,greaterThanExpression:dt,greaterThanOrEqualExpression:pt,hasExpression:Ot,isEmptyExpression:vt,isNotEmptyExpression:bt,lessThanExpression:ut,lessThanOrEqualExpression:ft,logicalExpressions:kt,matchesExpression:Nt,noExpression:gt,notEqualsExpression:ct,notExpression:yt,orExpression:ht,startsWithExpression:St,strictEqualsExpression:at,strictNotEqualsExpression:lt});function Lt(e,t,r,n,o="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:o,message:r,code:t,suggestions:n}}}function It(e,t){return{success:!0,value:e,type:t}}function Rt(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const $t={Array:(e,t)=>{try{return Array.isArray(e)?It(e,"array"):e instanceof NodeList?It(Array.from(e),"array"):It(null==e?[]:[e],"array")}catch(e){return Lt("Array","ARRAY_CONVERSION_FAILED",Rt("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?It("","string"):S(e)?It(e,"string"):O(e)?It(JSON.stringify(e),"string"):It(e+"","string")}catch(e){return Lt("String","STRING_CONVERSION_FAILED",Rt("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(N(e))return It(e,"boolean");if(null==e)return It(!1,"boolean");if(S(e)){const t=e.toLowerCase().trim();return It("false"!==t&&"0"!==t&&""!==t,"boolean")}return T(e)?It(0!==e&&!isNaN(e),"boolean"):It(!!e,"boolean")}catch(e){return Lt("Boolean","BOOLEAN_CONVERSION_FAILED",Rt("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(T(e))return It(e,"number");if(null==e)return It(0,"number");const t=Number(e);return isNaN(t)?Lt("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):It(t,"number")}catch(e){return Lt("Number","NUMBER_CONVERSION_FAILED",Rt("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=$t.Number(e,t);return r.success?It(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=$t.Number(e,t);return r.success?It(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return It(e,"object");if(null==e)return It(new Date(""),"object");if(S(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return It(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?Lt("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"):It(t,"object")}catch(e){return Lt("Date","DATE_CONVERSION_FAILED",Rt("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return It(JSON.stringify(e),"string")}catch(e){return Lt("JSON","JSON_STRINGIFY_FAILED",Rt("Failed to convert value to JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(O(e))return It(e,"object");if(S(e))try{return It(JSON.parse(e),"object")}catch(e){return Lt("Object","JSON_PARSE_FAILED",Rt("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return It({},"object")}catch(e){return Lt("Object","OBJECT_CONVERSION_FAILED",Rt("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 It(Pt(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{const t=e;if(t.name){const e=Bt(t);void 0!==e&&(r[t.name]=e)}}),It(r,"object")}return It({},"object")}catch(e){return Lt("FormValues","FORM_VALUES_EXTRACTION_FAILED",Rt("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},Mt=se({value:le(),type:ne().min(1)});class Dt extends fe{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=Mt,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:o,type:i}=t;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),s=n?parseInt(n[1],10):2,a=$t.Number(o,e);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(s),type:"string"};return this.trackPerformance(e,t,c,r),c}let s=$t[i];if(s){const n=s(o,e);return this.trackPerformance(e,t,n,r),n}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"}[i.toLowerCase()];if(a&&(s=$t[a],s)){const n=s(o,e);return this.trackPerformance(e,t,n,r),n}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(e,t,c,r),c}catch(n){const o={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}}const Vt=se({value:le(),type:ne().min(1)});new Dt,new class extends fe{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=Vt,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:o,type:i}=t,s=i.toLowerCase();let a;switch(s){case"null":a=null===o;break;case"undefined":a=void 0===o;break;case"string":a=S(o);break;case"number":a=T(o)&&!isNaN(o);break;case"boolean":a=N(o);break;case"object":a=O(o);break;case"array":a=Array.isArray(o);break;case"function":a=C(o);break;case"date":a=o instanceof Date;break;case"element":a=o instanceof Element;break;case"node":a=o instanceof Node;break;case"node-list":a=o instanceof NodeList;break;case"empty":a=null==o||""===o||Array.isArray(o)&&0===o.length||O(o)&&0===Object.keys(o).length;break;default:a=o?.constructor?.name?.toLowerCase()===s}const c=this.success(a,"boolean");return this.trackPerformance(e,t,c,r),c}catch(n){const o=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,o,r),o}}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 _t={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":S(e)?e:O(e)?JSON.stringify(e):e+"",Boolean:e=>{if(N(e))return e;if(null==e)return!1;if(S(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return T(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(T(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(T(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(!T(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=_t.Number(e);return Math.trunc(t)},Float:e=>{const t=_t.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(S(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)}return new Date(e)},JSON:e=>{try{return JSON.stringify(e)}catch(e){return"{}"}},Object:e=>{if(O(e))return e;if(S(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{S(e)||(e=_t.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>S(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:_t.String(e)).join(""):e instanceof Element?e.outerHTML:_t.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return Pt(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=Bt(e))}),r}return{}},"Values:Form":(e,t)=>{const r=_t.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=_t.Values(e,t);return JSON.stringify(r)}};function Pt(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Bt(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}function Bt(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}function qt(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}const Ft={name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:e}=qt(n);return _t.Number(r).toFixed(e||2)}let o=_t[n];if(o)return o(r,e);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(o=_t[i],o)?o(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>W(e,2,"as","value, type")??J(e,1,"as","conversion type")},Ht={name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!S(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return S(r);case"number":return T(r)&&!isNaN(r);case"boolean":return N(r);case"object":return O(r);case"array":return Array.isArray(r);case"function":return C(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||O(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>W(e,2,"is","value, type")??J(e,1,"is","type")},Ut={name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>W(e,1,"async","expression")},Wt={as:Ft,is:Ht,async:Ut};var Jt=Object.freeze({__proto__:null,AsExpression:Dt,asExpression:Ft,asyncExpression:Ut,conversionExpressions:Wt,createAsExpression:function(){return new Dt},defaultConversions:_t,getFormValues:function(e){const t=new FormData(e),r={};for(const[e,n]of t.entries())void 0!==r[e]?(Array.isArray(r[e])||(r[e]=[r[e]]),r[e].push(n)):r[e]=n;return r},getFormValuesProcessed:Pt,getInputValue:Bt,isExpression:Ht,parseFixedPrecision:qt});const zt={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"},Zt=se({collection:ce().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Gt=se({collection:ce().describe("Collection to access"),index:oe().describe("Index position to access")}).strict(),Xt=se({collection:ce().describe("Collection to select random item from")}).strict();class Yt extends fe{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=Zt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection),i=o.length>0?o[0]:void 0,s={success:!0,value:i,type:zt[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,s,r),s}catch(n){const o=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Kt extends fe{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=Zt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection),i=o.length>0?o[o.length-1]:void 0,s={success:!0,value:i,type:zt[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,s,r),s}catch(n){const o=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function Qt(){return new Yt}function er(){return new Kt}Qt(),er(),new class extends fe{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=Gt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection),i=this.normalizeIndex(t.index,o.length),s=i>=0&&o.length>i?o[i]:void 0,a={success:!0,value:s,type:zt[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,a,r),a}catch(n){const o=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}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 fe{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=Xt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection);if(0===o.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,n,r),n}const i=o[this.getSecureRandomIndex(o.length)],s={success:!0,value:i,type:zt[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,s,r),s}catch(n){const o=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}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 tr={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const r=void 0!==t?t:e.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:S(r)?r.length>0?r[0]:null:O(r)&&"length"in r&&T(r.length)&&r.length>0?r[0]:null},validate:e=>X(e,1,"first","collection")},rr={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const e=r.children;return e.length>0?e[e.length-1]:null}return S(r)?r.length>0?r[r.length-1]:null:O(r)&&"length"in r&&T(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>X(e,1,"last","collection")},nr={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!T(r))throw Error("Index must be a number");const o=r,i=void 0!==n?n:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>o?e.length+o:o;return t>=0&&e.length>t?e[t]:null}if(S(i)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(O(i)&&"length"in i&&T(i.length)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>Y(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)},or={name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[r,n]=t,o=n||e.me;return o&&o instanceof Element?r?sr(o,r):o.nextElementSibling:null},validate:e=>X(e,2,"next","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},ir={name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[r,n]=t,o=n||e.me;return o&&o instanceof Element?r?ar(o,r):o.previousElementSibling:null},validate:e=>X(e,2,"previous","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")};function sr(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;const e=r.querySelector(t);if(e)return e;r=r.nextElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?sr(n,t):null}function ar(e,t){let r=e.previousElementSibling;for(;r;){const e=Array.from(r.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(r.matches(t))return r;r=r.previousElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?ar(n,t):null}const cr={name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[r,n,o]=t,i=o||e.me;if(!(i&&i instanceof Element))return null;const s=i.closest(n);return s?ur(i,r,s):null},validate:e=>Y(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")},lr={name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[r,n,o]=t,i=o||e.me;if(!(i&&i instanceof Element))return null;const s=i.closest(n);return s?fr(i,r,s):null},validate:e=>Y(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")};function ur(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=dr(e);for(const e of n)if(dr(e)>o)return e;return null}function fr(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=dr(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(o>dr(t))return t}return null}function dr(e){let t=0,r=e;for(;r&&r.parentElement;)t+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,t+=1e3;return t}const pr={first:tr,last:rr,at:nr,next:or,previous:ir,nextWithin:cr,previousWithin:lr};var mr=Object.freeze({__proto__:null,FirstExpression:Yt,LastExpression:Kt,atExpression:nr,createFirstExpression:Qt,createLastExpression:er,findNextElementInDOM:sr,findNextElementWithinContainer:ur,findPreviousElementInDOM:ar,findPreviousElementWithinContainer:fr,firstExpression:tr,getElementPosition:dr,lastExpression:rr,nextExpression:or,nextWithinExpression:cr,positionalExpressions:pr,previousExpression:ir,previousWithinExpression:lr});const hr=new Set(["__proto__","constructor","prototype"]),yr={name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[r,n]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return $(r,n);if(O(r)){if(hr.has(n))return;return r[n]}return r[n]}},validate:e=>W(e,2,"possessive","element, property")??J(e,1,"possessive","property name")},vr={name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[r]=t;if(e.me){if("string"!=typeof r)throw Error("Property name must be a string");if(e.me instanceof Element)return $(e.me,r);if(O(e.me)){if(hr.has(r))return;return e.me[r]}return e.me[r]}},validate:e=>z(e,"my","property")},gr={name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[r]=t;if(null==e.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=e.it;if(n instanceof Element)return $(n,r);if(O(n)){if(hr.has(r))return;return n[r]}return n[r]},validate:e=>z(e,"its","property")},br={name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[r]=t;if(e.you){if("string"!=typeof r)throw Error("Property name must be a string");if(e.you instanceof Element)return $(e.you,r);if(O(e.you)){if(hr.has(r))return;return e.you[r]}return e.you[r]}},validate:e=>z(e,"your","property")},wr={name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[r,n]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return $(n,r);if(O(n)){if(hr.has(r))return;return n[r]}return n[r]}},validate:e=>W(e,2,"of","property, object")??J(e,0,"of","property name")},Er={name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");const o=n||e.me;return o&&o instanceof Element?o.getAttribute(r):null},validate:e=>Y(e,1,2,"attribute","attributeName, optional element")??J(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},xr={name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[r,n,o]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=o||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(r)===n},validate:e=>Y(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??J(e,0,"attributeWithValue","attribute name")??J(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},Ar={name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,o=document.getElementsByClassName(n);return Array.from(o)},validate:e=>z(e,"classReference","className")},Sr={name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:e=>z(e,"idReference","idValue")},Tr={possessive:yr,my:vr,its:gr,your:br,of:wr,attribute:Er,attributeWithValue:xr,classReference:Ar,idReference:Sr};var Nr=Object.freeze({__proto__:null,attributeExpression:Er,attributeWithValueExpression:xr,classReferenceExpression:Ar,getElementProperty:$,idReferenceExpression:Sr,isAriaAttribute:function(e){return e.startsWith("aria-")||"aria"===e},isDataAttribute:function(e){return e.startsWith("data-")||"data"===e},itsExpression:gr,myExpression:vr,ofExpression:wr,possessiveExpression:yr,propertiesExpressions:Tr,yourExpression:br});const Or=se({value:ne().describe("String literal value")}).strict(),Cr=se({value:oe().describe("Number literal value")}).strict(),kr=se({value:ie().describe("Boolean literal value")}).strict(),jr=se({left:ce().describe("Left operand"),right:ce().describe("Right operand")}).strict();class Lr extends fe{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=Or,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid){const t=this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(e,r,!1),t}let o=t.value;(o.includes("${")||o.includes("$"))&&(o=this.interpolateString(o,e));const i=this.success(o,"string");return this.trackSimple(e,r,!0,o),i}catch(t){return this.trackSimple(e,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let r=e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=this.resolveExpression(r.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,r)=>{try{const e=this.resolveVariable(r,t);return void 0!==e?e+"":""}catch(e){return""}}),r}resolveExpression(e,t){if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):void 0}}class Ir extends fe{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Cr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?Number.isFinite(t.value)?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Rr extends fe{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=kr,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class $r extends fe{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=jr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const o=Ue(t.left,"left operand")+Ue(t.right,"right operand");return this.trackSimple(e,r,!0,o),this.success(o,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Mr extends fe{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=jr,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const o=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,r,!0,o),this.success(o,"string")}catch(t){return this.trackSimple(e,r,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=jr.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(S(e))return e;if(T(e))return""+e;if(N(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}class Dr extends fe{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=jr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const o=Ue(t.left,"left operand")*Ue(t.right,"right operand");return this.trackSimple(e,r,!0,o),this.success(o,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function Vr(){return new Lr}function _r(){return new Ir}function Pr(){return new Rr}function Br(){return new $r}function qr(){return new Mr}function Fr(){return new Dr}const Hr={stringLiteral:Vr(),numberLiteral:_r(),booleanLiteral:Pr(),addition:Br(),stringConcatenation:qr(),multiplication:Fr()};var Ur=Object.freeze({__proto__:null,AdditionExpression:$r,BooleanLiteralExpression:Rr,MultiplicationExpression:Dr,NumberLiteralExpression:Ir,StringConcatenationExpression:Mr,StringLiteralExpression:Lr,createAdditionExpression:Br,createBooleanLiteralExpression:Pr,createMultiplicationExpression:Fr,createNumberLiteralExpression:_r,createStringConcatenationExpression:qr,createStringLiteralExpression:Vr,specialExpressions:Hr});class Wr extends H{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory($e),this.registerCategory(kt),this.registerCategory(Wt),this.registerCategory(pr),this.registerCategory(Tr),this.registerCategory(Hr)}}class Jr{static toTyped(e){return{me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class zr{constructor(e,t,r){this.impl=e,this.expressionEvaluator=t??new Wr,this.hookRegistry=r??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,r={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:r,event:e.event??void 0,executionContext:e}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(e,...t){const r=t[0],n=this.createHookContext(e,t,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(d(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void d(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const o=Jr.toTyped(e);let i,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(d(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers,n=t?.when||t?.where;if(n&&!await this.expressionEvaluator.evaluate(n,e))return void d(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:t||{},commandName:r.commandName},this.expressionEvaluator,e)}else i=t;else d(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return d("CommandAdapterV2: Calling execute with parsed input:",i),s=2===this.impl.execute.length?await this.impl.execute(i,o):await this.impl.execute(o,...i),d("CommandAdapterV2: Command result:",s),Object.assign(e,Jr.fromTyped(o,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,s),s}catch(e){if(Qr(e)||d(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(n,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class Zr{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);y(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=t.toLowerCase();y(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,e);const n=new zr(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),_e.add(r);const o=e.metadata?.aliases;if(o&&Array.isArray(o))for(const t of o){const r=t.toLowerCase();this.implementations.set(r,e),this.adapters.set(r,n),_e.add(r)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const r=this.getAdapter(e);return r?r.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Gr=null;function Xr(){return Gr||(Gr=function(e){const t=e?.commands??new Zr,r=e?.eventSources??new E,n=e?.context??new x,o=new Set,i={commands:t,eventSources:r,context:n,use(e){if(o.has(e.name))console.warn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const r of e.commands)t.register(r);if(e.eventSources)for(const t of e.eventSources)r.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:r,options:o}of e.contextProviders)n.register(t,r,o);e.setup?.(i),o.add(e.name)}},reset(){o.clear()}};return i}()),Gr}class Yr{constructor(e={}){this.contextCache=new WeakMap;const t=Xr();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,y(`[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),y(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return y("[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 y(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return y(`[RegistryIntegration] Found event source '${r}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(e,t,r);if(!n)throw Error(`Failed to subscribe to event source '${e}'`);return y(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,y("[RegistryIntegration] Destroyed")}}function Kr(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 Qr(e){return e instanceof Error&&(null!==r(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function en(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 tn(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const rn=new WeakMap;class nn{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionEvaluator=e.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=g,this.hookRegistry=new t,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new v,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Yr("object"==typeof e.registryIntegration?e.registryIntegration:{}),y("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),install:async(e,t,r)=>await this.installBehaviorOnElement(e,t,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const r of e)for(const e of r.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&y(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),y("RuntimeBase: Destroyed")}async execute(e,t){y(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,r)=>this.execute(e,r||t));try{switch(e.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(e,t);if(!i(r))throw Kr(r.error);return r.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const r={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(r,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=e,n=await this.executeCommandSequenceWithResult(r.commands||[],t);if(!i(n))throw Kr(n.error);return n.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(e,t);if(!i(r))throw Kr(r.error);return r.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:r,args:n,modifiers:o}=e,i=r.toLowerCase();if(d(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const e=await this.registry.getAdapter(i);if(!e)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:n||[],modifiers:o||{},commandName:i,runtime:this})}catch(e){throw Qr(e)||console.error(`Error executing command '${i}':`,e),e}}const s=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(s),Error(s)}toSignal(e){const t=r(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:r,args:i,modifiers:s}=e,a=r.toLowerCase();if(d(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(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 n(await c.execute(t,{args:i||[],modifiers:s||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return o(t);throw console.error(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let r;for(const o of e)if("command"===o.type){const e=await this.processCommandWithResult(o,t);if(!i(e)){const r=e.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==r.returnValue&&Object.assign(t,{it:r.returnValue,result:r.returnValue}),n(r.returnValue)}}r=e.value}else{const e=await this.evaluateExpressionWithResult(o,t);if(!i(e))return e;r=e.value}return n(r)}async evaluateExpression(e,t){const r=await this.expressionEvaluator.evaluate(e,t);return tn(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const r=await this.expressionEvaluator.evaluateWithResult(e,t);if(!i(r))return r;const s=r.value;if(tn(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return n(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return o(t);throw e}}return n(s)}async executeCommandFromPattern(e,t,r){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},r)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let r;const n=[],o=[],i=[];for(const t of e.statements)"eventHandler"===t.type?n.push(t):"initBlock"===t.type?o.push(t):i.push(t);for(const e of n)try{await this.execute(e,t)}catch(e){if(Qr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of o)try{r=await this.execute(e,t)}catch(e){if(Qr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(Qr(e)&&(e.isHalt||e.isExit))break;throw e}return r}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const r of e.commands)try{await this.execute(r,t)}catch(e){if(Qr(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let r;for(const n of e.commands)try{r=await this.execute(n,t)}catch(e){if(Qr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return r}async executeObjectLiteral(e,t){const r={};if(!e.properties)return r;for(const n of e.properties){let e;e="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,t)+"";const o=await this.execute(n.value,t);r[e]=o}return r}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:r,parameters:n,eventHandlers:o,initBlock:i}=e,s=e.imperativeInstaller;"function"==typeof s?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:s}),y(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:o,initBlock:i}),y(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(e,t,r){y("BEHAVIOR: installBehaviorOnElement called: "+e);const n=this.behaviorRegistry.get(e);if(!n)throw Error(`Behavior "${e}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return y(`BEHAVIOR: Installing imperative behavior '${e}'`),n.install(t,r),void y(`BEHAVIOR: Finished installing imperative behavior '${e}'`);y("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const o={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(o);if(n.parameters)for(const e of n.parameters)i.locals.set(e,e in r?r[e]:void 0);for(const[e,t]of Object.entries(r))n.parameters?.includes(e)||i.locals.set(e,t);if(n.initBlock){y("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),y("BEHAVIOR: Init block completed for "+e)}catch(t){if(y(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&Qr(t)))throw t}}if(y(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers){const t=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}y("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:r,events:n,commands:o,target:i,args:s,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,f=n&&n.length>0?n:[r];y(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let d=[],p=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)p=window;else if("document"===e||"the document"===e||"body"===e)p=document;else if("me"===e||"myself"===e)d=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);y(`BEHAVIOR: Target resolution: found local '${i}', 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 y(`BEHAVIOR: Target resolution: querying for '${i}'`),d=this.queryElements(i,t)}else d=t.me?[t.me]:[];if(0===d.length&&!p)return void y(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(d,c,o,t);if("change"===r&&l)return void this.setupChangeObserver(l,o,t);const m=e.customEventSource;if(m&&this.registryIntegration){y(`BEHAVIOR: executeEventHandler - Using custom event source '${m}' for event '${r}'`);const e=async e=>{const n=new Map(t.locals),i={...t,locals:n,it:e,event:e},s=this.enhanceContext(i);y(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:o},s)}catch(e){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,e)}};try{const n=this.registryIntegration.subscribeToEventSource(m,{event:r,handler:e,target:i,selector:a},t);y(`BEHAVIOR: Subscribed to custom event source '${m}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${m}' subscription ${n.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${m}':`,e)}return}const h=nn.createEventHandler(this,o,t,a,s);let v,g=null;if(u){let e=h;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let r;v=n=>{r&&clearTimeout(r),r=setTimeout(()=>e(n),t)},g=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const t=u.throttle;let r=0;v=n=>{const o=Date.now();t>o-r||(r=o,e(n))}}else v=e}else v=h;const b=u?.once?{once:!0}:void 0;if(p){for(const e of f)p.addEventListener(e,v,b),d.length>0?this.cleanupRegistry.registerListener(d[0],p,e,v):this.cleanupRegistry.registerGlobal(()=>p.removeEventListener(e,v),"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)e.addEventListener(t,v,b),this.cleanupRegistry.registerListener(e,e,t,v);g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,r,n,o){return async i=>{const s=rn.get(i)??0;if(s>=100)return;if(rn.set(i,s+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{y(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const a=new Map(r.locals),c={...r,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=e.enhanceContext(c);if(o&&o.length>0){const e=i,t=e.detail;for(const r of o)l.locals.set(r,e[r]??t?.[r]??null)}for(const r of t)try{const t=en(await e.execute(r,l));void 0!==t&&Object.assign(l,{it:t,result:t})}catch(e){if(Qr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(l,{it:e.returnValue,result:e.returnValue});break}}throw console.error("COMMAND FAILED:",e),e}}}setupMutationObserver(e,t,r,n){y(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const o of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){p(`MUTATION DETECTED: attribute '${t}' changed on`,o);const e={...n,me:o,it:i,locals:new Map(n.locals)},s=i.oldValue,a=o.getAttribute(t);e.locals.set("oldValue",s),e.locals.set("newValue",a);const c=this.enhanceContext(e);for(const e of r)try{await this.execute(e,c)}catch(e){if(Qr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing mutation handler command:",e)}}});e.observe(o,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(o,e),y("RUNTIME BASE: MutationObserver attached to",o,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){y("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(e,r);let o=[];this.isElement(n)?o=[n]:Array.isArray(n)&&(o=n.filter(e=>this.isElement(e))),y(`RUNTIME BASE: Watching ${o.length} target elements for content changes`);for(const e of o){const n=new MutationObserver(async n=>{for(const o of n)if("childList"===o.type||"characterData"===o.type){p("CONTENT CHANGE DETECTED on",e,"mutation type:",o.type);const n={...r,me:r.me,it:o,locals:new Map(r.locals)};n.locals.set("target",e);const i=o.oldValue,s=e.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",s);const a=this.enhanceContext(n);for(const e of t)try{await this.execute(e,a)}catch(e){if(Qr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing change handler command:",e)}}});n.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),y("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let o=e;o.startsWith("<")&&o.endsWith("/>")&&(o=o.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(o))}catch{return y(`queryElements: invalid CSS selector '${o}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}const on={core:["references","logical","special"],common:["properties","conversion"],optional:["positional"]};class sn extends H{constructor(e={}){super(),this.loadedCategories=new Set,this.loadPromises=new Map,this.options={preload:"core",...e},"none"!==this.options.preload&&this.preloadExpressions()}async preloadExpressions(){if(this.options.categories)await Promise.all(this.options.categories.map(e=>this.loadCategory(e)));else switch(this.options.preload){case"all":await this.preloadTier("core"),await this.preloadTier("common"),await this.preloadTier("optional");break;case"common":await this.preloadTier("core"),await this.preloadTier("common");break;case"core":await this.preloadTier("core")}}async preloadTier(e){const t=on[e];await Promise.all(t.map(e=>this.loadCategory(e)))}async loadCategory(e){if(this.loadedCategories.has(e))return;if(this.loadPromises.has(e))return this.loadPromises.get(e);const t=this.l(e);this.loadPromises.set(e,t);try{await t,this.loadedCategories.add(e),h("✅ Loaded expression category: "+e)}finally{this.loadPromises.delete(e)}}async l(e){try{let t;switch(h("📦 Loading expression category: "+e),e){case"references":t=await Promise.resolve().then(function(){return Me});break;case"logical":t=await Promise.resolve().then(function(){return jt});break;case"special":t=await Promise.resolve().then(function(){return Ur});break;case"properties":t=await Promise.resolve().then(function(){return Nr});break;case"conversion":t=await Promise.resolve().then(function(){return Jt});break;case"positional":t=await Promise.resolve().then(function(){return mr});break;default:return void console.warn("Unknown expression category: "+e)}const r=t[e+"Expressions"]||t.default;if(!r)return void console.warn("No expressions found in category: "+e);this.registerCategory(r),h(` ✓ Registered ${Object.keys(r).length} expressions from ${e}`)}catch(t){throw console.error("Failed to load expression category: "+e,t),t}}getCategoryForNodeType(e){return{identifier:"references",selector:"references",dollarExpression:"references",binaryExpression:"logical",unaryExpression:"logical",comparison:"logical",literal:"special",string:"special",numberLiteral:"special",stringLiteral:"special",booleanLiteral:"special",arrayLiteral:"special",objectLiteral:"special",templateLiteral:"special",memberExpression:"properties",possessiveExpression:"properties",propertyAccess:"properties",propertyOfExpression:"properties",asExpression:"conversion",positional:"positional",callExpression:"references"}[e]||null}async evaluate(e,t){if(!e)return h("LAZY EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("LAZY EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));const r=this.getCategoryForNodeType(e.type);return r&&!this.loadedCategories.has(r)&&(h(`🔄 Auto-loading category for node type: ${e.type} → ${r}`),await this.loadCategory(r)),super.evaluate(e,t)}async warmupExpressions(e){h("🔥 Warming up expression categories: "+e.join(", ")),await Promise.all(e.map(e=>this.loadCategory(e)))}getLoadedCategories(){return Array.from(this.loadedCategories)}}function an(e,t,r,n,o,i){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?n.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),d=!1,p=r.length-1;p>=0;p--){var m={};for(var h in n)m[h]="access"===h?{}:n[h];for(var h in n.access)m.access[h]=n.access[h];m.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var y=(0,r[p])("accessor"===c?{get:f.get,set:f.set}:f[l],m);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=s(y.get))&&(f.get=a),(a=s(y.set))&&(f.set=a),(a=s(y.init))&&o.unshift(a)}else(a=s(y))&&("field"===c?o.unshift(a):f[l]=a)}u&&Object.defineProperty(u,n.name,f),d=!0}function cn(e,t,r){for(var n=arguments.length>2,o=0;t.length>o;o++)r=n?t[o].call(e,r):t[o].call(e);return n?r:void 0}function ln(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}"function"==typeof SuppressedError&&SuppressedError;const un=Symbol("command:name"),fn=Symbol("command:category"),dn=Symbol("command:metadata");function pn(e){return function(t,r){const n=t;n[un]=e.name,n[fn]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function mn(e){return function(t,r){const n=t,o=n[fn];if(!o)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const i={description:e.description,syntax:e.syntax,examples:e.examples,category:o,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};n[dn]=i,Object.defineProperty(t,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function hn(e){return()=>new e}function yn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function vn(e,t){if(yn(e))return e;if(!e){const e=t.me;if(!e)throw Error("No target element - provide explicit target or ensure context.me is set");return bn(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return bn(t.me)}if("it"===r){if(!yn(t.it))throw Error('Context reference "it" is not an HTMLElement');return t.it}if("you"===r){if(!t.you)throw Error('Context reference "you" is not available');return bn(t.you)}const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const o=n.querySelector(r);if(!o)throw Error("Element not found with selector: "+r);if(!yn(o))throw Error("Element found but is not an HTMLElement: "+r);return o}throw Error("Invalid target type: "+typeof e)}function gn(e,t){if(Array.isArray(e))return e.filter(yn);if(e instanceof NodeList)return Array.from(e).filter(yn);if(yn(e))return[e];if(!e){const e=t.me;return e&&yn(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&yn(t.me)?[t.me]:[];if("it"===r)return yn(t.it)?[t.it]:[];if("you"===r)return t.you&&yn(t.you)?[t.you]:[];const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let e=r;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.querySelectorAll(e);return Array.from(t).filter(yn)}}return[]}function bn(e){if(yn(e))return e;throw Error("Value is not an HTMLElement")}function wn(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!yn(t.me))throw Error("context.me is not an HTMLElement");return t.me;case"its":case"it":if(!t.it)throw Error('No "it" value in context');if(!yn(t.it))throw Error("context.it is not an HTMLElement");return t.it;case"your":case"you":if(!t.you)throw Error('No "you" element in context');if(!yn(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const En=["on","from","to","in","with","at"];async function xn(e,t,r,n,o={},i){let s=e;if(o.filterPrepositions&&e&&(s=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!En.includes(t.name.toLowerCase())})),(!s||0===s.length)&&o.fallbackModifierKey&&i){const e=i[o.fallbackModifierKey];e&&(s=[e])}if(!s||0===s.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!yn(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const e of s){const o=await t.evaluate(e,r);if(""!==o&&("string"!=typeof o||""!==o.trim()))if(yn(o))a.push(o);else if(o instanceof NodeList){const e=Array.from(o).filter(yn);a.push(...e)}else if(Array.isArray(o)){const e=o.filter(yn);a.push(...e)}else{if("string"!=typeof o)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof o}`);try{let e=o;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const n=t.querySelectorAll(e),i=Array.from(n).filter(yn);a.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${o}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!yn(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}class An{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await xn(e.args,t,r,n)}}(e,t,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>yn(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const r=e.dataset.originalDisplay;void 0!==r?(e.style.display=r||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let Sn=(()=>{let e,t,r=[mn({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),pn({name:"hide",category:"dom"})],n=[],o=An;return t=class extends o{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=>yn(e))}},ln(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const Tn=hn(Sn);let Nn=(()=>{let e,t,r=[mn({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),pn({name:"show",category:"dom"})],n=[],o=An;return t=class extends o{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const r=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,r)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>yn(e))&&"string"==typeof t.defaultDisplay}},ln(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const On=hn(Nn);function Cn(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function kn(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),r=e.indexOf("=");if(-1===r)return{name:e.trim()};const n=e.slice(0,r).trim();let o=e.slice(r+1).trim();return(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),{name:n,value:o}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function jn(e,t){for(const r of e)t(r);return e}function Ln(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function In(e,t,r){const n=e.hasAttribute(t);void 0!==r?n&&e.getAttribute(t)===r?e.removeAttribute(t):e.setAttribute(t,r):n?e.removeAttribute(t):e.setAttribute(t,"")}function Rn(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&&Mn(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&&Mn(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&Mn(r)?[r]:[]}function $n(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function Mn(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!$n(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Dn(e,t){return e.map(e=>{if($n(e)){const r=function(e){const t=e.trim(),r=t.match(/^\{(.+)\}$/);return r?r[1].trim():t}(e),n=t.locals.get(r)??t.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return e}).filter(e=>e.length>0)}function Vn(e){return"string"==typeof e&&e.trim().startsWith("*")}function _n(e,t,r){e.style.setProperty(t,r)}const Pn=["dialog","details","summary","select"];function Bn(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 qn(e,t,r){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const r=Bn(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const r=Bn(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:Bn(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=Bn(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(n=e,"attributeAccess"===n.type?"@"+n.attributeName:Bn(n)),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1};var n}class Fn{async resolveTargets(e,t,r,n){return xn(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return qn(e,t,r)}parseClassNames(e){return Rn(e)}isAttribute(e){return Cn(e.trim())}isCSSProperty(e){return Vn(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>yn(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 Hn=(()=>{let e,t,r=[mn({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"]}),pn({name:"add",category:"dom"})],n=[],o=Fn;return t=class extends o{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if("string"==typeof n){const o=n.trim();if(this.isAttribute(o)){const{name:n,value:i}=function(e){const t=kn(e);return{name:t.name,value:t.value??""}}(o);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}if(this.isCSSProperty(o)){const n=o.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const i=await t.evaluate(e.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,r,e.modifiers)}}}const o=this.parseClassNames(n);if(0===o.length)throw Error("add command: no valid class names found");return{type:"classes",classes:o,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const r=Dn(e.classes,t);r.length>0&&Ln(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,jn(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":!function(e,t){Ln(e,Object.entries(t),(e,[t,r])=>{e.style.setProperty(t,r)})}(e.targets,e.styles)}var r,n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const r=t.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(e=>"string"==typeof e))return!1}return!0}},ln(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const Un=hn(Hn);function Wn(e){return!!e.parentNode&&(e.remove(),!0)}let Jn=(()=>{let e,t,r=[mn({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"]}),pn({name:"remove",category:"dom"})],n=[],o=Fn;return t=class extends o{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if(yn(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&yn(n[0]))return{type:"element",targets:n.filter(e=>yn(e))};if("string"==typeof n){const o=n.trim();if(this.isAttribute(o))return{type:"attribute",name:kn(o).name,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if(this.isCSSProperty(o))return{type:"styles",properties:[o.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}const o=this.parseClassNames(n);if(0===o.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:o,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const r=Dn(e.classes,t);r.length>0&&Ln(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,jn(e.targets,e=>{e.removeAttribute(r)});break;case"styles":!function(e,t){Ln(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)Wn(t)}var r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}},ln(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const zn=hn(Jn);function Zn(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function Gn(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=Zn(e);return r?r.milliseconds:t}return t}function Xn(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=Zn(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function Yn(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 Kn(e,t){let r=0;for(let n=0;e.length>n;n++)r=Math.max(r,(e[n]||0)+(t[n]||0));return r}function Qn(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function eo(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&In(e,r)}}function to(e,t,r,n){const o=eo(e,t,r),i=setTimeout(o,n);return()=>{clearTimeout(i)}}function ro(e,t,r,n){const o=eo(e,t,r),i=()=>{o(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function no(e,t,r){if(t.startsWith("@")){const n=t.substring(1);return void(!1===r?e.removeAttribute(n):e.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(t){case"textContent":return void(e.textContent=n);case"innerHTML":return void(e.innerHTML=n);case"innerText":return void(e.innerText=n);case"id":return void(e.id=n);case"className":return void(e.className=n);case"value":return void("value"in e&&(e.value=n));case"checked":return void("checked"in e&&(e.checked=!!r))}if(t.includes(".")){const n=t.split(".");let o=e;for(let e=0;n.length-1>e;e++)if(o=o[n[e]],null==o)return;return void(o[n[n.length-1]]=r)}if(t.includes("-")||t in e.style)e.style.setProperty(t,n);else try{e[t]=r}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function oo(e){return null==e||""===e}const io=/^the\s+(.+?)\s+of\s+(.+)$/i,so=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 ao(e){return"string"==typeof e&&io.test(e)}function co(e,t){const r=e.match(io);if(!r)return null;try{return{element:vn(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function lo(e,t,r){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,r){const n=e.property?.name;if(!n)return null;let o=await t.evaluate(e.target,r);return Array.isArray(o)&&(o=o[0]),yn(o)?{element:o,property:n}:null}(e,t,r);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,r){const n="string"==typeof e.property?e.property:e.property?.name;if(!n)return null;let o=await t.evaluate(e.object,r);return Array.isArray(o)&&(o=o[0]),yn(o)?{element:o,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const e=n.object,o=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!yn(i))return null;const s=o?.name||o?.value;return s&&(s.startsWith("@")||s.startsWith("*"))?{element:i,property:s}:null}return null}function uo(e,t){const{element:r,property:n}=e;n.startsWith("*")?_n(r,n.substring(1),t+""):no(r,n,t)}async function fo(e,t,r){let n,o;if(e?.for){const o=await t.evaluate(e.for,r);n="number"==typeof o?o:"string"==typeof o?Gn(o):void 0}if(e?.until){const n=await t.evaluate(e.until,r);"string"==typeof n&&(o=n)}return{duration:n,untilEvent:o}}function po(e,t){const r=t?.name,n=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return Pn.includes(t)}(t)}(t);if(yn(e)||Array.isArray(e)&&e.every(e=>yn(e)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return Pn.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const mo=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"toggle",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("toggle command requires an argument");const n=e.args[0],o=n?.name;if("between"===o&&e.args.length>=4){const{duration:n,untilEvent:o}=await fo(e.modifiers,t,r),i=await t.evaluate(e.args[1],r),s=await t.evaluate(e.args[3],r),a=[];for(let t=4;e.args.length>t;t++){const r=e.args[t]?.name;"on"!==r&&"from"!==r&&a.push(e.args[t])}const c={filterPrepositions:!0,fallbackModifierKey:"on"},l=await xn(a,t,r,"toggle",c,e.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(s+"").replace(/^\./,""),targets:l,duration:n,untilEvent:o}}const i=await lo(n,t,r);if(i)return{type:"property",target:i};const{duration:s,untilEvent:a}=await fo(e.modifiers,t,r),{value:c}=await qn(n,t,r);if(ao(c)){const e=co(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=po(c,n),f={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:o}=kn(u);return{type:"attribute",name:n,value:o,targets:await xn(e.args.slice(1),t,r,"toggle",f,e.modifiers),duration:s,untilEvent:a}}case"css-property":{const n=function(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const r=t.substring(1).trim();return r?{property:r}:null}(e);if(!t)return null;const r=t.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await xn(e.args.slice(1),t,r,"toggle",f,e.modifiers)}}case"element":{let o;if(yn(c))o=[c];else if(Array.isArray(c)&&c.every(e=>yn(e)))o=c;else if(u){const e=document.querySelectorAll(u);o=Array.from(e).filter(e=>yn(e))}else o=await xn([n],t,r,"toggle",f,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(o);if("dialog"===i){const n=await async function(e,t,r,n){if(t?.as){const e=await r.evaluate(t.as,n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await r.evaluate(e[1],n);if("string"==typeof t){const o=t.toLowerCase();if("modal"===o||"as modal"===o)return"modal";if("as"===o&&e.length>=3){const t=await r.evaluate(e[2],n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,r);return{type:"dialog",mode:n,targets:o}}return"details"===i?{type:"details",targets:Qn(o)}:"select"===i?{type:"select",targets:o}:{type:"classes",classes:Rn(u),targets:o,duration:s,untilEvent:a}}default:{const n=Rn(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await xn(e.args.slice(1),t,r,"toggle",f,e.modifiers),duration:s,untilEvent:a}}}}async execute(e,t){switch(e.type){case"classes":{const r=Dn(e.classes,t);if(0===r.length)return[...e.targets];if(Ln(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&to(t,"class",r[0],e.duration),e.untilEvent&&ro(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,jn(e.targets,e=>{In(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&to(t,"attribute",e.name,e.duration),e.untilEvent&&ro(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return jn(e.targets,t=>function(e,t){const r=window.getComputedStyle(e);switch(t){case"display":"none"===r.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=r.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:r}=e;return r.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,r.substring(1)):$(t,r)}(e),r=e.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof t||so.has(n)||so.has(n.toLowerCase())){const r=!t;return uo(e,r),r}if("number"==typeof t){const r=0===t?1:0;return uo(e,r),r}if("string"==typeof t){const n="__ht_"+r,o=e.element[n];return""===t&&void 0!==o?(uo(e,o),o):(e.element[n]=t,uo(e,""),"")}uo(e,!t)}(e.target),[e.target.element];case"dialog":return jn(e.targets,t=>{return n=e.mode,void((r=t).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return jn(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return jn(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const r=t.classList.contains(e.classA),n=t.classList.contains(e.classB);r?(t.classList.remove(e.classA),t.classList.add(e.classB)):n?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&to(t,"class",e.classA,e.duration),e.untilEvent&&ro(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},ln(t,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());const ho=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"put",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("put requires arguments");const n=e=>e?.type||"unknown",o=["into","before","after","at","at start of","at end of"];let i=-1,s=null;for(let t=0;e.args.length>t;t++){const r=e.args[t],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&o.includes(c)){i=t,s=c;break}}let a=null,c=null;if(-1===i)if(e.modifiers.into||e.modifiers.before||e.modifiers.after){const t=e.modifiers.into?"into":e.modifiers.before?"before":"after";a=e.args[0],s=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],s=e.args[1]?.value||e.args[1]?.name||"into"}else a=e.args[0],s=e.args[1]?.value||e.args[1]?.name||null,c=e.args[2];else a=e.args.slice(0,i)[0]||null,c=e.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!s)throw Error("put requires position keyword");const l=await t.evaluate(a,r),u=this.mapPosition(s);let f,d,p=null;if(c){const e=n(c),o=await lo(c,t,r);if(o)return{value:l,targets:[o.element],position:"replace",memberPath:o.property};if("memberExpression"===e){const e=c.object,n=c.property;if("selector"===e?.type?p=e.value:"identifier"===e?.type&&(p=e.name),p&&n?.name)f=n.name;else{const e=await t.evaluate(c,r);"string"==typeof e&&(p=e)}}else if("identifier"===e&&"me"===c.name)p=null;else if("selector"===e||"cssSelector"===e)p=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&ao(e)){const t=co(e,r);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?p=e:d=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))p=e;else{const n=await t.evaluate(c,r),o=this.resolveEvaluatedAsElements(n);if(o)return{value:l,targets:o,position:u,memberPath:f};d=e}}else{const e=await t.evaluate(c,r),n=this.resolveEvaluatedAsElements(e);if(n)return{value:l,targets:n,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?p=e:d=e)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(p,r),position:u,memberPath:f}}async execute(e,t){const{value:r,targets:n,position:o,memberPath:i,variableName:s}=e;if(s)return t.locals&&t.locals.set(s,r),t[s]=r,void Object.assign(t,{it:r});if(i)for(const e of n)this.setProperty(e,i,r);else for(const e of n){const t=this.parseValue(r);this.insertContent(e,t,o)}return n}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!yn(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>yn(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return yn(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(yn(t)){const n=t;switch(r){case"beforebegin":e.parentElement?.insertBefore(n,e);break;case"afterbegin":e.insertBefore(n,e.firstChild);break;case"beforeend":e.appendChild(n);break;case"afterend":e.parentElement?.insertBefore(n,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t);else yn(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(yn(e))return[e];if(Array.isArray(e)){const t=e.filter(yn);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(yn);return t.length>0?t:null}return null}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,r){const n=t.split(".");let o=e;for(let e=0;n.length-1>e;e++){if(!o[n[e]])throw Error(`Property path "${t}" does not exist`);o=o[n[e]]}o[n[n.length-1]]=r}},ln(t,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());function yo(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 vo(e,t,r){return"global"===r&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==r&&t.locals&&t.locals.has(e)?t.locals.get(e):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===r&&t.locals&&t.locals.has(e)?t.locals.get(e):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function go(e,t,r,n){if("global"===n)return r.globals.set(e,t),void("undefined"!=typeof window&&(window[e]=t));if(r.locals&&r.locals.has(e))r.locals.set(e,t);else{if(r.globals&&r.globals.has(e))return r.globals.set(e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(!r.variables||!r.variables.has(e))return"undefined"!=typeof window&&e in window?(window[e]=t,void r.globals.set(e,t)):void r.locals.set(e,t);r.variables.set(e,t)}}function bo(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:vo(e,t)}const wo=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"make",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){const n=e.args.length>0?await t.evaluate(e.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const o=void 0!==e.modifiers.an?"an":"a",i=await async function(e,t,r){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const n=[];for(const o of e.args)n.push(await t.evaluate(o,r));return n}const n=await t.evaluate(e,r);return Array.isArray(n)?n:[n]}(e.modifiers.from,t,r),s=await async function(e,t,r){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const n=await t.evaluate(e,r);return"string"==typeof n?n:n+""}(e.modifiers.called,t,r);return{article:o,expression:n,constructorArgs:i,variableName:s}}async execute(e,t){const{expression:r,constructorArgs:n=[],variableName:o}=e,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(e){const t=e.slice(1,-2);let r="div",n=t;const o=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);o&&(r=o[1],n=t.slice(o[0].length));const i=document.createElement(r),s=n.split(/(?=[.#])/);for(const e of s)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(r):function(e,t,r){if(yn(e))return e;const n=e+"";let o;if("undefined"!=typeof window&&(o=window[n]),o||"undefined"==typeof global||(o=global[n]),!o&&r.variables?.has(n)&&(o=r.variables.get(n)),!o||"function"!=typeof o)throw Error(`Constructor '${n}' not found or is not a function`);return 0===t.length?new o:new o(...t)}(r,n,t);return Object.assign(t,{it:i}),o&&go(o,i,t),i}},ln(t,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());function Eo(e,t,r){return e?new Promise(r=>{const n=Ao(()=>{e.removeEventListener(t,o)},r),o=e=>{n({event:e,timedOut:!1,cancelled:!1})};e.addEventListener(t,o)}):Promise.reject(Error("waitForEvent: no target provided"))}function xo(e){return new Promise(t=>setTimeout(t,e))}function Ao(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}const So=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"wait",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,r);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r);const n=e.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,e.args[1],t,r):this.parseTimeWait(e.args[0],t,r)}async execute(e,t){const r=Date.now();if("time"===e.type)return await xo(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,o=(await Eo(n,e.eventName)).event;if(Object.assign(t,{it:o}),e.destructure)for(const r of e.destructure)r in o&&t.locals.set(r,o[r]);return{type:"event",result:o,duration:Date.now()-r}}const{result:n,winningCondition:o}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:n}),n instanceof Event&&"event"===o?.type&&o.destructure)for(const e of o.destructure)e in n&&t.locals.set(e,n[e]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(e,t,r){return{type:"time",milliseconds:Xn(await t.evaluate(e,r))}}async parseEventWait(e,t,r,n){const o=await r.evaluate(e,n);if("string"!=typeof o)throw Error("wait for: event name must be a string");const i=o.match(/^(\w+)\(([^)]+)\)$/),s=i?i[1]:o,a=i?i[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await r.evaluate(t,n);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=n.me??void 0;return{type:"event",eventName:s,target:c,destructure:a}}async parseEventArrayWait(e,t,r,n){const o=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",r=[];for(const n of e.properties){const e=n.key?.name||n.key?.value;"name"===e&&n.value?t=n.value.value||"":"args"===e&&n.value?.elements&&(r=n.value.elements.map(e=>e.value||e.name||""))}t&&o.push({name:t,params:r})}}let i;if(t){const e=await r.evaluate(t,n);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=n.me??void 0),1===o.length?{type:"event",eventName:o[0].name,target:i,destructure:o[0].params.length>0?o[0].params:void 0}:{type:"race",conditions:o.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,r){const n=[];e.modifiers.for?n.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r)):e.args[0]&&n.push(await this.parseTimeWait(e.args[0],t,r));const o=await t.evaluate(e.modifiers.or,r),i=Array.isArray(o)?o:[o];for(const e of i)try{n.push({type:"time",milliseconds:Xn(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);n.push(t?{type:"event",eventName:t[1],target:r.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(e,t){const r=e.map(e=>"time"===e.type?xo(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Eo(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},ln(t,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),To=new Map;const No=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"fetch",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("fetch requires a URL");return{url:await this.parseURL(e.args[0],t,r),responseType:this.parseResponseType(e.modifiers.as),options:await this.parseRequestOptions(e.modifiers.with,t,r)}}async execute(e,t){const r=Date.now(),{url:n,responseType:o,options:i}=e,s=new AbortController;let a;t.me&&(a=()=>s.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...i,signal:s.signal},l=To.get(o);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>s.abort(),i.timeout));try{let e=await fetch(n,c);if(t.me){const r={response:e};this.dispatchEvent(t.me,"fetch:afterResponse",r),e=r.response}const i=await this.handleResponse(e,o,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:i});const s={status:e.status,statusText:e.statusText,headers:e.headers,data:i,url:e.url,duration:Date.now()-r};return Object.assign(t,{it:i}),s}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+n);throw Error(`Fetch failed for ${n}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,r){const n=await t.evaluate(e,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(To.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,r){if(!e)return{};const n=await t.evaluate(e,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const o={};return"method"in n&&(o.method=(n.method+"").toUpperCase()),"headers"in n&&(o.headers=this.parseHeaders(n.headers)),"body"in n&&(o.body=this.parseBody(n.body)),"credentials"in n&&(o.credentials=n.credentials),"mode"in n&&(o.mode=n.mode),"cache"in n&&(o.cache=n.cache),o}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[r,n]of Object.entries(e))t.set(r,n+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,r){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const n=To.get(t);return n?n.handler(e,r):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),r=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),1===r.childNodes.length&&yn(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},ln(t,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),Oo=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"set",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("set command requires a target");const n=e.args[0],o=n?.name||n?.value,i=await lo(n,t,r);if(i){const n=await this.extractValue(e,t,r);if(i.property.startsWith("*")){const e=i.property.substring(1);return{type:"style",element:i.element,property:e,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const o=await this.tryParseMemberExpression(n,e,t,r);if(o)return o}let s;if(s="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof o?await t.evaluate(n,r):o,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(yn(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(s))return{type:"object-literal",properties:s,targets:await this.resolveTargets(e.modifiers.on,t,r)};if(ao(s)){const n=co(s,r);if(n){const o=await this.extractValue(e,t,r);return{type:"property",element:n.element,property:n.property,value:o}}return this.parseTheXofY(s,e,t,r)}if("string"==typeof s&&Vn(s)){const n=s.substring(1).trim(),o=await this.extractValue(e,t,r);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,r),property:n,value:o+""}}if("string"==typeof s&&Cn(s)){const n=s.substring(1).trim(),o=await this.extractValue(e,t,r);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,r),name:n,value:o}}if("string"==typeof s){const n=s.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const o=wn(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:o,property:n[2],value:i}}}if(yn(s))return{type:"property",element:s,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(s)&&s.length>0&&yn(s[0])){const n=await this.extractValue(e,t,r);return{type:"property",element:s[0],property:"textContent",value:n}}if("string"!=typeof s)throw Error("set command target must be a string or object literal");return{type:"variable",name:s,value:await this.extractValue(e,t,r)}}async execute(e,t){switch(e.type){case"variable":return t.locals.set(e.name,e.value),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":return e.element.setAttribute(e.name,e.value+""),Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return no(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return _n(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[r,n]of Object.entries(e.properties))no(t,r,n);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,r,n){const o=e.object,i=e.property;if(o?.name&&i?.name){const e=o.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const o=wn(e,n),s=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.name,value:s}}}const s=e.object,a=e.computed;if(s){const o=await r.evaluate(s,n);if(null!=o&&"object"==typeof o){const s=a?await r.evaluate(e.property,n)+"":i?.name||"";if(s)return{type:"member-assignment",container:o,property:s,value:await this.extractValue(t,r,n)}}}return null}async extractValue(e,t,r){if(e.modifiers.to)return t.evaluate(e.modifiers.to,r);const n=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(n>=0&&e.args.length>n+1)return t.evaluate(e.args[n+1],r);if(e.args.length>=2)return t.evaluate(e.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,r){return vn(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return gn(e?await t.evaluate(e,r):void 0,r)}async parseTheXofY(e,t,r,n){const o=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!o)throw Error('Invalid "the X of Y" syntax');const[,i,s]=o,a=vn(s,n),c=await this.extractValue(t,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&yn(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&yn(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&yn(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}}},ln(t,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());let Co=(()=>{let e,t,r=[mn({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"]}),pn({name:"increment",category:"data"})],n=[];return t=class{async parseInput(e,t,r){const n="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",o=await async function(e,t,r,n){if(!e.args||0===e.args.length)throw Error(n+" command requires a target");const o=e.args[0];let i,s;const a=(c=o)&&"object"==typeof c&&c.type||"unknown";var c;if("identifier"===a)i=o.name,o.scope&&(s=o.scope);else if("literal"===a)i=o.value;else{const e=await t.evaluate(o,r);i=Array.isArray(e)&&e.length>0?e[0]:e}let l=1,u=s;for(let n=1;e.args.length>n;n++){const o=e.args[n];if(o&&"literal"===o.type){const e=o.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(o&&"literal"!==o.type){const e=await t.evaluate(o,r);"number"==typeof e&&(l=e)}}return{target:i,amount:l,...u&&{scope:u}}}(e,t,r,n);return{...o,operation:n}}async execute(e,t){const{target:r,property:n,scope:o,amount:i=1,operation:s="increment"}=e,a=function(e,t,r,n){if("number"==typeof e)return e;if(yn(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?yo(r.getAttribute(t)):yo(r[t]):yo(r.value||r.textContent)}return"string"==typeof e?"global"===r?yo(vo(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],o=bo(r[0],t);return o?yo(o[n]):0}(e,n):yo("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:vo(e,n)):yo(e)}(r,n,o,t);let c;if(isNaN(a))c=NaN;else{const e=isFinite(i)?i:1;c="increment"===s?a+e:a-e}return function(e,t,r,n,o){if(yn(e)){const r=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?r.setAttribute(t,n+""):r[t]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof e){if("global"===r)return void go(e,n,o,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),o=n[1],i=bo(n[0],r);i&&(i[o]=t)}(e,n,o);if("me"===e&&o.me)return void(o.me.value=n);if("it"===e)return void Object.assign(o,{it:n});if("you"===e&&o.you)return void(o.you.value=n);go(e,n,o)}}(r,n,o,c,t),Object.assign(t,{it:c}),c}},ln(t,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})();const ko=hn(Co),jo=hn(Co),Lo=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"log",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{values:[]}}async execute(e,t){const r="undefined"!=typeof window?window.console:console;0===e.values.length?r.log():r.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},ln(t,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());function Io(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}let Ro=(()=>{let e,t,r=[mn({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"]}),pn({name:"trigger",category:"event"})],n=[];return t=class{async parseInput(e,t,r){const n="send"===e.commandName?.toLowerCase()?"send":"trigger",o=n;if(!e.args?.length)throw Error(o+" command requires an event name");const i=e=>e?.type||"unknown",s=e.args[0];let a,c,l;if("functionCall"===i(s)||"callExpression"===i(s)){a=s.name||s.callee?.name;const e=s.args||s.arguments;e?.length&&(c=await this.parseEventDetail(e,t,r))}else if("identifier"===i(s)||"keyword"===i(s))a=s.name;else{const e=await t.evaluate(s,r);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,r,o);else{const n=e.args.findIndex((e,t)=>{if(0===t)return!1;const r=e.name||e.value;return"on"===r||"to"===r});if(-1!==n&&e.args.length-1>n){const i=e.args.slice(n+1),s=i.findIndex(e=>"with"===(e.name||e.value)),a=-1===s?i:i.slice(0,s);l=await this.resolveTargets(a,t,r,o)}else{if(!r.me)throw Error(o+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(e.args,t,r),mode:n}}async execute(e,t){const r=function(e,t,r={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(r);t.it=r}async resolveTargets(e,t,r,n){const o=[];for(const n of e){const e=await t.evaluate(n,r);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&r.me)o.push(r.me);else if("you"===e&&r.you)o.push(r.you);else if("it"===e&&r.it)o.push(r.it);else if(yn(e))o.push(e);else if(e instanceof NodeList)o.push(...Array.from(e).filter(yn));else if(Array.isArray(e))o.push(...e.filter(yn));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);o.push(...Array.from(t).filter(yn));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);o.push(e)}else o.push(document);else o.push(window)}if(!o.length)throw Error(n+": no valid targets");return o}async parseEventDetail(e,t,r){if(!e?.length)return;if(1===e.length){const n=e[0];if("objectLiteral"!==n?.type)return await t.evaluate(n,r)}const n={};for(const o of e){const e=await t.evaluate(o,r);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,r]=e.split(":",2);n[t.trim()]=Io(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:!0,cancelable:!0,composed:!1},o=e.findIndex(e=>"with"===(e.name||e.value));if(-1===o)return n;for(const i of e.slice(o+1)){const e=await t.evaluate(i,r);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?n.bubbles=!0:"nobubbles"===t?n.bubbles=!1:"cancelable"===t?n.cancelable=!0:"nocancelable"===t?n.cancelable=!1:"composed"===t&&(n.composed=!0)}}return n}},ln(t,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})();const $o=hn(Ro),Mo=hn(Ro),Do=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"go",category:"navigation"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{args:[]}}async execute(e,t){const{args:r}=e;if(0===r.length)throw Error("Go command requires arguments");return"string"==typeof r[0]&&"back"===r[0].toLowerCase()?(await this.goBack(),{result:"back",type:"back"}):this.isUrlNavigation(r)?{result:await this.navigateToUrl(r,t),type:"url"}:{result:await this.scrollToElement(r,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const r=e.findIndex(e=>"url"===e),n=e[r+1];if(!n)throw Error('URL is required after "url" keyword');const o="string"==typeof n?n:n+"",i=e.includes("new")&&e.includes("window");if(!this.isValidUrl(o))throw Error(`Invalid URL: "${o}"`);if(i){if("undefined"!=typeof window&&window.open){const e=window.open(o,"_blank");e?.focus&&e.focus()}}else o.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=o):"undefined"!=typeof window&&(window.location.assign?.(o)??(window.location.href=o));return o}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const r=this.parseScrollPosition(e),n=this.parseScrollTarget(e),o=this.parseScrollOffset(e),i=!e.includes("instantly"),s=this.resolveScrollTarget(n,t);if(!s)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==o){s.scrollIntoView?.({behavior:e,block:t,inline:n});const{x:i,y:a}=this.calculateScrollPosition(s,r,o);window.scrollTo?.({left:i,top:a,behavior:e})}else s.scrollIntoView?.({behavior:e,block:t,inline:n})}return s}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let o=!1,i=!1;for(const s of e)"string"==typeof s&&(r.includes(s)?(t.vertical=s,o=!0):n.includes(s)&&(t.horizontal=s,i=!0));return i&&!o&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let r=e[t+1];return"the"===r&&e.length>t+2&&(r=e[t+2]),r}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!r.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const r=e[t];if("string"==typeof r){const e=r.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===r||"-"===r)&&e.length>t+1){const n=e[t+1],o="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(o))return"-"===r?-o:o}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const r="string"==typeof e?e:e+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&yn(t.me))return t.me;if("it"===r&&yn(t.it))return t.it;if("you"===r&&yn(t.you))return t.you;const n=vo(r,t);if(yn(n))return n;if("undefined"!=typeof document)try{const e=document.querySelector(r);if(e)return e}catch{try{const e=document.getElementsByTagName(r);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,r){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const n=e.getBoundingClientRect(),o=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,s=window.innerWidth||800,a=window.innerHeight||600;let c=o,l=i;switch(t.horizontal){case"left":c=n.left+o;break;case"center":c=n.left+o+n.width/2-s/2;break;case"right":c=n.right+o-s}switch(t.vertical){case"top":l=n.top+i+r;break;case"middle":l=n.top+i+n.height/2-a/2+r;break;case"bottom":l=n.bottom+i-a+r}return{x:Math.max(0,c),y:Math.max(0,l)}}},ln(t,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());function Vo(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const r=vo(e,t);return void 0!==r?!!r:!!e}return!!e}const _o=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"if",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){const n="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(n+" command requires a condition to evaluate");let o,i;if("unless"===n){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");o=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(o=e.args[1],i=3>e.args.length?void 0:e.args[2]):e.modifiers?.then&&(o=e.modifiers.then,i=e.modifiers.else),!o)throw Error('if command requires "then" branch with commands');return{mode:n,condition:await t.evaluate(e.args[0],r),thenCommands:o,elseCommands:i}}async execute(e,t){const{mode:r,condition:n,thenCommands:o,elseCommands:i}=e,s=Vo(n,t);let a,c;return("unless"===r?!s:s)?(a="then",c=await this.executeCommandsOrBlock(o,t),"unless"===r&&Object.assign(t,{it:c})):i&&"if"===r?(a="else",c=await this.executeCommandsOrBlock(i,t)):a="none",{mode:r,conditionResult:s,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 r=t.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let n;if(e.commands?.length)for(const o of e.commands)n=await r(o,t);return n}async executeCommands(e,t){let r;for(const n of e)r=n?.execute?await n.execute(t):"function"==typeof n?await n():n;return r}},ln(t,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),Po=_o,Bo=_o;let qo=(()=>{let e,t,r=[mn({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"]}),pn({name:"repeat",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){let n;if(e.modifiers?.index){const o=await t.evaluate(e.modifiers.index,r);"string"==typeof o&&(n=o)}let o=e.modifiers?.block||e.modifiers?.commands;if(!o)for(let t=e.args.length-1;t>=0;t--){const r=e.args[t];if("block"===r?.type&&r.commands){o=r;break}}const i=e.args[0],s="identifier"===i?.type?i.name:null;if("for"===s||e.modifiers?.for){const i=e.args[1],s=i?.value||i?.name,a=e.args[2]?await t.evaluate(e.args[2],r):void 0;if(!s||void 0===a)throw Error("for loops require variable and collection");return{type:"for",variable:s,collection:Array.isArray(a)?a:[a],indexVariable:n,commands:o}}if("times"===s||e.modifiers?.times){const i=e.args[1],s=i?await t.evaluate(i,r):void 0,a="number"==typeof s?s:parseInt(s+"",10);if(isNaN(a))throw Error("times loops require a count number");return{type:"times",count:a,indexVariable:n,commands:o}}if("while"===s||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw Error("while loops require a condition");return{type:"while",condition:t,indexVariable:n,commands:o}}if("until"===s&&e.modifiers?.from||"until-event"===s){const i=e.args[1],s=i?.value||i?.name;if(!s)throw Error("until-event loops require an event name");let a=r.me;if(e.args[2]){const n=await t.evaluate(e.args[2],r);n instanceof EventTarget?a=n:"document"===n&&(a=document)}return{type:"until-event",eventName:s,eventTarget:a,indexVariable:n,commands:o}}if("until"===s||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw Error("until loops require a condition");return{type:"until",condition:t,indexVariable:n,commands:o}}if("forever"===s||e.modifiers?.forever)return{type:"forever",indexVariable:n,commands:o};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:r,variable:n,collection:o,condition:i,count:s,indexVariable:a,commands:c,eventName:l,eventTarget:u}=e;let f,d;switch(r){case"for":({config:f,iterCtx:d}=function(e,t,r){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:r}}}(o,n,a));break;case"times":({config:f,iterCtx:d}=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}}}(s,a));break;case"while":({config:f,iterCtx:d}=function(e,t,r,n){return{config:{type:"while",shouldContinue:()=>t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,Vo,t,a));break;case"until":({config:f,iterCtx:d}=function(e,t,r,n){return{config:{type:"until",shouldContinue:()=>!t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,Vo,t,a));break;case"until-event":({config:f,iterCtx:d}=function(e,t,r){const n={index:0,eventFired:!1,indexVariable:r};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{n.eventFired=!0}}},iterCtx:n}}(l,u,a));break;case"forever":({config:f,iterCtx:d}=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: "+r)}try{const e=await async function(e,t,r,n,o){const i=e.maxIterations??1e4;let s,a=0,c=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>a&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,r),n.indexVariable&&r.locals&&r.locals.set(n.indexVariable,a);try{s=await o(t,r)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){c=!0;break}if(t.message.includes("CONTINUE")){a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:a,lastResult:s,interrupted:c}}(f,c,t,d,this.executeCommands.bind(this));return Object.assign(t,{it:e.lastResult}),{type:r,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:r,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const r=e,n=t.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let o;if(r.commands)for(const e of r.commands)o=await n(e,t);return o}if(Array.isArray(e)){let r;for(const n of e)r="function"==typeof n?await n(t):n&&"function"==typeof n.execute?await n.execute(t):n;return r}return"function"==typeof e?await e(t):e}},ln(t,"RepeatCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})();const Fo=hn(qo);class Ho{async parseInput(e,t,r){return{signalType:this.signalType}}async execute(e,t){const r=Error(this.errorMessage);throw r[this.errorFlag]=!0,"exit"===this.signalType&&(r.returnValue=void 0,r.timestamp=Date.now()),r}}let Uo=(()=>{let e,t,r=[mn({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"]}),pn({name:"break",category:"control-flow"})],n=[],o=Ho;return t=class extends o{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},ln(t,"BreakCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const Wo=hn(Uo);let Jo=(()=>{let e,t,r=[mn({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"]}),pn({name:"continue",category:"control-flow"})],n=[],o=Ho;return t=class extends o{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},ln(t,"ContinueCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const zo=hn(Jo),Zo=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"halt",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(e.args&&e.args.length>0){const n=e.args[0],o=e.args.length>1?e.args[1]:null;return"identifier"===n.type&&"the"===n.name&&o&&"identifier"===o.type&&"event"===o.name?{target:r.event}:{target:await t.evaluate(e.args[0],r)}}return{}}async execute(e,t){let r=e.target;if(("the"===r&&t.event||"object"==typeof r&&null!==r&&"the"===r.target&&t.event)&&(r=t.event),this.isEvent(r)){const e=r;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in t&&(t.halted=!0);const n=Error("HALT_EXECUTION");throw n.isHalt=!0,n}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},ln(t,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),Go=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"return",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{value:await t.evaluate(e.args[0],r)}:{value:void 0}}async execute(e,t){const{value:r}=e;"returnValue"in t&&(t.returnValue=r),Object.assign(t,{it:r});const n=Error("RETURN_VALUE");throw n.isReturn=!0,n.returnValue=r,n}},ln(t,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());let Xo=(()=>{let e,t,r=[mn({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"]}),pn({name:"exit",category:"control-flow"})],n=[],o=Ho;return t=class extends o{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},ln(t,"ExitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cn(t,n)})(),t})();const Yo=hn(Xo),Ko=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"call",category:"execution"})],n=[];return t=class{parseInput(e,t,r){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:r}=e,n=t.locals?.get("__evaluator");if(!n)throw Error("[CALL.execute] No evaluator available in context");const o=await n.evaluate(r,t);let i,s,a=!1;return"function"==typeof o?(s="function",i=o(),i instanceof Promise&&(a=!0,i=await i)):o instanceof Promise?(s="promise",a=!0,i=await o):(s="value",i=o),Object.assign(t,{it:i,result:i}),{result:i,wasAsync:a,expressionType:s}}},ln(t,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),Qo=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"append",category:"content"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("append requires content");const n=await t.evaluate(e.args[0],r);let o;return e.modifiers?.to?o=await t.evaluate(e.modifiers.to,r):e.target&&(o=e.target),{content:n,target:o}}async execute(e,t){const{content:r,target:n}=e,o=r+"";if(!n)return Object.assign(t,void 0===t.it?{it:o}:{it:t.it+""+o}),{result:t.it,targetType:"result"};if("string"==typeof n){if(n.startsWith("#")||n.startsWith(".")||n.includes("[")){const e=this.resolveDOMElement(n);return e.innerHTML+=o,{result:e,targetType:"element",target:e}}if("me"===n||"it"===n||"you"===n){const e=this.resolveContextRef(n,t);if(yn(e))return e.innerHTML+=o,{result:e,targetType:"element",target:e}}const e=vo(n,t);if(void 0!==e){if(Array.isArray(e))return e.push(r),{result:e,targetType:"array",target:n};const i=(null==e?"":e+"")+o;return go(n,i,t),{result:i,targetType:"variable",target:n}}return go(n,o,t),{result:o,targetType:"variable",target:n}}if(Array.isArray(n))return n.push(r),{result:n,targetType:"array"};if(yn(n))return n.innerHTML+=o,{result:n,targetType:"element",target:n};{const e=n+""+o;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)}}},ln(t,"AppendCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),ei=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"transition",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("transition requires property and value");let n,o;const i=await t.evaluate(e.args[0],r);if(yn(i)||"string"==typeof i&&/^[#.]|^(?:me|it|you)$/.test(i)?(o=i,n=await t.evaluate(e.args[1],r)+""):n=i+"",!n)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let s=await t.evaluate(e.modifiers.to,r);void 0===s&&"identifier"===e.modifiers.to.type&&(s=e.modifiers.to.name);const a={property:n,value:s};return void 0!==o&&(a.target=o),e.modifiers?.over&&(a.duration=await t.evaluate(e.modifiers.over,r)),e.modifiers?.with&&(a.timingFunction=await t.evaluate(e.modifiers.with,r)+""),a}async execute(e,t){let{property:r}=e;const{target:n,value:o,duration:i,timingFunction:s}=e;r.startsWith("*")&&(r=r.substring(1)),r=r.replace(/([A-Z])/g,"-$1").toLowerCase();const a=vn(n,t),c=Gn(i,300),l=getComputedStyle(a).getPropertyValue(r),u=a.style.transition,f=`${r} ${c}ms ${s||"ease"}`;a.style.transition=u?`${u}, ${f}`:f;let d=o+"",p=!1;if("initial"===d||"inherit"===d||"unset"===d||"revert"===d){const e=a.style.getPropertyValue(r);a.style.removeProperty(r),d=getComputedStyle(a).getPropertyValue(r),e&&a.style.setProperty(r,e),p=!0}a.style.setProperty(r,d);const m=await function(e,t,r){return new Promise(n=>{const o=r=>{r.target===e&&r.propertyName===t&&s({completed:!0,cancelled:!1})},i=r=>{r.target===e&&r.propertyName===t&&s({completed:!1,cancelled:!0})},s=Ao(()=>{e.removeEventListener("transitionend",o),e.removeEventListener("transitioncancel",i),clearTimeout(a)},n);e.addEventListener("transitionend",o),e.addEventListener("transitioncancel",i);const a=setTimeout(()=>{s({completed:!0,cancelled:!1})},r+50)})}(a,r,c);return a.style.transition=u,p&&a.style.removeProperty(r),Object.assign(t,{it:a}),{element:a,property:r,fromValue:l,toValue:d,duration:c,completed:m.completed}}},ln(t,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),ti=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"measure",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,o,i;if(e.args?.length){const i=e.args[0];if("identifier"===i.type&&i.name){const s=i.name.toLowerCase();if("me"===s||"it"===s||"you"===s){const s=await t.evaluate(i,r);if(yn(s)&&(n=s,e.args.length>1)){const n=e.args[1];o="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else o=i.name}else{const s=await t.evaluate(i,r);if(yn(s)||"string"==typeof s&&/^[#.]/.test(s)){if(n=s,e.args.length>1){const n=e.args[1];o="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else"string"==typeof s&&(o=s)}}e.modifiers?.set&&(i=await t.evaluate(e.modifiers.set,r)+"");const s={};return void 0!==n&&(s.target=n),void 0!==o&&(s.property=o),void 0!==i&&(s.variable=i),s}async execute(e,t){const r=vn(e.target,t),n=e.property||"width",o=this.getMeasurement(r,n);return e.variable&&t.locals&&t.locals.set(e.variable,o.value),Object.assign(t,{it:o.value}),{result:o.value,wasAsync:!1,element:r,property:n,value:o.value,unit:o.unit,stored:!!e.variable}}getMeasurement(e,t){const r=getComputedStyle(e);if(t.startsWith("*")){const e=r.getPropertyValue(t.substring(1)),n=parseFloat(e);if(!isNaN(n)){const t=e.match(/([a-zA-Z%]+)$/);return{value:n,unit:t?t[1]:""}}return{value:e,unit:""}}const n=t.toLowerCase(),o=e.getBoundingClientRect(),i={width:()=>o.width,height:()=>o.height,top:()=>o.top,left:()=>o.left,right:()=>o.right,bottom:()=>o.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(i[n])return{value:i[n](),unit:"px"};const s=r.getPropertyValue(t),a=parseFloat(s);if(!isNaN(a)){const e=s.match(/([a-zA-Z%]+)$/);return{value:a,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},ln(t,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),ri=hn((()=>{let e,t,r=[mn({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),pn({name:"settle",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,o;if(e.args&&e.args.length>0){const o=await t.evaluate(e.args[0],r);(yn(o)||"string"==typeof o&&(o.startsWith("#")||o.startsWith(".")||"me"===o||"it"===o||"you"===o))&&(n=o)}e.modifiers?.for&&(o=await t.evaluate(e.modifiers.for,r));const i={};return void 0!==n&&(i.target=n),void 0!==o&&(i.timeout=o),i}async execute(e,t){const{target:r,timeout:n}=e,o=vn(r,t),i=Gn(n,5e3),s=Date.now(),a=getComputedStyle(o),c=Yn(a.transitionDuration),l=Yn(a.transitionDelay),u=Yn(a.animationDuration),f=Yn(a.animationDelay),d=Kn(c,l),p=Kn(u,f),m=Math.max(d,p),h=await(y=o,v=m,g=i,v>0?new Promise(e=>{const t=e=>{e.target===y&&n({completed:!0,type:"transition"})},r=e=>{e.target===y&&n({completed:!0,type:"animation"})},n=Ao(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",r),clearTimeout(o),clearTimeout(i)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",r);const o=setTimeout(()=>{n({completed:!0,type:"timeout"})},v+50),i=setTimeout(()=>{n({completed:!1,type:"timeout"})},g)}):Promise.resolve({completed:!0,type:"timeout"}));var y,v,g;const b=Date.now()-s;return Object.assign(t,{it:o}),{element:o,settled:h.completed,timeout:i,duration:b}}},ln(t,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),ni=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"js",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){let n,o;if(0===e.args.length)throw Error("js command requires JavaScript code");const i=e.args[0],s=e.args[1];if(i&&"literal"===i.type&&"string"==typeof i.value)n=i.value;else{if(!i||void 0===i.value)throw Error("js command requires JavaScript code");n=i.value+""}s&&"arrayLiteral"===s.type&&Array.isArray(s.elements)&&(o=s.elements.map(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const a={code:n};return o&&o.length>0&&(a.parameters=o),a}async execute(e,t){const{code:r,parameters:n=[]}=e;if(!r.trim())return{result:void 0,executed:!1,codeLength:r.length,parameters:n,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,n),o=Function(...Object.keys(e),r),i=await o(...Object.values(e));return void 0!==i&&Object.assign(t,{it:i}),{result:i,executed:!0,codeLength:r.length,parameters:n,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,r)=>{let n=e.locals?.get(r);return void 0===n&&(n=e.variables?.get(r)),void 0===n&&(n=e[r]),t[r]=n,t},{})}}},ln(t,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),oi=hn((()=>{let e,t,r=[mn({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),pn({name:"async",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:r}=e,n=Date.now();try{const e=await this.executeCommandsAsync(t,r),o=Date.now()-n;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:r.length,results:e,executed:!0,duration:o}}catch(e){throw Error("Async command execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}async executeCommandsAsync(e,t){const r=[];for(let n=0;t.length>n;n++){const o=t[n];try{const t=await this.executeCommand(o,e);r.push(t),Object.assign(e,{it:t})}catch(e){const r=this.getCommandName(o);throw Error(`Command '${r}' (${n+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return r}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},ln(t,"AsyncCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),ii=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"default",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("default command requires a target");const n=await t.evaluate(e.args[0],r);let o;if(e.modifiers?.to)o=await t.evaluate(e.modifiers.to,r);else{if(2>e.args.length)throw Error('default command requires a value (use "to <value>")');o=await t.evaluate(e.args[1],r)}return{target:n,value:o}}async execute(e,t){const{target:r,value:n}=e;if("string"==typeof r){if(r.startsWith("@"))return this.defaultAttribute(t,r.substring(1),n);const e=r.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,r,o]=e;return this.defaultElementProperty(t,r,o,n)}return this.defaultVariable(t,r,n)}if(yn(r))return this.defaultElementValue(t,r,n);throw Error("Invalid target type: "+typeof r)}defaultVariable(e,t,r){const n=vo(t,e);return void 0!==n?{target:t,value:r,wasSet:!1,existingValue:n,targetType:"variable"}:(go(t,r,e),Object.assign(e,{it:r}),{target:t,value:r,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,r){if(!e.me)throw Error("No element context available for attribute default");const n=e.me.getAttribute(t);return null!==n?{target:"@"+t,value:r,wasSet:!1,existingValue:n,targetType:"attribute"}:(e.me.setAttribute(t,r+""),Object.assign(e,{it:r}),{target:"@"+t,value:r,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,r,n){const o=wn(t,e),i=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const r=t.split(".");let n=e;for(const e of r){if(null==n)break;n=n[e]}return n}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(o,r),s=`${t} ${r}`;return oo(i)?(no(o,r,n),Object.assign(e,{it:n}),{target:s,value:n,wasSet:!0,targetType:"property"}):{target:s,value:n,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(e,t,r){const n=function(e){return"value"in e?e.value:e.textContent}(t);return oo(n)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,r),Object.assign(e,{it:r}),{target:"element",value:r,wasSet:!0,targetType:"element"}):{target:"element",value:r,wasSet:!1,existingValue:n,targetType:"element"}}},ln(t,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());class si{constructor(){this.name="pseudo-command"}get metadata(){return si.metadata}async parseInput(e,t,r){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const n=e.args[0].properties||[];let o,i,s="",a=[];for(const e of n){const n=e.value;switch(e.key?.name||e.key?.value){case"methodName":s=n?.value||await t.evaluate(n,r)+"";break;case"methodArgs":"arrayLiteral"===n?.type&&n.elements?a=await Promise.all(n.elements.map(e=>t.evaluate(e,r))):"literal"===n?.type&&Array.isArray(n.value)&&(a=await Promise.all(n.value.map(e=>t.evaluate(e,r))));break;case"preposition":const e=n?.value;e&&"null"!==e&&(o=e);break;case"target":case"targetExpression":i=await t.evaluate(n,r)}}if(!s)throw Error("pseudo-command requires method name");if(null==i)throw Error("pseudo-command requires a target expression");return{methodName:s,methodArgs:a,preposition:o,targetExpression:i}}if(2>e.args.length)throw Error("pseudo-command requires method name and target expression");const n=await t.evaluate(e.args[0],r)+"",o=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,r))):[];let i,s;const a=["from","on","with","into","at","to"];for(const n of a)if(e.modifiers?.[n]){s=n,i=await t.evaluate(e.modifiers[n],r);break}if(i||3>e.args.length||(i=await t.evaluate(e.args[2],r)),!i)throw Error("pseudo-command requires a target expression");return{methodName:n,methodArgs:o,preposition:s,targetExpression:i}}async execute(e,t){const{methodName:r,methodArgs:n,targetExpression:o}=e;try{const e=await this.resolveTarget(o,t);if(null==e)throw Error("Target expression resolved to "+e);const i=this.resolveMethod(e,r);if(!i)throw Error(`Method "${r}" not found on target object`);if("function"!=typeof i)throw Error(`"${r}" is not a function (it's a ${typeof i})`);const s=await this.executeMethod(i,e,n);return t.locals.set("result",s),Object.assign(t,{it:s}),{result:s,methodName:r,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const r=e.split(".");let n="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(r[0])?(n=t.locals.get(r[0]),r.shift()):t.variables?.has(r[0])?(n=t.variables.get(r[0]),r.shift()):t.globals.has(r[0])&&(n=t.globals.get(r[0]),r.shift());for(const e of r){if(null==n)return null;n=n[e]}return n}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const r=t.split(".");let n=e;for(let e=0;r.length>e;e++){const t=r[e];if(null==n)return null;if(!(t in n))return null;if(n=n[t],e===r.length-1&&"function"==typeof n)return n}return null}async executeMethod(e,t,r){try{const n=e.apply(t,r);return n&&"object"==typeof n&&"then"in n?await n:n}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}function ai(){return new si}si.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 ci=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"tell",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],r),commands:e.args.slice(1)}}async execute(e,t){const{target:r,commands:n}=e,o=gn(r,t);if(0===o.length)throw Error("tell command found no target elements");const i=t.locals.get("_runtimeExecute"),s=[];for(const e of o){const r={...t,me:e,you:e};for(const e of n)try{const t=await this.executeCommand(e,r,i);s.push(t),Object.assign(r,{it:t})}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}}return{targetElements:o,commandResults:s,executionCount:o.length*n.length}}async executeCommand(e,t,r){if(e&&"object"==typeof e&&"command"===e.type&&r)return await r(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}},ln(t,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());let li=(()=>{let e,t,r=[mn({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"]}),pn({name:"copy",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("copy command requires a source (text or element)");const n=await t.evaluate(e.args[0],r);let o="text";if(e.modifiers?.format){const n=await t.evaluate(e.modifiers.format,r);"html"!==n&&"text"!==n||(o=n)}return{source:n,format:o}}async execute(e,t){const{source:r,format:n="text"}=e,o=this.extractText(r,n,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(o),this.dispatchCopyEvent(t,"copy:success",{text:o,method:"clipboard-api"}),{success:!0,text:o,format:n,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(o))return this.dispatchCopyEvent(t,"copy:success",{text:o,method:"execCommand"}),{success:!0,text:o,format:n,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:o,error:"All copy methods failed"}),{success:!1,text:o,format:n,method:"fallback"}}extractText(e,t,r){if("string"==typeof e)return e;if(yn(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&yn(r.me)){const e=r.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,r){if(yn(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},ln(t,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})();const ui=hn(li),fi=hn((()=>{let e,t,r=[mn({description:"Select a random element from a collection",syntax:["pick <item1>, <item2>, ...","pick from <array>"],examples:['pick "red", "green", "blue"',"pick from colors","pick 1, 2, 3, 4, 5"],sideEffects:["random-selection"]}),pn({name:"pick",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(e.modifiers?.from){const n=await t.evaluate(e.modifiers.from,r);if(!Array.isArray(n))throw Error("pick from requires an array");if(0===n.length)throw Error("Cannot pick from empty array");return{array:n}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{items:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const{items:r,array:n}=e,o=r||n,i=r?"items":"array",s=Math.floor(Math.random()*o.length),a=o[s];return Object.assign(t,{it:a}),{selectedItem:a,selectedIndex:s,sourceLength:o.length,sourceType:i}}},ln(t,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})()),di=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"throw",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],r)}}async execute(e,t){const{message:r}=e;let n;throw n=r instanceof Error?r:Error("string"==typeof r?r:r+""),n}},ln(t,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());const pi=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"beep",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return 0===e.args.length?{expressions:[]}:{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.expressions||[];if(0===r.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const n=[];console.group("🔔 beep! Debug Output");for(const e of r){const t=this.debugExpression(e);n.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:r.length,debugged:!0,outputs:n}}debugContext(e){console.group("🔔 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":yn(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(yn(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+""}},ln(t,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());class mi{constructor(){this.name="install"}get metadata(){return mi.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("install command requires a behavior name");const n=e.args[0];let o,i,s;if(o="identifier"===n?.type&&"string"==typeof n.name?n.name:await t.evaluate(n,r)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(o))throw Error(`Behavior name must be PascalCase (start with uppercase): "${o}"`);if(e.args.length>=2){const n=await t.evaluate(e.args[1],r);if(n&&"object"==typeof n&&!Array.isArray(n)){i=n;for(const e of Object.keys(i))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(s=await t.evaluate(e.modifiers.on,r)),{behaviorName:o,parameters:i,target:s}}async execute(e,t){const{behaviorName:r,parameters:n={},target:o}=e;try{const e=this.resolveTarget(o,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(r,t))throw Error(`Behavior "${r}" is not defined. Define it using the 'behavior' keyword before installing.`);const i=[];for(const o of e){const e=await this.installBehavior(r,o,n,t);i.push(e)}return{success:!0,behaviorName:r,installedCount:i.length,instances:i}}catch(e){throw Error(`Failed to install behavior "${r}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(yn(e))return[e];throw Error('No target specified and "me" is not available in context')}if(yn(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>yn(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(yn(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),r=Array.from(t).filter(e=>yn(e));if(0===r.length)throw Error(`No elements found matching selector: "${e}"`);return r}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>yn(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(yn(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+e)}behaviorExists(e,t){const r=t.locals.get("_behaviors");if(r&&"object"==typeof r)return r.has(e);if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors)return t.behaviors.has(e)}return!1}async installBehavior(e,t,r,n){const o=n.locals.get("_behaviors");if(o&&"object"==typeof o){const n=o;if(n.install&&"function"==typeof n.install)return await n.install(e,t,r)}if("undefined"!=typeof globalThis){const n=globalThis._hyperscript;if(n?.behaviors?.install)return await n.behaviors.install(e,t,r)}throw Error("Behavior system not available in context")}}function hi(){return new mi}mi.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};const yi=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"take",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(3>e.args.length)throw Error('take requires property, "from", and source');const n=await t.evaluate(e.args[0],r)+"";if("from"!==await t.evaluate(e.args[1],r))throw Error("take syntax: take <property> from <source>");const o=await t.evaluate(e.args[2],r);let i;if(8>e.args.length)e.args.length>3&&(i=await t.evaluate(e.args[3],r));else{const n=await Promise.all([3,4,5,6].map(n=>t.evaluate(e.args[n],r)));"and"===n[0]&&"put"===n[1]&&"it"===n[2]&&"on"===n[3]&&e.args[7]&&(i=await t.evaluate(e.args[7],r))}return!i&&e.modifiers?.on&&(i=await t.evaluate(e.modifiers.on,r)),{property:n,source:o,target:i}}async execute(e,t){const r=vn(e.source,t),n=vn(e.target?e.target:void 0,t),o=this.takeProperty(r,e.property);return this.putProperty(n,e.property,o),{targetElement:n,property:e.property,value:o}}takeProperty(e,t){const r=t.trim(),n=r.toLowerCase();if("class"===n||"classes"===n){const t=Array.from(e.classList);return e.className="",t}if(r.startsWith(".")){const t=r.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(r.startsWith("@")){const t=r.substring(1),n=e.getAttribute(t);return e.removeAttribute(t),n}if(r.startsWith("data-")){const t=e.getAttribute(r);return e.removeAttribute(r),t}if("id"===n){const t=e.id;return e.id="",t}if("title"===n){const t=e.title;return e.title="",t}if("value"===n&&"value"in e){const t=e.value;return e.value="",t}const o=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(r.includes("-")||o in e.style||r in e.style){let t;return o in e.style?(t=e.style[o],e.style[o]=""):r in e.style?(t=e.style[r],e.style[r]=""):(t=e.style.getPropertyValue(r),e.style.removeProperty(r)),t}const i=e.getAttribute(t);return null!==i?(e.removeAttribute(t),i):null}putProperty(e,t,r){if(null==r)return;const n=t.trim(),o=n.toLowerCase();if("class"===o||"classes"===o)return void(Array.isArray(r)?r.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof r&&(e.className=r));if(n.startsWith("."))return void(r&&e.classList.add(n.substring(1)));if(n.startsWith("@"))return void e.setAttribute(n.substring(1),r+"");if(n.startsWith("data-"))return void e.setAttribute(n,r+"");if("id"===o)return void(e.id=r+"");if("title"===o)return void(e.title=r+"");if("value"===o&&"value"in e)return void(e.value=r+"");const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());n.includes("-")||i in e.style||n in e.style?i in e.style?e.style[i]=r+"":n in e.style?e.style[n]=r+"":e.style.setProperty(n,r+""):e.setAttribute(t,r+"")}},ln(t,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());class vi{constructor(){this.name="render"}get metadata(){return vi.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("render command requires a template");const n=await t.evaluate(e.args[0],r);let o;if(e.args.length>=3&&"with"===await t.evaluate(e.args[1],r)){const n=await t.evaluate(e.args[2],r);n&&"object"==typeof n&&(o=n)}if(!o&&e.modifiers?.with){const n=await t.evaluate(e.modifiers.with,r);n&&"object"==typeof n&&(o=n)}return{template:n,variables:o}}async execute(e,t){const{template:r,variables:n={}}=e,o=this.extractTemplateContent(r,t),i=this.createTemplateContext(t,n),s=[],a=await this.processTemplate(o,i,s),c=this.createDOMElement(a);return Object.assign(t,{it:c}),{element:c,rendered:a,directivesProcessed:s}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let r=e;if(!r.includes("<")&&!r.includes("$")){const e=this.resolveVariable(r,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(r=e)}const n=r.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return n?n[1]:r}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,r){const n=e.split("\n"),o=[];let i=0;for(;n.length>i;){const e=n[i].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:s}=await this.processRepeatDirective(n,i,t);o.push(s),i=e,r.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:s}=await this.processIfDirective(n,i,t,r);o.push(s),i=e,r.push("@if")}else if("@else"===e||"@end"===e)i++;else{const r=this.processVariableInterpolation(e,t);o.push(r),i++}}return o.join("\n")}async processRepeatDirective(e,t,r){const n=e[t].trim(),o=n.match(/^@repeat\s+in\s+(.+)$/);if(!o)throw Error("Invalid @repeat syntax: "+n);const i=this.evaluateExpression(o[1],r),{endIndex:s,blockContent:a}=this.extractDirectiveBlock(e,t+1),c=[];if(Array.isArray(i))for(const e of i){const t={...r,locals:new Map([...r.locals.entries(),["it",e]])},n=await this.processTemplate(a.join("\n"),t,[]);c.push(n)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(e,t,r,n){const o=e[t].trim(),i=o.match(/^@if\s+(.+)$/);if(!i)throw Error("Invalid @if syntax: "+o);const s=!!this.evaluateExpression(i[1],r),{endIndex:a,blockContent:c,elseContent:l}=this.extractIfElseBlock(e,t+1);let u="";return s?u=await this.processTemplate(c.join("\n"),r,[]):l.length>0&&(u=await this.processTemplate(l.join("\n"),r,[]),n.push("@else")),{nextIndex:a+1,rendered:u}}extractDirectiveBlock(e,t){const r=[];let n=1,o=t;for(;e.length>o&&n>0;){const t=e[o].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(n++,r.push(e[o])):"@end"===t?(n--,n>0&&r.push(e[o])):r.push(e[o]),o++}return{endIndex:o-1,blockContent:r}}extractIfElseBlock(e,t){const r=[],n=[];let o=1,i=t,s=!1;for(;e.length>i&&o>0;){const t=e[i].trim();if(t.startsWith("@if "))o++;else{if("@else"===t&&1===o){s=!0,i++;continue}if("@end"===t&&(o--,0===o))break}s?n.push(e[i]):r.push(e[i]),i++}return{endIndex:i,blockContent:r,elseContent:n}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=r.trim();if(e.startsWith("unescaped ")){const r=e.substring(10).trim();return(this.evaluateExpression(r,t)||"")+""}const n=this.evaluateExpression(e,t);return this.escapeHtml((n||"")+"")}catch(t){return console.warn(`Template interpolation error for ${r}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const r=Number(e);if(!isNaN(r)&&""!==e.trim())return r;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++){if("object"!=typeof n||null===n)return;n=n[r[e]]}return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&").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 gi(){return new vi}vi.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};class bi extends nn{constructor(e={}){const t=e.registry||new Zr;let r;e.registry||(t.register(Tn()),t.register(On()),t.register(Un()),t.register(zn()),t.register(mo()),t.register(ho()),t.register(wo()),t.register(So()),t.register(No()),t.register(Oo()),t.register(ko()),t.register(jo()),t.register(Lo()),t.register($o()),t.register(Mo()),t.register(Do()),t.register(Po()),t.register(Fo()),t.register(Wo()),t.register(zo()),t.register(Zo()),t.register(Go()),t.register(Yo()),t.register(Ko()),t.register(Qo()),t.register(ei()),t.register(ti()),t.register(ri()),t.register(ni()),t.register(oi()),t.register(Bo()),t.register(ii()),t.register(ai()),t.register(ci()),t.register(ui()),t.register(fi()),t.register(di()),t.register(pi()),t.register(hi()),t.register(yi()),t.register(gi()),console.log("RuntimeExperimental: Registered 43 V2 commands (Phase 6 COMPLETE - All commands migrated)")),r=e.expressionEvaluator?e.expressionEvaluator:e.lazyLoad?new sn({preload:e.expressionPreload||"core"}):new Wr;const n={registry:t,expressionEvaluator:r};void 0!==e.enableAsyncCommands&&(n.enableAsyncCommands=e.enableAsyncCommands),void 0!==e.commandTimeout&&(n.commandTimeout=e.commandTimeout),void 0!==e.enableErrorReporting&&(n.enableErrorReporting=e.enableErrorReporting),super(n)}}const wi=hn((()=>{let e,t,r=[mn({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"]}),pn({name:"get",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const n=e.args[0],o=await t.evaluate(n,r);return o instanceof NodeList&&1===o.length||Array.isArray(o)&&1===o.length?{value:o[0]}:{value:o}}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}},ln(t,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;an(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cn(t,n)})(),t})());function Ei(){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>')}const xi=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],Ai=function(e,t={}){const r=new Zr;for(const t of e)r.register(t);return new bi({...t,registry:r})}([Tn(),On(),Un(),zn(),mo(),ho(),wo(),So(),No(),Oo(),wi(),ko(),jo(),ii(),$o(),Mo(),Do(),Po(),Fo(),Wo(),zo(),Zo(),Go(),Yo(),Bo(),di(),Ko(),ai(),Qo(),ei(),ti(),ri(),yi(),ni(),oi(),Lo(),ci(),ui(),fi(),pi(),hi(),gi()],{expressionPreload:"all"}),Si={async execute(e,t,r){const n=Ei(),o=n.createSemanticAnalyzer().analyze(e,t);if(.5>o.confidence||!o.node)throw Error(`Failed to parse "${e}" in language "${t}" (confidence: ${o.confidence.toFixed(2)})`);const i=n.buildAST(o.node),s=w(r);return Ai.execute(i.ast,s)},parse(e,t){const r=Ei(),n=r.createSemanticAnalyzer().analyze(e,t);return.5>n.confidence||!n.node?null:r.buildAST(n.node).ast},translate:(e,t,r)=>Ei().translate(e,t,r),getAllTranslations:(e,t)=>Ei().getAllTranslations(e,t),createContext:b,runtime:Ai,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:xi,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await Ci():e instanceof HTMLElement&&await Oi(e)},process:async e=>Si.processNode(e)},Ti=new WeakSet;let Ni=null;async function Oi(e){if(Ti.has(e))return;const t=e.getAttribute("_");if(t)try{const r=function(e){const t=e.getAttribute("data-lang");if(t&&xi.includes(t))return t;let r=e;for(;r;){const e=r.getAttribute("lang");if(e){const t=e.split("-")[0].toLowerCase();if(xi.includes(t))return t}r=r.parentElement}return"en"}(e);m(`ATTR-ML: Processing element with lang="${r}":`,t.substring(0,60));const n=Ei(),o=n.createSemanticAnalyzer().analyze(t,r);if(.5>o.confidence||!o.node)return void m(`ATTR-ML: Low confidence (${o.confidence.toFixed(2)}) for: ${t}`);const i=n.buildAST(o.node),s=w(e);await Ai.execute(i.ast,s),Ti.add(e),m("ATTR-ML: Successfully processed element")}catch(e){m("ATTR-ML: Error processing element:",e.message)}}async function Ci(){const e=document.querySelectorAll("[_]");m(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(Oi(e))}),await Promise.all(t),m("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:e.length}}))}function ki(){"undefined"!=typeof MutationObserver&&(Ni=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&Oi(t).catch(e=>{m("ATTR-ML: Error processing dynamic element:",e)});const r=t.querySelectorAll?.("[_]");r?.forEach(e=>{e instanceof HTMLElement&&Oi(e).catch(e=>{m("ATTR-ML: Error processing dynamic descendant:",e)})})})}),Ni.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=Si,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",()=>{Ci().then(()=>ki())}):Ci().then(()=>ki())),e.default=Si,e.hyperfixi=Si,Object.defineProperty(e,"u",{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 r of this.afterExecuteHooks)await r(e,t)}async runOnError(e,t){let r=t;for(const t of this.onErrorHooks){const n=await t(e,r);n instanceof Error&&(r=n)}return r}shouldIntercept(e,t){for(const r of this.interceptCommandHooks)if(r(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function r(e){return e instanceof Error&&("isHalt"in e||"isExit"in e||"isBreak"in e||"isContinue"in e||"isReturn"in e)?e:null}function n(e){return{ok:!0,value:e}}function o(e){return{ok:!1,error:e}}function i(e){return!0===e.ok}const s=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}(),a=s,c=s,l=s,u=s,f=s,d=(...e)=>{a&&console.log("🔧",...e)},p=(...e)=>{c&&console.log("🎯",...e)},m=(...e)=>{l&&console.log("📝",...e)},h=(...e)=>{u&&console.log("🔍",...e)},y=(...e)=>{f&&console.log("🚀",...e)};class v{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,r,n,o){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,o),this.debugMode&&y(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&y("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&y("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&y("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(e,t,r){this.addCleanup(e,{type:"custom",cleanup:t,description:r||"Custom cleanup"})}registerGlobal(e,t="custom",r){this.globalCleanups.push({type:t,cleanup:e,description:r||"Global cleanup"}),this.debugMode&&y("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e);r?r.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++,this.debugMode&&y(`CleanupRegistry: Registered ${t.type} for element`,e)}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let r=0;for(const e of t){try{e.cleanup(),r++}catch(e){this.debugMode&&y("CleanupRegistry: Error during cleanup:",e)}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,this.debugMode&&y(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(e){let t=this.cleanupElement(e);const r=e.querySelectorAll("*");for(const e of r)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){this.debugMode&&y("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&y(`CleanupRegistry: Cleaned up ${e} global resources`),e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,r=0,n=0,o=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":o++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+o,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const g=new Map;function b(e,t){return{me:e??null,it:null,you:null,result:null,locals:new Map,globals:t||g,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function w(e){if(!e)return b();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=b(e.me instanceof Element?e.me:null);return void 0!==e.it&&(t.it=e.it),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&(t.result=e.result),void 0!==e.event&&Object.assign(t,{event:e.event}),t}class E{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const r=e.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+e),this.sources.set(r,t)}unregister(e){const t=e.toLowerCase(),r=this.sources.get(t);if(r){for(const[e,r]of this.subscriptions.entries())r.source===t&&(r.unsubscribe(),this.subscriptions.delete(e));return r.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,r){const n=this.get(e);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+e);n.initialize?.();const o=n.subscribe(t,r);return this.subscriptions.set(o.id,o),o}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,r]of this.sources.entries())if(r.supports?.(e)??r.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}class x{constructor(){this.providers=new Map,this.globalProviders=new Map}register(e,t,r){const n=e.toLowerCase();this.providers.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}registerGlobal(e,t,r){const n=e.toLowerCase();this.globalProviders.set(n,"function"==typeof t?{name:n,provide:t,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:t)}unregister(e){return this.providers.delete(e.toLowerCase())}unregisterGlobal(e){return this.globalProviders.delete(e.toLowerCase())}get(e){const t=e.toLowerCase();return this.providers.get(t)??this.globalProviders.get(t)}has(e){const t=e.toLowerCase();return this.providers.has(t)||this.globalProviders.has(t)}async resolve(e,t,r){const n=this.get(e);if(!n)return;const o="__provider_"+n.name;if(n.cache&&r?.has(o))return r.get(o);if(n.dependencies)for(const e of n.dependencies)await this.resolve(e,t,r);const i=await n.provide(t);return n.cache&&r&&r.set(o,i),i}resolveSync(e,t,r){const n=this.get(e);if(!n)return;const o="__provider_"+n.name;if(n.cache&&r?.has(o))return r.get(o);const i=n.provide(t);if(i instanceof Promise)throw Error(`Context provider '${e}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(o,i),i}enhance(e){const t=this,r=new Map;return new Proxy(e,{get(e,n,o){if("string"==typeof n&&t.get(n))try{return t.resolveSync(n,e,r)}catch{return t.resolve(n,e,r)}return Reflect.get(e,n,o)},has:(e,r)=>!("string"!=typeof r||!t.has(r))||Reflect.has(e,r)})}async resolveAll(e){const t=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[o,i]of n)try{r[o]=await this.resolve(o,e,t)}catch(e){console.warn(`[ContextProviderRegistry] Failed to resolve '${o}':`,e),r[o]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const A=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,r]of this.types)if(r.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),r=this.types.get(t);return r?.hyperscriptType??"unknown"}coerce(e,t,r){const n=this.types.get(t);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(n.isType(e))return e;if(this.config.cacheCoercions){const r=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const o=this.inferType(e),i=n.coerceFrom?.[o];if(i){const n=i(e,r);if(this.config.cacheCoercions&&null!==n){const r=`${o}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(e,t){const r=this.types.get(t);if(!r)return!1;if(r.isType(e))return!0;const n=this.inferType(e);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(e,t){const r=this.types.get(t);return r&&(e===t||r.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const r=e;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,r)=>{t[r+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function S(e){const t=A.get("String");return t?t.isType(e):"string"==typeof e}function T(e){const t=A.get("Number");return t?t.isType(e):"number"==typeof e}function N(e){const t=A.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function O(e){const t=A.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function C(e){const t=A.get("Function");return t?t.isType(e):"function"==typeof e}function k(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function j(e){return e instanceof Element}const L=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function I(e,t){return L.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const R={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=>k(e)?e.tabIndex:void 0,hidden:e=>k(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e.getAttribute("name");r&&"value"in e&&t.append(r,e.value)}),t}(e)};function $(e,t){if(t.startsWith("computed-")){const r=t.slice(9);return function(e){return e instanceof HTMLElement}(e)?getComputedStyle(e).getPropertyValue(r):void 0}if(t.startsWith("@"))return I(e,t.slice(1));const r=R[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return I(e,t);const n=e[t];return C(n)?n.bind(e):n}function M(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 D(e){return e.me?.ownerDocument??("undefined"!=typeof document?document:null)}function V(e,t){return t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):t.variables?.has(e)?t.variables.get(e):"me"===e?t.me:"it"===e?t.it:"result"===e?t.result:void 0}async function P(e,t){if(e.includes(".")){const r=e.split(".");let n=V(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return V(e,t)}async function B(e,t){if(h(`RESOLVE: Looking for '${e}' in context`,{hasInLocals:t.locals.has(e),localsKeys:Array.from(t.locals.keys()),value:t.locals.get(e)}),t.locals.has(e)){const r=t.locals.get(e);return h(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return h(`RESOLVE: Found '${e}' in globals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return h(`RESOLVE: Found '${e}' in variables (legacy):`,r),r}const r=Number(e);if(!isNaN(r))return r;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split("."),n=r[0];let o=null;if(t.locals.has(n)?o=t.locals.get(n):t.globals&&t.globals.has(n)?o=t.globals.get(n):t.variables&&t.variables.has(n)&&(o=t.variables.get(n)),null!=o){for(let e=1;r.length>e;e++){if(null==o)return void h(`RESOLVE: Property access failed at '${r[e-1]}'`);o=o[r[e]]}return h(`RESOLVE: Property access '${e}' =`,o),o}}return e}async function _(e,t){h("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,o]=r;h("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:o});const i=await B(e.trim(),t);if(h("EVAL: Ternary condition value:",i),i){const e=await B(n.trim(),t);return h("EVAL: Ternary returned true branch:",e),e}{const e=await B(o.trim(),t);return h("EVAL: Ternary returned false branch:",e),e}}const n=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,e,r,o]=n;h("EVAL: Parsed arithmetic:",{left:e,operator:r,right:o});const i=await B(e.trim(),t),s=await B(o.trim(),t);h("EVAL: Resolved values:",{leftValue:i,rightValue:s});const a=Number(i),c=Number(s);if(!isNaN(a)&&!isNaN(c)){let e;switch(r){case"+":e=a+c;break;case"-":e=a-c;break;case"*":e=a*c;break;case"/":e=a/c;break;case"%":e=a%c;break;default:e=a}return h("EVAL: Arithmetic result:",e),e}}const o=await B(e.trim(),t);return h("EVAL: Fallback result:",o),o}function q(e){if(Array.isArray(e)&&1===e.length&&(e=e[0]),null!==e&&"object"==typeof e&&"string"==typeof e.textContent){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?e:r}return 0}return e}async function F(e,t,r,n,o){try{const i=o(await n(e.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const s=M(e.property);if(!s||"string"!=typeof s)throw Error("Invalid method name: "+s);const a=i[s];if("function"!=typeof a)throw Error(`Property "${s}" is not a function on ${i.constructor?.name||typeof i}`);const c=await Promise.all(t.map(e=>n(e,r)));return a.apply(i,c)}catch(e){if(e instanceof Error)throw e;throw Error("Failed to evaluate method call: "+e)}}class H{constructor(){this.expressionRegistry=new Map}registerCategory(e){Object.entries(e).forEach(([e,t])=>{this.expressionRegistry.set(e,t)})}unwrapSelectorResult(e){if(e instanceof NodeList&&e.length>0)return e[0];if(Array.isArray(e)&&e.length>0){const t=e[0];return"index"in e&&"input"in e?e:t instanceof Element||t instanceof Node?t:e}return e}async evaluate(e,t){if(!e)return h("EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));switch(e.type){case"identifier":return this.evaluateIdentifier(e,t);case"literal":return this.evaluateLiteral(e,t);case"string":return e.value??"";case"memberExpression":return this.evaluateMemberExpression(e,t);case"binaryExpression":return this.evaluateBinaryExpression(e,t);case"unaryExpression":return this.evaluateUnaryExpression(e,t);case"callExpression":return this.evaluateCallExpression(e,t);case"selector":return this.evaluateSelector(e,t);case"dollarExpression":return this.evaluateDollarExpression(e,t);case"possessiveExpression":return this.evaluatePossessiveExpression(e,t);case"templateLiteral":return this.evaluateTemplateLiteral(e,t);case"arrayLiteral":return this.evaluateArrayLiteral(e,t);case"objectLiteral":return this.evaluateObjectLiteral(e,t);case"conditionalExpression":return this.evaluateConditionalExpression(e,t);case"cssSelector":return this.evaluateCSSSelector(e,t);case"propertyAccess":return this.evaluatePropertyAccess(e,t);case"propertyOfExpression":return this.evaluatePropertyOfExpression(e,t);case"contextReference":return this.evaluateContextReference(e,t);case"queryReference":return this.evaluateQueryReference(e,t);case"idSelector":return this.evaluateIdSelector(e,t);case"attributeAccess":return this.evaluateAttributeAccess(e,t);default:throw Error("Unsupported AST node type for evaluation: "+e.type)}}async evaluateWithResult(e,t){try{return n(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return o({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return o({type:"exit",returnValue:t.returnValue});if(t.isBreak)return o({type:"break"});if(t.isContinue)return o({type:"continue"});if(t.isReturn)return o({type:"return",returnValue:t.returnValue})}throw e}}async evaluateArrayLiteral(e,t){const r=e.elements||[],n=[];for(const e of r){const r=await this.evaluate(e,t);n.push(r)}return n}async evaluateObjectLiteral(e,t){const r=e.properties||[],n={};for(const e of r){let r;r="identifier"===e.key.type?e.key.name:"literal"===e.key.type?e.key.value+"":await this.evaluate(e.key,t)+"";const o=await this.evaluate(e.value,t);n[r]=o}return n}async evaluateConditionalExpression(e,t){return await this.evaluate(e.test,t)?this.evaluate(e.consequent,t):e.alternate?this.evaluate(e.alternate,t):void 0}async evaluateTemplateLiteral(e,t){return async function(e,t){let r=e.value||"";h("TEMPLATE LITERAL: Evaluating",{template:r,node:e});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,o=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&o.push({match:i[0],varName:i[1],index:i.index});for(let e=o.length-1;e>=0;e--){const{match:n,varName:i,index:s}=o[e],a=await P(i,t);h(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,s)+((a??"")+"")+r.slice(s+n.length)}let s="",a=0;for(;r.length>a;){const e=r.indexOf("${",a);if(-1===e){s+=r.slice(a);break}s+=r.slice(a,e);let n=1,o=e+2;for(;r.length>o&&n>0;)"{"===r[o]&&n++,"}"===r[o]&&n--,n>0&&o++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(e+2,o);let c;h("TEMPLATE: Evaluating expression:",i);const l=i.trim();t.locals.has(l)?(c=t.locals.get(l),h(`TEMPLATE: Found in locals: ${l} =`,c)):t.globals&&t.globals.has(l)?(c=t.globals.get(l),h(`TEMPLATE: Found in globals: ${l} =`,c)):t.variables&&t.variables.has(l)?(c=t.variables.get(l),h(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await _(i,t),h(`TEMPLATE: Evaluated expression "${i}" =`,c)),s+=c+"",a=o+1}return s}(e,t)}async evaluateSimpleExpression(e,t){return _(e,t)}async resolveValue(e,t){return B(e,t)}async evaluateIdentifier(e,t){const{name:r,scope:n}=e;if("me"===r||"my"===r||"I"===r)return t.me;if("you"===r||"your"===r)return t.you;if("it"===r||"its"===r)return t.it;if("result"===r)return t.result;if("event"===r)return t.event;const o=this.expressionRegistry.get(r);return o?o.evaluate(t):"local"===n?t.locals?.has(r)?t.locals.get(r):void 0:"global"===n?t.globals?.has(r)?t.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:t.locals?.has(r)?t.locals.get(r):t.globals?.has(r)?t.globals.get(r):t.variables?.has(r)?t.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(e,t){return e.value}async evaluateContextReference(e,t){const{contextType:r}=e;switch(r){case"me":return t.me;case"it":return t.result;case"you":return t.you;case"event":return t.event;case"body":return t.meta?.ownerDocument?.body||document?.body;case"detail":return t.event?.detail;case"target":return t.you||t.event?.target;case"sender":return t.event?.target;default:return t.locals&&t.locals.has(r)?t.locals.get(r):void h("Unknown context reference type: "+r)}}async evaluateMemberExpression(e,t){const{object:r,property:n,computed:o}=e;if("identifier"===r.type&&["add","remove"].includes(r.name)){const e=r.name,o=M(n);if(!t.me)throw Error('Context element "me" is null');return void("add"===e?t.me.classList.add(o):"remove"===e&&t.me.classList.remove(o))}let i=await this.evaluate(r,t);if(o)return i[await this.evaluate(n,t)];{const e=M(n);if(Array.isArray(i)&&"string"==typeof e&&("length"===e||e in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof e){if(e.startsWith("computed-")){const t=e.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(t):void 0}if(e.startsWith("@")){const t=e.substring(1);return i&&"function"==typeof i.getAttribute?I(i,t):void 0}if(i&&i instanceof Element){if("previous"===e||"prev"===e)return i.previousElementSibling;if("next"===e)return i.nextElementSibling}}const t=i?.[e];return"function"==typeof t?t.bind(i):t}}coerceArithmeticOperand(e){return q(e)}async evaluateBinaryExpression(e,t){return async function(e,t,r,n,o){const{operator:i,left:s,right:a}=e;if("in"===i&&"selector"===s.type){let e=s.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const o=n(await r(a,t));if(!o||"function"!=typeof o.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof o})`);const i=o.querySelectorAll(e);return Array.from(i)}if("in"===i&&"queryReference"===s.type){let e=s.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const o=n(await r(a,t));if(!o||"function"!=typeof o.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof o})`);const i=o.querySelectorAll(e);return Array.from(i)}if("in"===i){let e=null,o=null;if("positionalExpression"===s.type){e=s.operator;const n=s.argument;"cssSelector"===n?.type?o=n.selector:"selector"===n?.type?o=n.value:"classSelector"===n?.type?o="."+n.className:"idSelector"===n?.type?o="#"+n.id:n&&(o=await r(n,t)+"")}else if("memberExpression"!==s.type||"identifier"!==s.object?.type||"first"!==s.object.name&&"last"!==s.object.name){if("callExpression"===s.type&&"identifier"===s.callee?.type&&("first"===s.callee.name||"last"===s.callee.name)){e=s.callee.name;const n=s.arguments?.[0];"selector"===n?.type?o=n.value:"cssSelector"===n?.type?o=n.selector:"classSelector"===n?.type?o="."+n.className:"idSelector"===n?.type?o="#"+n.id:n&&(o=await r(n,t)+"")}}else e=s.object.name,"identifier"===s.property?.type&&s.property.name&&(o="."+s.property.name);if(e&&o){const i=n(await r(a,t));if(!i||"function"!=typeof i.querySelectorAll)return;const s=i.querySelectorAll(o),c=Array.from(s);return"first"===e?c.length>0?c[0]:void 0:"last"===e?c.length>0?c[c.length-1]:void 0:c}}if("matches"===i&&("selector"===a.type||"cssSelector"===a.type||"classSelector"===a.type)){const e=await r(s,t),n=a.value||a.selector;if(e&&"function"==typeof e.matches)try{return e.matches(n)}catch{return!1}return!1}const c=await r(s,t),l=await r(a,t);if("has"===i||"have"===i){if(c instanceof Element){if("cssSelector"===a.type&&"class"===a.selectorType||"selector"===a.type&&a.value?.startsWith(".")){const e=a.selector?.slice(1)||a.value?.slice(1)||"";return c.classList.contains(e)}if("attributeAccess"===a.type||"attributeRef"===a.type){const e=a.attributeName||a.name||a.value?.replace(/^@/,"")||"";return c.hasAttribute(e)}if("cssSelector"===a.type&&"attribute"===a.selectorType){const e=(a.selector||a.value||"").replace(/^@/,"");return c.hasAttribute(e)}if("cssSelector"===a.type&&"id"===a.selectorType||"idSelector"===a.type){const e=(a.selector||a.value||"").replace(/^#/,"");return null!==c.querySelector("#"+CSS.escape(e))}if("selector"===a.type||"queryReference"===a.type){let e=a.value||a.selector||"";e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());try{return null!==c.querySelector(e)}catch{return!1}}if("cssSelector"===a.type){const e=a.selector||"";try{return null!==c.querySelector(e)}catch{return!1}}}return Array.isArray(c)?c.includes(l):"string"==typeof c&&c.includes(l+"")}switch(i){case">":case"is greater than":return c>l;case"<":case"is less than":return l>c;case">=":case"is greater than or equal to":return c>=l;case"<=":case"is less than or equal to":return l>=c;case"==":case"equals":case"is equal to":return c==l;case"===":case"is really equal to":case"really equals":return c===l;case"!=":case"is not equal to":return c!=l;case"!==":case"is not really equal to":return c!==l;case"+":{const e=q(c),r=q(l);if("string"==typeof e||"string"==typeof r){const n=o.get("stringConcatenation");if(n){h("Using string concatenation for:",{leftValue:e,rightValue:r});const o=await n.evaluate(t,{left:e,right:r});return o.success?o.value:e+r}}else{const n=o.get("addition");if(n){h("Using numeric addition for:",{leftValue:e,rightValue:r});const o=await n.evaluate(t,{left:e,right:r});return o.success?o.value:e+r}}return e+r}case"-":return q(c)-q(l);case"*":return q(c)*q(l);case"/":return q(c)/q(l);case"%":case"mod":return q(c)%q(l);case"as":const e="string"==typeof l?l:"identifier"===a.type?a.name:"literal"===a.type?a.value:l+"",r=o.get("as");return r?r.evaluate(t,c,e):c;case"&&":case"and":return c&&l;case"||":case"or":return c||l;case"is":return c===l;case"is not":return c!==l;case"is a":case"is an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"==typeof c;case"number":return"number"==typeof c;case"boolean":return"boolean"==typeof c;case"object":return"object"==typeof c&&null!==c;case"array":return Array.isArray(c);case"function":return"function"==typeof c;case"null":return null===c;case"undefined":return void 0===c;default:const e="identifier"===a.type?a.name:l+"";return null!=c&&c.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"!=typeof c;case"number":return"number"!=typeof c;case"boolean":return"boolean"!=typeof c;case"object":return!("object"==typeof c&&null!==c);case"array":return!Array.isArray(c);case"function":return"function"!=typeof c;case"null":return null!==c;case"undefined":return void 0!==c;default:const e="identifier"===a.type?a.name:l+"";return!(null!=c&&c.constructor?.name===e)}case"=":if("identifier"===s.type){const e=s.name;return"result"===e?t.result=l:"it"===e?t.it=l:"you"===e?t.you=l:t.locals.set(e,l),l}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):!(!c||"function"!=typeof c.matches)&&c.matches(l+"");case"match":case"matches":if(c&&"function"==typeof c.matches){const e="string"==typeof l?l:l+"";try{return c.matches(e)}catch{return!1}}return!1;case"in":const n="string"==typeof c?c:c+"",u=l;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(c);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof c&&"string"==typeof l?{command:c,selector:l}:"identifier"===s.type&&"selector"===a.type?{command:s.name,selector:a.value}:l;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(e,t){const{operator:r,argument:n}=e,o=await this.evaluate(n,t);switch(r){case"not":case"!":const e=this.expressionRegistry.get("not");return e?e.evaluate(t,o):!o;case"no":const n=this.expressionRegistry.get("no");return!!n&&n.evaluate(t,o);case"some":return null!=o&&("string"==typeof o||Array.isArray(o)||o instanceof NodeList||o instanceof HTMLCollection?o.length>0:"object"!=typeof o||Object.keys(o).length>0);case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(t,o):null!=o;case"does not exist":const s=this.expressionRegistry.get("doesNotExist");return s?s.evaluate(t,o):null==o;case"-":return-o;case"+":return+o;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(e,t){return async function(e,t,r,n,o,i){const{callee:s,arguments:a,isConstructor:c}=e;if(c){const e=s.name,n=t.globals?.get(e)||window[e];if("function"==typeof n)return new n(...await Promise.all(a.map(e=>r(e,t))));throw Error("Unknown constructor: "+e)}if("memberExpression"===s.type||"propertyAccess"===s.type)return F(s,a,t,r,n);const l=s.name||s,u=o.get(l);if(u){const e=["first","last","random","at"],n=["closest","previous","next"].includes(l),o=e.includes(l),s=await Promise.all(a.map(e=>n&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:n&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:o&&e&&"selector"===e.type&&"string"==typeof e.value?i(e,t):r(e,t)));return u.evaluate(t,...s)}const f=t.globals?.get(l)||window[l];if("function"==typeof f)return f(...await Promise.all(a.map(e=>r(e,t))));throw Error("Unknown function: "+l)}(e,t,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(e,t,r){return F(e,t,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(e,t){return function(e,t){let r=e.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=D(t);if(!n)return[];const o=n.querySelectorAll(r);return Array.from(o).filter(e=>e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.tagName)}(e,t)}evaluateAttributeAccess(e,t){return t.me&&"function"==typeof t.me.getAttribute?I(t.me,e.attributeName):"@"+e.attributeName}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(e,t){const r=await this.evaluate(e.expression,t);if("identifier"===e.expression.type){const r=e.expression.name;return/^\d+$/.test(r)?r:t.locals?.has(r)?t.locals.get(r):"me"===r&&t.me?t.me:"you"===r&&t.you?t.you:"it"===r&&t.it?t.it:"result"===r&&t.result?t.result:"undefined"!=typeof window&&"window"===r?window:t.globals?.has(r)?t.globals.get(r):void 0}return r}async evaluatePossessiveExpression(e,t){const{object:r,property:n}=e,o=this.unwrapSelectorResult(await this.evaluate(r,t));if(!o)return;const i=M(n);return"string"==typeof i&&j(o)?$(o,i):o[i]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){return function(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=D(t);if(!n)return"id"===e.selectorType?null:[];if("id"===e.selectorType){const e=r.startsWith("#")?r.slice(1):r;return n.getElementById(e)}if("class"===e.selectorType){const e=r.replace(/:/g,"\\:"),t=n.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const o=n.querySelectorAll(r);return Array.from(o).filter(e=>e instanceof HTMLElement)}(e,t)}async evaluateIdSelector(e,t){return function(e,t){const r=D(t);if(!r)return null;const n=e.value.startsWith("#")?e.value.slice(1):e.value;return r.getElementById(n)}(e,t)}async evaluateQueryReference(e,t){return function(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=D(t);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(e,t)}async evaluatePropertyAccess(e,t){const r=await this.evaluate(e.object,t),n=e.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const o=n.name||n.value;if(!o)throw Error("Property name must be an identifier");try{let e;return e=j(r)?$(r,o):r[o],"function"==typeof e?e.bind(r):e}catch(e){throw Error(`Error accessing property "${o}": ${e}`)}}async evaluatePropertyOfExpression(e,t){const r=e.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const o=this.unwrapSelectorResult(await this.evaluate(e.target,t));if(null==o)throw Error(`Cannot access property "${n}" of ${o}`);try{let e;return e=j(o)?$(o,n):o[n],"function"==typeof e?e.bind(o):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const U={1:"one",2:"two",3:"three",4:"four",5:"five"};function W(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${o=t,U[o]??o+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var o;return null}function J(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function z(e,t,r){return W(e,1,t,r)??J(e,0,t,r)}function Z(e,t){return W(e,2,t,"left, right")}function G(){return null}function X(e,t,r,n){return e.length>t?`${r} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${n?` (${n})`:""}`:null}function Y(e,t,r,n,o){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${o?` (${o})`:""}`:null}function K(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const Q="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 ee;function te(){return ee({validate:e=>({success:!0,data:e})})}function re(e,t){if(Q)return te();const r=ee({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:K("type-mismatch","Expected object, received "+typeof r)};const n=r,o={};if(t?.strict){const t=Object.keys(e),r=Object.keys(n).filter(e=>!t.includes(e));if(r.length>0)return{success:!1,error:K("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=n[t];if(!(t in n)&&!r.t)return{success:!1,error:K("missing-argument",`Required field "${t}" is missing`,t)};const i=r.validate(e);if(!i.success)return{success:!1,error:K("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};void 0!==i.data&&(o[t]=i.data)}return{success:!0,data:o}}});return r.strict=()=>re(e,{strict:!0}),r}ee=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 ee(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&e>n.data.length?{success:!1,error:K("runtime-error",`String must be at least ${e} characters long`)}:n}};return ee(r)}),e.max||(e.max=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&n.data.length>e?{success:!1,error:K("runtime-error",`String must be at most ${e} characters long`)}:n}};return ee(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,o:e,i:!0,validate:r=>void 0===r?{success:!0,data:e}:t(r)};return ee(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const r=this.validate.bind(this),n={...this,validate:n=>{const o=r(n);return o.success?e(o.data)?o:{success:!1,error:K("runtime-error",t||"Refinement validation failed")}:o}};return ee(n)}),new Proxy(e,{get:(e,t,r)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,r):function(...e){return r}})};const ne=e=>function(e={}){return Q?te():ee({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:K("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:K("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:K("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:K("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:K("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),oe=e=>function(e={}){return Q?te():ee({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:K("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:K("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:K("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{}),ie=()=>Q?te():ee({validate:e=>"boolean"!=typeof e?{success:!1,error:K("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),se=e=>re(e),ae=e=>function(e){return Q?te():ee({validate:t=>{if(!Array.isArray(t))return{success:!1,error:K("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:K("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const r=[];for(let n=0;e.length>n;n++){const o=e[n].validate(t[n]);if(!o.success)return{success:!1,error:K("runtime-error",o.error.message,o.error.path?`${n}.${o.error.path}`:""+n)};r.push(o.data)}return{success:!0,data:r}}})}(e),ce=()=>te(),le=()=>te(),ue=()=>function(e,t="Custom validation failed"){return Q?te():ee({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:K("runtime-error",t)}})}(e=>void 0===e,"Expected undefined");class fe{trackPerformance(e,t,r,n){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:t,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(e,t,r,n=(r?"success":"error")){e.evaluationHistory&&e.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:t,duration:Date.now()-t,success:r})}toBoolean(e){return!(!1===e||0===e||0n===e||""===e||null==e||T(e)&&isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,r,n,o=[]){return{success:!1,error:{name:e,type:t,message:r,code:n,suggestions:o}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":O(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":S(e)?"String":T(e)?"Number":N(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):S(e)?e.split(""):null==e?[]:O(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(T(e)&&Number.isFinite(e))return e;if(S(e)){const t=Number(e);return Number.isFinite(t)?t:null}return N(e)?e?1:0:null}}class de extends fe{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=ue(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.me,o=this.isElement(n)?n:null,i=this.success(o,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const o=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(e,t,o,r),o}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}}class pe extends fe{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=ue(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.you,o=this.isElement(n)?n:null,i=this.success(o,"element");return this.trackPerformance(e,t,i,r),i}catch(n){const o=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(e,t,o,r),o}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}}class me extends fe{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=ue(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=e.it,o={success:!0,value:n,type:this.inferType(n)};return this.trackPerformance(e,t,o,r),o}catch(n){const o=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(e,t,o,r),o}}validate(e){return void 0!==e?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}}const he=se({selector:ne().min(1),single:ie().optional().default(!1)});class ye extends fe{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=he,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(e,t){const r=Date.now();try{if(!this.isValidCSSSelector(t.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${t.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(e,t,n,r),n}let n;if(t.single)n=document.querySelector(t.selector);else{const e=Array.from(document.querySelectorAll(t.selector));n=e.length>0?e:null}const o={success:!0,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(e,t,o,r),o}catch(n){const o=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);if(!t.success)return{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid input: "+e.message,suggestions:this.getValidationSuggestion(e.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=t.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(e){try{return document.querySelector(e),!0}catch{return!1}}getValidationSuggestion(e){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[e]||"Check input format and types"]}}new de,new pe,new me,new ye;const ve={name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:G},ge={name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:G},be={name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:G},we={name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:G},Ee={name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:G},xe={name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:e=>z(e,"querySelector","selector")},Ae={name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>z(e,"querySelectorAll","selector")},Se={name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:e=>z(e,"getElementById","ID")},Te={name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:e=>z(e,"getElementsByClassName","className")},Ne={name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let r=t[0];if(r&&"object"==typeof r&&"type"in r){const e=r;"identifier"===e.type&&e.name?r=e.name:"literal"===e.type&&"string"==typeof e.value&&(r=e.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return e.me?e.me.closest(r):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];return"string"==typeof t||t&&"object"==typeof t&&"type"in t&&("identifier"===t.type||"literal"===t.type)?null:"closest selector must be a string or identifier"}},Oe={name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:G},Ce={name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:G},ke={name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:G},je={name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>z(e,"elementWithSelector","selector")},Le={name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const o=n||e.me;if(o&&o instanceof HTMLElement){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(r)||void 0}},validate:e=>Y(e,1,2,"styleRef","property, optional element")??J(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},Ie={name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let o=null;if("my"===r&&e.me?o=e.me instanceof HTMLElement?e.me:null:"its"===r&&e.it&&(o=e.it instanceof HTMLElement?e.it:null),o){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(n)||void 0}},validate:e=>W(e,2,"possessiveStyleRef","possessor, property")??J(e,0,"possessiveStyleRef","possessor")??J(e,1,"possessiveStyleRef","property")},Re={name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let o=null;if("me"===n&&e.me?o=e.me instanceof HTMLElement?e.me:null:"it"===n&&e.it&&(o=e.it instanceof HTMLElement?e.it:null),o){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(r)||void 0}},validate:e=>W(e,2,"ofStyleRef","property, reference")??J(e,0,"ofStyleRef","property")??J(e,1,"ofStyleRef","reference")},$e={me:ve,you:ge,it:be,its:we,result:Ee,querySelector:xe,querySelectorAll:Ae,getElementById:Se,getElementsByClassName:Te,closest:Ne,parent:Oe,window:Ce,document:ke,elementWithSelector:je,styleRef:Le,possessiveStyleRef:Ie,ofStyleRef:Re};var Me=Object.freeze({__proto__:null,CSSSelectorExpression:ye,ItExpression:me,MeExpression:de,YouExpression:pe,classExpression:Te,closestExpression:Ne,createItExpression:function(){return new me},createMeExpression:function(){return new de},createYouExpression:function(){return new pe},documentExpression:ke,elementWithSelectorExpression:je,idExpression:Se,itExpression:be,itsExpression:we,meExpression:ve,ofStyleRefExpression:Re,parentExpression:Oe,possessiveStyleRefExpression:Ie,querySelectorAllExpression:Ae,querySelectorExpression:xe,referencesExpressions:$e,resultExpression:Ee,styleRefExpression:Le,windowExpression:Ce,youExpression:ge});class De{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.timestamp<=this.ttl)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU();const r={result:t,timestamp:Date.now(),accessCount:1};this.cache.set(e,r),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[r,n]of this.accessOrder)t>n&&(t=n,e=r);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,r)=>e+(t-r.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const Ve=new class{constructor(){this.domQueryCache=new De(200,3e3),this.exprResultCache=new De(500,2e3),this.cssMatchCache=new De(100,5e3),this.formValueCache=new De(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(e);return this.domQueryCache.set(t,n),n}querySelectorAll(e){const t="querySelectorAll:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,n),n}getElementById(e){const t="getElementById:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(e);return this.domQueryCache.set(t,n),n}getElementsByClassName(e){const t="getElementsByClassName:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,n),n}matches(e,t){const r=`matches:${this.getElementCacheKey(e)}:${t}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const o=e.matches(t);return this.cssMatchCache.set(r,o),o}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),r=this.formValueCache.get("formValue:"+t);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(e,t){const r=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+r,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(e.cache.keys()))"string"==typeof r&&r.includes(t)&&e.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),r=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${r}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([r,n])=>{e-n.timestamp>t.ttl&&t.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{Ve.cleanup()},1e4);const Pe=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]);var Be;!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"}(Be||(Be={}));const _e=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const r=performance.now()-t;return this.startTimes.delete(e),r}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=Ve.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 qe(){Ve.cleanup(),_e.getMetrics().memoryUsage>52428800&&_e.reset()}let Fe=null;function He(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const r=e.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${t} cannot be converted to number: "${e}"`);return n}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const r=e[0];if(Array.isArray(r))throw Error(t+" is a nested array, cannot convert to number");return He(r,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const r=parseFloat(e);if(!isNaN(r))return r}}const r=e.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Ue(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?null:r}return"boolean"==typeof e?e?1:0:null==e?0:null}function We(e,t,r){if("==="===r)return e===t;if("!=="===r)return e!==t;if(null==e||null==t)return function(e,t,r){if(null==e&&null==t)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,r);const[n,o]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const r=parseFloat(e),n=parseFloat(t);return isNaN(r)||isNaN(n)?[e,t]:[r,n]}const r=Ue(e),n=Ue(t);return null!==r&&null!==n?[r,n]:[e+"",t+""]}(e,t);switch(r){case">":return n>o;case"<":return o>n;case">=":return n>=o;case"<=":return o>=n;case"==":return Je(e,t);case"!=":return!Je(e,t);default:return!1}}function Je(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const r=parseFloat(t);return!isNaN(r)&&e===r}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);return!isNaN(r)&&r===t}return"boolean"==typeof e?Je(e?1:0,t):"boolean"==typeof t?Je(e,t?1:0):e+""==t+""}function ze(e,t,r,n,o,i=!0,s){return t&&"object"==typeof t&&"evaluationHistory"in t&&Array.isArray(t.evaluationHistory)&&t.evaluationHistory.push({expressionName:e.name,category:e.category,input:r,output:n,timestamp:o,duration:Date.now()-o,success:i,...void 0!==s&&{error:s}}),n}"undefined"!=typeof window&&function(e=3e4){Fe&&clearInterval(Fe),Fe=setInterval(qe,e)}();const Ze=se({left:ce().describe("Left operand value"),right:ce().describe("Right operand value")}).strict(),Ge=se({operand:ce().describe("Operand value to negate")}).strict();class Xe extends fe{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=Ze,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.toBoolean(t.left);if(!o)return this.trackSimple(e,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(t.right),s=o&&i;return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(t instanceof Error?t.message:t+""),"AND_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid AND operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Ye extends fe{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=Ze,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.toBoolean(t.left);if(o)return this.trackSimple(e,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(t.right),s=o||i;return this.trackSimple(e,r,!0,"boolean"),this.success(s,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(t instanceof Error?t.message:t+""),"OR_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid OR operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Ke extends fe{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=Ge,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=!this.toBoolean(t.operand);return this.trackSimple(e,r,!0,"boolean"),this.success(o,"boolean")}catch(t){return this.trackSimple(e,r,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(t instanceof Error?t.message:t+""),"NOT_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid NOT operation input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function Qe(){return new Xe}function et(){return new Ye}function tt(){return new Ke}function rt(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}Qe(),et(),tt();const nt=ae([ce(),ce()]),ot=ae([ce(),ne()]),it={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return ze(this,e,[t,r],t==r,n)}catch(o){throw ze(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>Z(e,"equals"),inputSchema:nt,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"]}},st={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t===r;return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"strictEquals")},at={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t!=r;return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"notEquals")},ct={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t!==r;return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"strictNotEquals")},lt={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=We(t,r,"<");return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"lessThan")},ut={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=We(t,r,"<=");return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"lessThanOrEqual")},ft={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=We(t,r,">");return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"greaterThan")},dt={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=We(t,r,">=");return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"greaterThanOrEqual")},pt={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return ze(this,e,[t,r],t&&r,n)}catch(o){throw ze(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>Z(e,"and"),inputSchema:nt,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"]}},mt={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=t||r;return n&&ze(this,e,[t,r],i,o),i},validate:e=>Z(e,"or")},ht={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=!t;return r&&ze(this,e,[t],o,n),o},validate:e=>W(e,1,"not","operand")},yt={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let o;return o=null==t||(S(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!O(t)||0!==Object.keys(t).length)),r&&ze(this,e,[t],o,n),o},validate:e=>W(e,1,"isEmpty","value")},vt={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0;let o;return o=null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!(S(t)||t instanceof Node||t instanceof Element||!O(t)||0!==Object.keys(t).length)),r&&ze(this,e,[t],o,n),o},validate:e=>W(e,1,"no","value")},gt={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=!await yt.evaluate(e,t);return r&&ze(this,e,[t],o,n),o},validate:e=>W(e,1,"isNotEmpty","value")},bt={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=null!=t;return r&&ze(this,e,[t],o,n),o},validate:e=>W(e,1,"exists","value")},wt={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(e,t){const r=e.evaluationHistory,n=r?Date.now():0,o=null==t;return r&&ze(this,e,[t],o,n),o},validate:e=>W(e,1,"doesNotExist","value")},Et={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0;let i;if(t&&r){if(rt(t)&&rt(r))return i=t.contains(r),n&&ze(this,e,[t,r],i,o),i;if(S(t)&&t.match(/^[.#][\w-]+$/)){const s=document.querySelector(t);if(s&&rt(r))return i=s.contains(r),n&&ze(this,e,[t,r],i,o),i;if(s&&S(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=!!a&&s.contains(a),n&&ze(this,e,[t,r],i,o),i}}if(S(r)&&r.match(/^[.#][\w-]+$/)&&rt(t)){const s=document.querySelector(r);return i=!!s&&t.contains(s),n&&ze(this,e,[t,r],i,o),i}}return i=S(t)&&S(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!O(t)||!S(r))&&r in t,n&&ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"contains","container, value")},xt={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!await Et.evaluate(e,t,r);return n&&ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"doesNotContain","container, value")},At={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!(!S(t)||!S(r))&&t.startsWith(r);return n&&ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"startsWith","str, prefix")},St={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!(!S(t)||!S(r))&&t.endsWith(r);return n&&ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"endsWith","str, suffix")},Tt={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let o;if(t instanceof Element&&S(r)){const e=r;if(e.startsWith(".")||e.startsWith("#")||e.startsWith(":")||e.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(e))try{o=function(e,t){return Ve.matches(e,t)}(t,e)}catch(e){o=!1}else o=!1}else if(S(t)&&S(r)){const e=t,n=r;try{o=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(e)}catch(t){o=e.includes(n)}}else o=!1;return ze(this,e,[t,r],o,n)}catch(o){throw ze(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>W(e,2,"matches","element, selector"),inputSchema:ot,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"]}},Nt={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0;let i=!1;if(t instanceof Element&&S(r)){const e=r;e.startsWith(".")?i=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(i=t.hasAttribute(e.slice(1,-1)))}return n&&ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"has","element, selector")},Ot={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(e,t,r){const n=e.evaluationHistory,o=n?Date.now():0,i=!await Nt.evaluate(e,t,r);return n&&ze(this,e,[t,r],i,o),i},validate:e=>W(e,2,"doesNotHave","element, selector")},Ct={equals:it,strictEquals:st,notEquals:at,strictNotEquals:ct,lessThan:lt,lessThanOrEqual:ut,greaterThan:ft,greaterThanOrEqual:dt,and:pt,or:mt,not:ht,no:vt,isEmpty:yt,isNotEmpty:gt,exists:bt,doesNotExist:wt,contains:Et,doesNotContain:xt,startsWith:At,endsWith:St,matches:Tt,has:Nt,doesNotHave:Ot};var kt=Object.freeze({__proto__:null,AndExpression:Xe,NotExpression:Ke,OrExpression:Ye,andExpression:pt,containsExpression:Et,createAndExpression:Qe,createNotExpression:tt,createOrExpression:et,doesNotContainExpression:xt,doesNotExistExpression:wt,doesNotHaveExpression:Ot,endsWithExpression:St,equalsExpression:it,existsExpression:bt,greaterThanExpression:ft,greaterThanOrEqualExpression:dt,hasExpression:Nt,isEmptyExpression:yt,isNotEmptyExpression:gt,lessThanExpression:lt,lessThanOrEqualExpression:ut,logicalExpressions:Ct,matchesExpression:Tt,noExpression:vt,notEqualsExpression:at,notExpression:ht,orExpression:mt,startsWithExpression:At,strictEqualsExpression:st,strictNotEqualsExpression:ct});function jt(e,t,r,n,o="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:o,message:r,code:t,suggestions:n}}}function Lt(e,t){return{success:!0,value:e,type:t}}function It(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const Rt={Array:(e,t)=>{try{return Array.isArray(e)?Lt(e,"array"):e instanceof NodeList?Lt(Array.from(e),"array"):Lt(null==e?[]:[e],"array")}catch(e){return jt("Array","ARRAY_CONVERSION_FAILED",It("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?Lt("","string"):S(e)?Lt(e,"string"):O(e)?Lt(JSON.stringify(e),"string"):Lt(e+"","string")}catch(e){return jt("String","STRING_CONVERSION_FAILED",It("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(N(e))return Lt(e,"boolean");if(null==e)return Lt(!1,"boolean");if(S(e)){const t=e.toLowerCase().trim();return Lt("false"!==t&&"0"!==t&&""!==t,"boolean")}return T(e)?Lt(0!==e&&!isNaN(e),"boolean"):Lt(!!e,"boolean")}catch(e){return jt("Boolean","BOOLEAN_CONVERSION_FAILED",It("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(T(e))return Lt(e,"number");if(null==e)return Lt(0,"number");const t=Number(e);return isNaN(t)?jt("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):Lt(t,"number")}catch(e){return jt("Number","NUMBER_CONVERSION_FAILED",It("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=Rt.Number(e,t);return r.success?Lt(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=Rt.Number(e,t);return r.success?Lt(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return Lt(e,"object");if(null==e)return Lt(new Date(""),"object");if(S(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return Lt(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?jt("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"):Lt(t,"object")}catch(e){return jt("Date","DATE_CONVERSION_FAILED",It("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return Lt(JSON.stringify(e),"string")}catch(e){return jt("JSON","JSON_STRINGIFY_FAILED",It("Failed to convert value to JSON",e),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(e,t)=>{try{if(O(e))return Lt(e,"object");if(S(e))try{return Lt(JSON.parse(e),"object")}catch(e){return jt("Object","JSON_PARSE_FAILED",It("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return Lt({},"object")}catch(e){return jt("Object","OBJECT_CONVERSION_FAILED",It("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 Lt(Pt(e),"object");if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{const t=e;if(t.name){const e=Bt(t);void 0!==e&&(r[t.name]=e)}}),Lt(r,"object")}return Lt({},"object")}catch(e){return jt("FormValues","FORM_VALUES_EXTRACTION_FAILED",It("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},$t=se({value:le(),type:ne().min(1)});class Mt extends fe{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=$t,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:o,type:i}=t;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),s=n?parseInt(n[1],10):2,a=Rt.Number(o,e);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(s),type:"string"};return this.trackPerformance(e,t,c,r),c}let s=Rt[i];if(s){const n=s(o,e);return this.trackPerformance(e,t,n,r),n}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"}[i.toLowerCase()];if(a&&(s=Rt[a],s)){const n=s(o,e);return this.trackPerformance(e,t,n,r),n}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(e,t,c,r),c}catch(n){const o={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:e.message,suggestions:["Expected valid input structure, got: "+e.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(e){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}}const Dt=se({value:le(),type:ne().min(1)});new Mt,new class extends fe{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=Dt,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:o,type:i}=t,s=i.toLowerCase();let a;switch(s){case"null":a=null===o;break;case"undefined":a=void 0===o;break;case"string":a=S(o);break;case"number":a=T(o)&&!isNaN(o);break;case"boolean":a=N(o);break;case"object":a=O(o);break;case"array":a=Array.isArray(o);break;case"function":a=C(o);break;case"date":a=o instanceof Date;break;case"element":a=o instanceof Element;break;case"node":a=o instanceof Node;break;case"node-list":a=o instanceof NodeList;break;case"empty":a=null==o||""===o||Array.isArray(o)&&0===o.length||O(o)&&0===Object.keys(o).length;break;default:a=o?.constructor?.name?.toLowerCase()===s}const c=this.success(a,"boolean");return this.trackPerformance(e,t,c,r),c}catch(n){const o=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(e,t,o,r),o}}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 Vt={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":S(e)?e:O(e)?JSON.stringify(e):e+"",Boolean:e=>{if(N(e))return e;if(null==e)return!1;if(S(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return T(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(T(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(T(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(!T(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=Vt.Number(e);return Math.trunc(t)},Float:e=>{const t=Vt.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(S(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)}return new Date(e)},JSON:e=>{try{return JSON.stringify(e)}catch(e){return"{}"}},Object:e=>{if(O(e))return e;if(S(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{S(e)||(e=Vt.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>S(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:Vt.String(e)).join(""):e instanceof Element?e.outerHTML:Vt.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return Pt(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=Bt(e))}),r}return{}},"Values:Form":(e,t)=>{const r=Vt.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=Vt.Values(e,t);return JSON.stringify(r)}};function Pt(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Bt(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}function Bt(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}function _t(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}const qt={name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:e}=_t(n);return Vt.Number(r).toFixed(e||2)}let o=Vt[n];if(o)return o(r,e);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(o=Vt[i],o)?o(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>W(e,2,"as","value, type")??J(e,1,"as","conversion type")},Ft={name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!S(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return S(r);case"number":return T(r)&&!isNaN(r);case"boolean":return N(r);case"object":return O(r);case"array":return Array.isArray(r);case"function":return C(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||O(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>W(e,2,"is","value, type")??J(e,1,"is","type")},Ht={name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>W(e,1,"async","expression")},Ut={as:qt,is:Ft,async:Ht};var Wt=Object.freeze({__proto__:null,AsExpression:Mt,asExpression:qt,asyncExpression:Ht,conversionExpressions:Ut,createAsExpression:function(){return new Mt},defaultConversions:Vt,getFormValues:function(e){const t=new FormData(e),r={};for(const[e,n]of t.entries())void 0!==r[e]?(Array.isArray(r[e])||(r[e]=[r[e]]),r[e].push(n)):r[e]=n;return r},getFormValuesProcessed:Pt,getInputValue:Bt,isExpression:Ft,parseFixedPrecision:_t});const Jt={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"},zt=se({collection:ce().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Zt=se({collection:ce().describe("Collection to access"),index:oe().describe("Index position to access")}).strict(),Gt=se({collection:ce().describe("Collection to select random item from")}).strict();class Xt extends fe{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=zt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection),i=o.length>0?o[0]:void 0,s={success:!0,value:i,type:Jt[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,s,r),s}catch(n){const o=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid first input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Yt extends fe{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=zt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection),i=o.length>0?o[o.length-1]:void 0,s={success:!0,value:i,type:Jt[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,s,r),s}catch(n){const o=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():{isValid:!1,errors:t.error?.errors.map(e=>({type:"type-mismatch",message:"Invalid last input: "+e.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function Kt(){return new Xt}function Qt(){return new Yt}Kt(),Qt(),new class extends fe{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=Zt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection),i=this.normalizeIndex(t.index,o.length),s=i>=0&&o.length>i?o[i]:void 0,a={success:!0,value:s,type:Jt[this.inferEvaluationType(s)]};return this.trackPerformance(e,t,a,r),a}catch(n){const o=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}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 fe{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=Gt,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return{success:!1,error:n.errors[0]};const o=this.normalizeCollection(t.collection);if(0===o.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(e,t,n,r),n}const i=o[this.getSecureRandomIndex(o.length)],s={success:!0,value:i,type:Jt[this.inferEvaluationType(i)]};return this.trackPerformance(e,t,s,r),s}catch(n){const o=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(e,t,o,r),o}}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 er={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const r=void 0!==t?t:e.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:S(r)?r.length>0?r[0]:null:O(r)&&"length"in r&&T(r.length)&&r.length>0?r[0]:null},validate:e=>X(e,1,"first","collection")},tr={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const e=r.children;return e.length>0?e[e.length-1]:null}return S(r)?r.length>0?r[r.length-1]:null:O(r)&&"length"in r&&T(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>X(e,1,"last","collection")},rr={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!T(r))throw Error("Index must be a number");const o=r,i=void 0!==n?n:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>o?e.length+o:o;return t>=0&&e.length>t?e[t]:null}if(S(i)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(O(i)&&"length"in i&&T(i.length)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>Y(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)},nr={name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[r,n]=t,o=n||e.me;return o&&o instanceof Element?r?ir(o,r):o.nextElementSibling:null},validate:e=>X(e,2,"next","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},or={name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(e,...t){const[r,n]=t,o=n||e.me;return o&&o instanceof Element?r?sr(o,r):o.previousElementSibling:null},validate:e=>X(e,2,"previous","optional selector, optional fromElement")||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")};function ir(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;const e=r.querySelector(t);if(e)return e;r=r.nextElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?ir(n,t):null}function sr(e,t){let r=e.previousElementSibling;for(;r;){const e=Array.from(r.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(r.matches(t))return r;r=r.previousElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?sr(n,t):null}const ar={name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(e,...t){const[r,n,o]=t,i=o||e.me;if(!(i&&i instanceof Element))return null;const s=i.closest(n);return s?lr(i,r,s):null},validate:e=>Y(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")},cr={name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[r,n,o]=t,i=o||e.me;if(!(i&&i instanceof Element))return null;const s=i.closest(n);return s?ur(i,r,s):null},validate:e=>Y(e,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")};function lr(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=fr(e);for(const e of n)if(fr(e)>o)return e;return null}function ur(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=fr(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(o>fr(t))return t}return null}function fr(e){let t=0,r=e;for(;r&&r.parentElement;)t+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,t+=1e3;return t}const dr={first:er,last:tr,at:rr,next:nr,previous:or,nextWithin:ar,previousWithin:cr};var pr=Object.freeze({__proto__:null,FirstExpression:Xt,LastExpression:Yt,atExpression:rr,createFirstExpression:Kt,createLastExpression:Qt,findNextElementInDOM:ir,findNextElementWithinContainer:lr,findPreviousElementInDOM:sr,findPreviousElementWithinContainer:ur,firstExpression:er,getElementPosition:fr,lastExpression:tr,nextExpression:nr,nextWithinExpression:ar,positionalExpressions:dr,previousExpression:or,previousWithinExpression:cr});const mr=new Set(["__proto__","constructor","prototype"]),hr={name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[r,n]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return $(r,n);if(O(r)){if(mr.has(n))return;return r[n]}return r[n]}},validate:e=>W(e,2,"possessive","element, property")??J(e,1,"possessive","property name")},yr={name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[r]=t;if(e.me){if("string"!=typeof r)throw Error("Property name must be a string");if(e.me instanceof Element)return $(e.me,r);if(O(e.me)){if(mr.has(r))return;return e.me[r]}return e.me[r]}},validate:e=>z(e,"my","property")},vr={name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[r]=t;if(null==e.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=e.it;if(n instanceof Element)return $(n,r);if(O(n)){if(mr.has(r))return;return n[r]}return n[r]},validate:e=>z(e,"its","property")},gr={name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[r]=t;if(e.you){if("string"!=typeof r)throw Error("Property name must be a string");if(e.you instanceof Element)return $(e.you,r);if(O(e.you)){if(mr.has(r))return;return e.you[r]}return e.you[r]}},validate:e=>z(e,"your","property")},br={name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[r,n]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return $(n,r);if(O(n)){if(mr.has(r))return;return n[r]}return n[r]}},validate:e=>W(e,2,"of","property, object")??J(e,0,"of","property name")},wr={name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");const o=n||e.me;return o&&o instanceof Element?o.getAttribute(r):null},validate:e=>Y(e,1,2,"attribute","attributeName, optional element")??J(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},Er={name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[r,n,o]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=o||e.me;return!!(i&&i instanceof Element)&&i.getAttribute(r)===n},validate:e=>Y(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??J(e,0,"attributeWithValue","attribute name")??J(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},xr={name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,o=document.getElementsByClassName(n);return Array.from(o)},validate:e=>z(e,"classReference","className")},Ar={name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:e=>z(e,"idReference","idValue")},Sr={possessive:hr,my:yr,its:vr,your:gr,of:br,attribute:wr,attributeWithValue:Er,classReference:xr,idReference:Ar};var Tr=Object.freeze({__proto__:null,attributeExpression:wr,attributeWithValueExpression:Er,classReferenceExpression:xr,getElementProperty:$,idReferenceExpression:Ar,isAriaAttribute:function(e){return e.startsWith("aria-")||"aria"===e},isDataAttribute:function(e){return e.startsWith("data-")||"data"===e},itsExpression:vr,myExpression:yr,ofExpression:br,possessiveExpression:hr,propertiesExpressions:Sr,yourExpression:gr});const Nr=se({value:ne().describe("String literal value")}).strict(),Or=se({value:oe().describe("Number literal value")}).strict(),Cr=se({value:ie().describe("Boolean literal value")}).strict(),kr=se({left:ce().describe("Left operand"),right:ce().describe("Right operand")}).strict();class jr extends fe{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=Nr,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid){const t=this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(e,r,!1),t}let o=t.value;(o.includes("${")||o.includes("$"))&&(o=this.interpolateString(o,e));const i=this.success(o,"string");return this.trackSimple(e,r,!0,o),i}catch(t){return this.trackSimple(e,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let r=e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=this.resolveExpression(r.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,r)=>{try{const e=this.resolveVariable(r,t);return void 0!==e?e+"":""}catch(e){return""}}),r}resolveExpression(e,t){if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):void 0}}class Lr extends fe{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Or,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?Number.isFinite(t.value)?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Ir extends fe{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Cr,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Rr extends fe{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=kr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const o=He(t.left,"left operand")+He(t.right,"right operand");return this.trackSimple(e,r,!0,o),this.success(o,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""),"ADDITION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class $r extends fe{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=kr,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const o=this.convertToString(t.left)+this.convertToString(t.right);return this.trackSimple(e,r,!0,o),this.success(o,"string")}catch(t){return this.trackSimple(e,r,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=kr.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(S(e))return e;if(T(e))return""+e;if(N(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}class Mr extends fe{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=kr,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);const o=He(t.left,"left operand")*He(t.right,"right operand");return this.trackSimple(e,r,!0,o),this.success(o,"number")}catch(t){return this.trackSimple(e,r,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""),"MULTIPLICATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}function Dr(){return new jr}function Vr(){return new Lr}function Pr(){return new Ir}function Br(){return new Rr}function _r(){return new $r}function qr(){return new Mr}const Fr={stringLiteral:Dr(),numberLiteral:Vr(),booleanLiteral:Pr(),addition:Br(),stringConcatenation:_r(),multiplication:qr()};var Hr=Object.freeze({__proto__:null,AdditionExpression:Rr,BooleanLiteralExpression:Ir,MultiplicationExpression:Mr,NumberLiteralExpression:Lr,StringConcatenationExpression:$r,StringLiteralExpression:jr,createAdditionExpression:Br,createBooleanLiteralExpression:Pr,createMultiplicationExpression:qr,createNumberLiteralExpression:Vr,createStringConcatenationExpression:_r,createStringLiteralExpression:Dr,specialExpressions:Fr});class Ur extends H{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory($e),this.registerCategory(Ct),this.registerCategory(Ut),this.registerCategory(dr),this.registerCategory(Sr),this.registerCategory(Fr)}}class Wr{static toTyped(e){return{me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},variables:e.variables||new Map,locals:e.locals||new Map,globals:e.globals||new Map,...void 0!==e.events&&{events:e.events},meta:e.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(e,t){return{...t,me:e.me,it:e.it,you:e.you,result:e.result,...void 0!==e.event&&{event:e.event},...void 0!==e.variables&&{variables:e.variables},locals:e.locals,globals:e.globals,...void 0!==e.events&&{events:e.events},...void 0!==e.meta&&{meta:e.meta}}}}class Jr{constructor(e,t,r){this.impl=e,this.expressionEvaluator=t??new Ur,this.hookRegistry=r??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,r={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:r,event:e.event??void 0,executionContext:e}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(e,...t){const r=t[0],n=this.createHookContext(e,t,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(d(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void d(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const o=Wr.toTyped(e);let i,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(d(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers,n=t?.when||t?.where;if(n&&!await this.expressionEvaluator.evaluate(n,e))return void d(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:t||{},commandName:r.commandName},this.expressionEvaluator,e)}else i=t;else d(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return d("CommandAdapterV2: Calling execute with parsed input:",i),s=2===this.impl.execute.length?await this.impl.execute(i,o):await this.impl.execute(o,...i),d("CommandAdapterV2: Command result:",s),Object.assign(e,Wr.fromTyped(o,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,s),s}catch(e){if(Kr(e)||d(`CommandAdapterV2: Error executing '${this.name}':`,e),this.hookRegistry&&e instanceof Error)throw await this.hookRegistry.runOnError(n,e);throw e}}validate(e){return this.impl.validate?this.impl.validate(e):{isValid:!0,errors:[],suggestions:[]}}}class zr{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e);y(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=t.toLowerCase();y(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,e);const n=new Jr(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),Pe.add(r);const o=e.metadata?.aliases;if(o&&Array.isArray(o))for(const t of o){const r=t.toLowerCase();this.implementations.set(r,e),this.adapters.set(r,n),Pe.add(r)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const r=this.getAdapter(e);return r?r.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Zr=null;function Gr(){return Zr||(Zr=function(e){const t=e?.commands??new zr,r=e?.eventSources??new E,n=e?.context??new x,o=new Set,i={commands:t,eventSources:r,context:n,use(e){if(o.has(e.name))console.warn(`[LokaScriptRegistry] Plugin '${e.name}' is already installed`);else{if(e.commands)for(const r of e.commands)t.register(r);if(e.eventSources)for(const t of e.eventSources)r.register(t.name,t);if(e.contextProviders)for(const{name:t,provide:r,options:o}of e.contextProviders)n.register(t,r,o);e.setup?.(i),o.add(e.name)}},reset(){o.clear()}};return i}()),Zr}class Xr{constructor(e={}){this.contextCache=new WeakMap;const t=Gr();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,y(`[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),y(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return y("[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 y(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return y(`[RegistryIntegration] Found event source '${r}' supporting '${e}'`),t}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(e,t,r);if(!n)throw Error(`Failed to subscribe to event source '${e}'`);return y(`[RegistryIntegration] Subscribed to '${e}' event '${t.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,y("[RegistryIntegration] Destroyed")}}function Yr(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 Kr(e){return e instanceof Error&&(null!==r(e)||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message||"EXIT_EXECUTION"===e.message)}function Qr(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 en(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const tn=new WeakMap;class rn{constructor(e){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionEvaluator=e.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=g,this.hookRegistry=new t,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new v,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Xr("object"==typeof e.registryIntegration?e.registryIntegration:{}),y("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),install:async(e,t,r)=>await this.installBehaviorOnElement(e,t,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const r of e)for(const e of r.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&y(`RuntimeBase: Auto-cleaned ${t} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),y("RuntimeBase: Destroyed")}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){y(`RUNTIME BASE: execute() called with node type: '${e.type}'`),t.locals.has("_behaviors")||t.locals.set("_behaviors",this.behaviorAPI),t.locals.has("_runtimeExecute")||t.locals.set("_runtimeExecute",(e,r)=>this.execute(e,r||t));try{if(this.hasErrorDiagnostics(e)){const t=e.diagnostics?.[0];return y("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),void this.runtimeWarnings.push(t?.message||"Skipped error node")}switch(e.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(e,t);if(!i(r))throw Yr(r.error);return r.value}catch(e){throw e}return await this.processCommand(e,t);case"eventHandler":return await this.executeEventHandler(e,t);case"event":{const r={type:"eventHandler",event:e.event,events:[e.event],commands:e.body||[],target:e.filter,modifiers:e.modifiers||{}};return await this.executeEventHandler(r,t)}case"behavior":return await this.executeBehaviorDefinition(e,t);case"Program":return await this.executeProgram(e,t);case"initBlock":case"block":return await this.executeBlock(e,t);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=e,n=await this.executeCommandSequenceWithResult(r.commands||[],t);if(!i(n))throw Yr(n.error);return n.value}return await this.executeCommandSequence(e,t);case"objectLiteral":return await this.executeObjectLiteral(e,t);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(e,t);if(!i(r))throw Yr(r.error);return r.value}return await this.evaluateExpression(e,t)}}catch(e){throw e}}async processCommand(e,t){const{name:r,args:n,modifiers:o}=e,i=r.toLowerCase();if(d(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const e=await this.registry.getAdapter(i);if(!e)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await e.execute(t,{args:n||[],modifiers:o||{},commandName:i,runtime:this})}catch(e){throw Kr(e)||console.error(`Error executing command '${i}':`,e),e}}const s=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(s),Error(s)}toSignal(e){const t=r(e);if(t){if(t.isHalt||"HALT_EXECUTION"===t.message)return{type:"halt"};if(t.isExit||"EXIT_COMMAND"===t.message)return{type:"exit",returnValue:t.returnValue};if(t.isBreak)return{type:"break"};if(t.isContinue)return{type:"continue"};if(t.isReturn)return{type:"return",returnValue:t.returnValue}}if(e instanceof Error){if("HALT_EXECUTION"===e.message)return{type:"halt"};if("EXIT_COMMAND"===e.message)return{type:"exit"}}return null}async processCommandWithResult(e,t){const{name:r,args:i,modifiers:s}=e,a=r.toLowerCase();if(d(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(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 n(await c.execute(t,{args:i||[],modifiers:s||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return o(t);throw console.error(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let r;for(const o of e){if(this.hasErrorDiagnostics(o)){const e=o.diagnostics?.[0];y("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===o.type){const e=await this.processCommandWithResult(o,t);if(!i(e)){const r=e.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==r.returnValue&&Object.assign(t,{it:r.returnValue,result:r.returnValue}),n(r.returnValue)}}r=e.value}else{const e=await this.evaluateExpressionWithResult(o,t);if(!i(e))return e;r=e.value}}return n(r)}async evaluateExpression(e,t){const r=await this.expressionEvaluator.evaluate(e,t);return en(r)?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const r=await this.expressionEvaluator.evaluateWithResult(e,t);if(!i(r))return r;const s=r.value;if(en(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return n(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return o(t);throw e}}return n(s)}async executeCommandFromPattern(e,t,r){return this.processCommand({type:"command",name:e,args:[{type:"literal",value:t}]},r)}async executeProgram(e,t){if(!e.statements||!Array.isArray(e.statements))return;let r;const n=[],o=[],i=[];for(const t of e.statements)"eventHandler"===t.type?n.push(t):"initBlock"===t.type?o.push(t):i.push(t);for(const e of n)try{await this.execute(e,t)}catch(e){if(Kr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of o)try{r=await this.execute(e,t)}catch(e){if(Kr(e)&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(Kr(e)&&(e.isHalt||e.isExit))break;throw e}return r}async executeBlock(e,t){if(e.commands&&Array.isArray(e.commands))for(const r of e.commands)try{await this.execute(r,t)}catch(e){if(Kr(e)&&e.isHalt)break;throw e}}async executeCommandSequence(e,t){if(!e.commands||!Array.isArray(e.commands))return;let r;for(const n of e.commands)try{r=await this.execute(n,t)}catch(e){if(Kr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){if(void 0!==e.returnValue)return Object.assign(t,{it:e.returnValue,result:e.returnValue}),e.returnValue;break}if(e.isBreak)throw e}throw e}return r}async executeObjectLiteral(e,t){const r={};if(!e.properties)return r;for(const n of e.properties){let e;e="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,t)+"";const o=await this.execute(n.value,t);r[e]=o}return r}enhanceContext(e){return this.registryIntegration?this.registryIntegration.enhanceContext(e):e}async executeBehaviorDefinition(e,t){const{name:r,parameters:n,eventHandlers:o,initBlock:i}=e,s=e.imperativeInstaller;"function"==typeof s?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:s}),y(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:o,initBlock:i}),y(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(e,t,r){y("BEHAVIOR: installBehaviorOnElement called: "+e);const n=this.behaviorRegistry.get(e);if(!n)throw Error(`Behavior "${e}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return y(`BEHAVIOR: Installing imperative behavior '${e}'`),n.install(t,r),void y(`BEHAVIOR: Finished installing imperative behavior '${e}'`);y("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const o={me:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(o);if(n.parameters)for(const e of n.parameters)i.locals.set(e,e in r?r[e]:void 0);for(const[e,t]of Object.entries(r))n.parameters?.includes(e)||i.locals.set(e,t);if(n.initBlock){y("BEHAVIOR: Running init block for "+e);const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))]),y("BEHAVIOR: Init block completed for "+e)}catch(t){if(y(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&Kr(t)))throw t}}if(y(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers){const t=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}y("BEHAVIOR: Finished installing "+e)}async executeEventHandler(e,t){const{event:r,events:n,commands:o,target:i,args:s,selector:a,attributeName:c,watchTarget:l,modifiers:u}=e,f=n&&n.length>0?n:[r];y(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let d=[],p=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)p=window;else if("document"===e||"the document"===e||"body"===e)p=document;else if("me"===e||"myself"===e)d=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);y(`BEHAVIOR: Target resolution: found local '${i}', 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 y(`BEHAVIOR: Target resolution: querying for '${i}'`),d=this.queryElements(i,t)}else d=t.me?[t.me]:[];if(0===d.length&&!p)return void y(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(d,c,o,t);if("change"===r&&l)return void this.setupChangeObserver(l,o,t);const m=e.customEventSource;if(m&&this.registryIntegration){y(`BEHAVIOR: executeEventHandler - Using custom event source '${m}' for event '${r}'`);const e=async e=>{const n=new Map(t.locals),i={...t,locals:n,it:e,event:e},s=this.enhanceContext(i);y(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:o},s)}catch(e){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,e)}};try{const n=this.registryIntegration.subscribeToEventSource(m,{event:r,handler:e,target:i,selector:a},t);y(`BEHAVIOR: Subscribed to custom event source '${m}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${m}' subscription ${n.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${m}':`,e)}return}const h=rn.createEventHandler(this,o,t,a,s);let v,g=null;if(u){let e=h;if(u.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(u.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(u.debounce){const t=u.debounce;let r;v=n=>{r&&clearTimeout(r),r=setTimeout(()=>e(n),t)},g=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const t=u.throttle;let r=0;v=n=>{const o=Date.now();t>o-r||(r=o,e(n))}}else v=e}else v=h;const b=u?.once?{once:!0}:void 0;if(p){for(const e of f)p.addEventListener(e,v,b),d.length>0?this.cleanupRegistry.registerListener(d[0],p,e,v):this.cleanupRegistry.registerGlobal(()=>p.removeEventListener(e,v),"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)e.addEventListener(t,v,b),this.cleanupRegistry.registerListener(e,e,t,v);g&&this.cleanupRegistry.registerCustom(e,g,"debounce-timeout")}}static createEventHandler(e,t,r,n,o){return async i=>{const s=tn.get(i)??0;if(s>=100)return;if(tn.set(i,s+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{y(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const a=new Map(r.locals),c={...r,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=e.enhanceContext(c);if(o&&o.length>0){const e=i,t=e.detail;for(const r of o)l.locals.set(r,e[r]??t?.[r]??null)}for(const r of t)try{const t=Qr(await e.execute(r,l));void 0!==t&&Object.assign(l,{it:t,result:t})}catch(e){if(Kr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(l,{it:e.returnValue,result:e.returnValue});break}}throw console.error("COMMAND FAILED:",e),e}}}setupMutationObserver(e,t,r,n){y(`RUNTIME BASE: Setting up MutationObserver for attribute '${t}' on ${e.length} elements`);for(const o of e){const e=new MutationObserver(async e=>{for(const i of e)if("attributes"===i.type&&i.attributeName===t){p(`MUTATION DETECTED: attribute '${t}' changed on`,o);const e={...n,me:o,it:i,locals:new Map(n.locals)},s=i.oldValue,a=o.getAttribute(t);e.locals.set("oldValue",s),e.locals.set("newValue",a);const c=this.enhanceContext(e);for(const e of r)try{await this.execute(e,c)}catch(e){if(Kr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing mutation handler command:",e)}}});e.observe(o,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(o,e),y("RUNTIME BASE: MutationObserver attached to",o,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){y("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(e,r);let o=[];this.isElement(n)?o=[n]:Array.isArray(n)&&(o=n.filter(e=>this.isElement(e))),y(`RUNTIME BASE: Watching ${o.length} target elements for content changes`);for(const e of o){const n=new MutationObserver(async n=>{for(const o of n)if("childList"===o.type||"characterData"===o.type){p("CONTENT CHANGE DETECTED on",e,"mutation type:",o.type);const n={...r,me:r.me,it:o,locals:new Map(r.locals)};n.locals.set("target",e);const i=o.oldValue,s=e.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",s);const a=this.enhanceContext(n);for(const e of t)try{await this.execute(e,a)}catch(e){if(Kr(e)){if(e.isHalt||e.isExit||e.isReturn)break}else console.error("Error executing change handler command:",e)}}});n.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),y("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let o=e;o.startsWith("<")&&o.endsWith("/>")&&(o=o.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(o))}catch{return y(`queryElements: invalid CSS selector '${o}'`),[]}}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||!(!e||"object"!=typeof e)&&(!!e.style&&!!e.classList)}}const nn={core:["references","logical","special"],common:["properties","conversion"],optional:["positional"]};class on extends H{constructor(e={}){super(),this.loadedCategories=new Set,this.loadPromises=new Map,this.options={preload:"core",...e},"none"!==this.options.preload&&this.preloadExpressions()}async preloadExpressions(){if(this.options.categories)await Promise.all(this.options.categories.map(e=>this.loadCategory(e)));else switch(this.options.preload){case"all":await this.preloadTier("core"),await this.preloadTier("common"),await this.preloadTier("optional");break;case"common":await this.preloadTier("core"),await this.preloadTier("common");break;case"core":await this.preloadTier("core")}}async preloadTier(e){const t=nn[e];await Promise.all(t.map(e=>this.loadCategory(e)))}async loadCategory(e){if(this.loadedCategories.has(e))return;if(this.loadPromises.has(e))return this.loadPromises.get(e);const t=this.l(e);this.loadPromises.set(e,t);try{await t,this.loadedCategories.add(e),h("✅ Loaded expression category: "+e)}finally{this.loadPromises.delete(e)}}async l(e){try{let t;switch(h("📦 Loading expression category: "+e),e){case"references":t=await Promise.resolve().then(function(){return Me});break;case"logical":t=await Promise.resolve().then(function(){return kt});break;case"special":t=await Promise.resolve().then(function(){return Hr});break;case"properties":t=await Promise.resolve().then(function(){return Tr});break;case"conversion":t=await Promise.resolve().then(function(){return Wt});break;case"positional":t=await Promise.resolve().then(function(){return pr});break;default:return void console.warn("Unknown expression category: "+e)}const r=t[e+"Expressions"]||t.default;if(!r)return void console.warn("No expressions found in category: "+e);this.registerCategory(r),h(` ✓ Registered ${Object.keys(r).length} expressions from ${e}`)}catch(t){throw console.error("Failed to load expression category: "+e,t),t}}getCategoryForNodeType(e){return{identifier:"references",selector:"references",dollarExpression:"references",binaryExpression:"logical",unaryExpression:"logical",comparison:"logical",literal:"special",string:"special",numberLiteral:"special",stringLiteral:"special",booleanLiteral:"special",arrayLiteral:"special",objectLiteral:"special",templateLiteral:"special",memberExpression:"properties",possessiveExpression:"properties",propertyAccess:"properties",propertyOfExpression:"properties",asExpression:"conversion",positional:"positional",callExpression:"references"}[e]||null}async evaluate(e,t){if(!e)return h("LAZY EVALUATOR: Received null/undefined node, returning null"),null;if(!e.type)throw console.error("LAZY EVALUATOR: Node missing type property:",e),Error("Node missing type property: "+JSON.stringify(e));const r=this.getCategoryForNodeType(e.type);return r&&!this.loadedCategories.has(r)&&(h(`🔄 Auto-loading category for node type: ${e.type} → ${r}`),await this.loadCategory(r)),super.evaluate(e,t)}async warmupExpressions(e){h("🔥 Warming up expression categories: "+e.join(", ")),await Promise.all(e.map(e=>this.loadCategory(e)))}getLoadedCategories(){return Array.from(this.loadedCategories)}}function sn(e,t,r,n,o,i){function s(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?n.static?e:e.prototype:null,f=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),d=!1,p=r.length-1;p>=0;p--){var m={};for(var h in n)m[h]="access"===h?{}:n[h];for(var h in n.access)m.access[h]=n.access[h];m.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var y=(0,r[p])("accessor"===c?{get:f.get,set:f.set}:f[l],m);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=s(y.get))&&(f.get=a),(a=s(y.set))&&(f.set=a),(a=s(y.init))&&o.unshift(a)}else(a=s(y))&&("field"===c?o.unshift(a):f[l]=a)}u&&Object.defineProperty(u,n.name,f),d=!0}function an(e,t,r){for(var n=arguments.length>2,o=0;t.length>o;o++)r=n?t[o].call(e,r):t[o].call(e);return n?r:void 0}function cn(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}"function"==typeof SuppressedError&&SuppressedError;const ln=Symbol("command:name"),un=Symbol("command:category"),fn=Symbol("command:metadata");function dn(e){return function(t,r){const n=t;n[ln]=e.name,n[un]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function pn(e){return function(t,r){const n=t,o=n[un];if(!o)throw Error("@meta decorator requires @command decorator to be applied first on "+t.name);const i={description:e.description,syntax:e.syntax,examples:e.examples,category:o,sideEffects:e.sideEffects,deprecated:e.deprecated,deprecationMessage:e.deprecationMessage,aliases:e.aliases,relatedCommands:e.relatedCommands,isBlocking:e.isBlocking??!1,hasBody:e.hasBody??!1,version:"1.0.0",compatibility:e.compatibility};n[fn]=i,Object.defineProperty(t,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(t.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function mn(e){return()=>new e}function hn(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function yn(e,t){if(hn(e))return e;if(!e){const e=t.me;if(!e)throw Error("No target element - provide explicit target or ensure context.me is set");return gn(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return gn(t.me)}if("it"===r){if(!hn(t.it))throw Error('Context reference "it" is not an HTMLElement');return t.it}if("you"===r){if(!t.you)throw Error('Context reference "you" is not available');return gn(t.you)}const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const o=n.querySelector(r);if(!o)throw Error("Element not found with selector: "+r);if(!hn(o))throw Error("Element found but is not an HTMLElement: "+r);return o}throw Error("Invalid target type: "+typeof e)}function vn(e,t){if(Array.isArray(e))return e.filter(hn);if(e instanceof NodeList)return Array.from(e).filter(hn);if(hn(e))return[e];if(!e){const e=t.me;return e&&hn(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&hn(t.me)?[t.me]:[];if("it"===r)return hn(t.it)?[t.it]:[];if("you"===r)return t.you&&hn(t.you)?[t.you]:[];const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let e=r;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.querySelectorAll(e);return Array.from(t).filter(hn)}}return[]}function gn(e){if(hn(e))return e;throw Error("Value is not an HTMLElement")}function bn(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!hn(t.me))throw Error("context.me is not an HTMLElement");return t.me;case"its":case"it":if(!t.it)throw Error('No "it" value in context');if(!hn(t.it))throw Error("context.it is not an HTMLElement");return t.it;case"your":case"you":if(!t.you)throw Error('No "you" element in context');if(!hn(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const wn=["on","from","to","in","with","at"];async function En(e,t,r,n,o={},i){let s=e;if(o.filterPrepositions&&e&&(s=e.filter(e=>{const t=e;return"identifier"!==t?.type||"string"!=typeof t.name||!wn.includes(t.name.toLowerCase())})),(!s||0===s.length)&&o.fallbackModifierKey&&i){const e=i[o.fallbackModifierKey];e&&(s=[e])}if(!s||0===s.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!hn(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const e of s){const o=await t.evaluate(e,r);if(""!==o&&("string"!=typeof o||""!==o.trim()))if(hn(o))a.push(o);else if(o instanceof NodeList){const e=Array.from(o).filter(hn);a.push(...e)}else if(Array.isArray(o)){const e=o.filter(hn);a.push(...e)}else{if("string"!=typeof o)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof o}`);try{let e=o;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const n=t.querySelectorAll(e),i=Array.from(n).filter(hn);a.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${o}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!hn(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}class xn{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await En(e.args,t,r,n)}}(e,t,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.targets)||!t.targets.every(e=>hn(e))||"show"!==t.mode&&"hide"!==t.mode||"show"===t.mode&&"string"!=typeof t.defaultDisplay)}showElement(e,t="block"){const r=e.dataset.originalDisplay;void 0!==r?(e.style.display=r||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}let An=(()=>{let e,t,r=[pn({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),dn({name:"hide",category:"dom"})],n=[],o=xn;return t=class extends o{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=>hn(e))}},cn(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const Sn=mn(An);let Tn=(()=>{let e,t,r=[pn({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),dn({name:"show",category:"dom"})],n=[],o=xn;return t=class extends o{constructor(){super(...arguments),this.mode="show"}async execute(e,t){const r=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,r)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>hn(e))&&"string"==typeof t.defaultDisplay}},cn(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const Nn=mn(Tn);function On(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function Cn(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),r=e.indexOf("=");if(-1===r)return{name:e.trim()};const n=e.slice(0,r).trim();let o=e.slice(r+1).trim();return(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),{name:n,value:o}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function kn(e,t){for(const r of e)t(r);return e}function jn(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function Ln(e,t,r){const n=e.hasAttribute(t);void 0!==r?n&&e.getAttribute(t)===r?e.removeAttribute(t):e.setAttribute(t,r):n?e.removeAttribute(t):e.setAttribute(t,"")}function In(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&&$n(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&&$n(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&$n(r)?[r]:[]}function Rn(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function $n(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!Rn(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function Mn(e,t){return e.map(e=>{if(Rn(e)){const r=function(e){const t=e.trim(),r=t.match(/^\{(.+)\}$/);return r?r[1].trim():t}(e),n=t.locals.get(r)??t.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return e}).filter(e=>e.length>0)}function Dn(e){return"string"==typeof e&&e.trim().startsWith("*")}function Vn(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const r=t.substring(1).trim();return r?{property:r}:null}(e);if(!t)return null;const r=t.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function Pn(e,t,r){e.style.setProperty(t,r)}const Bn=["dialog","details","summary","select"];function _n(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 qn(e,t,r){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const r=_n(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const r=_n(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:_n(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=_n(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(n=e,"attributeAccess"===n.type?"@"+n.attributeName:_n(n)),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1};var n}class Fn{async resolveTargets(e,t,r,n){return En(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return qn(e,t,r)}parseClassNames(e){return In(e)}isAttribute(e){return On(e.trim())}isCSSProperty(e){return Dn(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>hn(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 Hn=(()=>{let e,t,r=[pn({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"]}),dn({name:"add",category:"dom"})],n=[],o=Fn;return t=class extends o{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if("string"==typeof n){const o=n.trim();if(this.isAttribute(o)){const{name:n,value:i}=function(e){const t=Cn(e);return{name:t.name,value:t.value??""}}(o);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}if(this.isCSSProperty(o)){const n=o.substring(1).trim();if(2>e.args.length)throw Error("add *property requires a value argument");const i=await t.evaluate(e.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(e.args.slice(2),t,r,e.modifiers)}}}const o=this.parseClassNames(n);if(0===o.length)throw Error("add command: no valid class names found");return{type:"classes",classes:o,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const r=Mn(e.classes,t);r.length>0&&jn(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,kn(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":!function(e,t){jn(e,Object.entries(t),(e,[t,r])=>{e.style.setProperty(t,r)})}(e.targets,e.styles)}var r,n}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const r=t.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(e=>"string"==typeof e))return!1}return!0}},cn(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const Un=mn(Hn);function Wn(e){return!!e.parentNode&&(e.remove(),!0)}let Jn=(()=>{let e,t,r=[pn({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"]}),dn({name:"remove",category:"dom"})],n=[],o=Fn;return t=class extends o{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if(hn(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&hn(n[0]))return{type:"element",targets:n.filter(e=>hn(e))};if("string"==typeof n){const o=n.trim();if(this.isAttribute(o))return{type:"attribute",name:Cn(o).name,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)};if(this.isCSSProperty(o))return{type:"styles",properties:[o.substring(1).trim()],targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}const o=this.parseClassNames(n);if(0===o.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:o,targets:await this.resolveTargets(e.args.slice(1),t,r,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const r=Mn(e.classes,t);r.length>0&&jn(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,kn(e.targets,e=>{e.removeAttribute(r)});break;case"styles":!function(e,t){jn(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)Wn(t)}var r}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type&&!this.validateStringArray(e.properties,1))return!1;return!0}},cn(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const zn=mn(Jn);function Zn(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function Gn(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=Zn(e);return r?r.milliseconds:t}return t}function Xn(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=Zn(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function Yn(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 Kn(e,t){let r=0;for(let n=0;e.length>n;n++)r=Math.max(r,(e[n]||0)+(t[n]||0));return r}function Qn(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function eo(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&Ln(e,r)}}function to(e,t,r,n){const o=eo(e,t,r),i=setTimeout(o,n);return()=>{clearTimeout(i)}}function ro(e,t,r,n){const o=eo(e,t,r),i=()=>{o(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function no(e,t,r){if(t.startsWith("@")){const n=t.substring(1);return void(!1===r?e.removeAttribute(n):e.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(t){case"textContent":return void(e.textContent=n);case"innerHTML":return void(e.innerHTML=n);case"innerText":return void(e.innerText=n);case"id":return void(e.id=n);case"className":return void(e.className=n);case"value":return void("value"in e&&(e.value=n));case"checked":return void("checked"in e&&(e.checked=!!r))}if(t.includes(".")){const n=t.split(".");let o=e;for(let e=0;n.length-1>e;e++)if(o=o[n[e]],null==o)return;return void(o[n[n.length-1]]=r)}if(t.includes("-")||t in e.style)e.style.setProperty(t,n);else try{e[t]=r}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function oo(e){return null==e||""===e}const io=/^the\s+(.+?)\s+of\s+(.+)$/i,so=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 ao(e){return"string"==typeof e&&io.test(e)}function co(e,t){const r=e.match(io);if(!r)return null;try{return{element:yn(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function lo(e,t,r){if(function(e){return!(!e||"object"!=typeof e)&&"propertyOfExpression"===e.type&&"object"==typeof e.property&&null!==e.property}(e))return async function(e,t,r){const n=e.property?.name;if(!n)return null;let o=await t.evaluate(e.target,r);return Array.isArray(o)&&(o=o[0]),hn(o)?{element:o,property:n}:null}(e,t,r);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&("string"==typeof e.property||"object"==typeof e.property&&null!==e.property&&"string"==typeof e.property.name)}(e))return async function(e,t,r){const n="string"==typeof e.property?e.property:e.property?.name;if(!n)return null;let o=await t.evaluate(e.object,r);return Array.isArray(o)&&(o=o[0]),hn(o)?{element:o,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const e=n.object,o=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!hn(i))return null;const s=o?.name||o?.value;return s&&(s.startsWith("@")||s.startsWith("*"))?{element:i,property:s}:null}return null}function uo(e,t){const{element:r,property:n}=e;n.startsWith("*")?Pn(r,n.substring(1),t+""):no(r,n,t)}async function fo(e,t,r){let n,o;if(e?.for){const o=await t.evaluate(e.for,r);n="number"==typeof o?o:"string"==typeof o?Gn(o):void 0}if(e?.until){const n=await t.evaluate(e.until,r);"string"==typeof n&&(o=n)}return{duration:n,untilEvent:o}}function po(e,t){const r=t?.name,n=function(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return Bn.includes(t)}(t)}(t);if(hn(e)||Array.isArray(e)&&e.every(e=>hn(e)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return Bn.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const mo=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"toggle",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("toggle command requires an argument");const n=e.args[0],o=n?.name;if("between"===o&&e.args.length>=4){const{duration:n,untilEvent:o}=await fo(e.modifiers,t,r),i=await t.evaluate(e.args[1],r),s=await t.evaluate(e.args[3],r),a=[];for(let t=4;e.args.length>t;t++){const r=e.args[t]?.name;"on"!==r&&"from"!==r&&a.push(e.args[t])}const c={filterPrepositions:!0,fallbackModifierKey:"on"},l=await En(a,t,r,"toggle",c,e.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(s+"").replace(/^\./,""),targets:l,duration:n,untilEvent:o}}const i=await lo(n,t,r);if(i)return{type:"property",target:i};if("selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("*")){let o=n.value,i=1;if("*"===o&&e.args.length>1&&"identifier"===e.args[1].type&&(o="*"+e.args[1].name,i=2),"*"===o&&e.modifiers?.on){const n=e.modifiers.on?.name;if(n&&["display","visibility","opacity"].includes(n)){o="*"+n;const{duration:i,untilEvent:s}=await fo(e.modifiers,t,r),a=Vn(o);if(a){const e=r.me;return{type:"css-property",property:a,targets:e?[e]:[],duration:i,untilEvent:s}}}}const s=Vn(o);if(s){const{duration:n,untilEvent:o}=await fo(e.modifiers,t,r),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:s,targets:await En(e.args.slice(i),t,r,"toggle",a,e.modifiers),duration:n,untilEvent:o}}}const{duration:s,untilEvent:a}=await fo(e.modifiers,t,r),{value:c}=await qn(n,t,r);if(ao(c)){const e=co(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=po(c,n),f={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:o}=Cn(u);return{type:"attribute",name:n,value:o,targets:await En(e.args.slice(1),t,r,"toggle",f,e.modifiers),duration:s,untilEvent:a}}case"css-property":{const n=Vn(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await En(e.args.slice(1),t,r,"toggle",f,e.modifiers)}}case"element":{let o;if(hn(c))o=[c];else if(Array.isArray(c)&&c.every(e=>hn(e)))o=c;else if(u){const e=document.querySelectorAll(u);o=Array.from(e).filter(e=>hn(e))}else o=await En([n],t,r,"toggle",f,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(o);if("dialog"===i){const n=await async function(e,t,r,n){if(t?.as){const e=await r.evaluate(t.as,n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}if(e.length>=2){const t=await r.evaluate(e[1],n);if("string"==typeof t){const o=t.toLowerCase();if("modal"===o||"as modal"===o)return"modal";if("as"===o&&e.length>=3){const t=await r.evaluate(e[2],n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}}}return"non-modal"}(e.args,e.modifiers,t,r);return{type:"dialog",mode:n,targets:o}}return"details"===i?{type:"details",targets:Qn(o)}:"select"===i?{type:"select",targets:o}:{type:"classes",classes:In(u),targets:o,duration:s,untilEvent:a}}default:{const n=In(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await En(e.args.slice(1),t,r,"toggle",f,e.modifiers),duration:s,untilEvent:a}}}}async execute(e,t){switch(e.type){case"classes":{const r=Mn(e.classes,t);if(0===r.length)return[...e.targets];if(jn(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&to(t,"class",r[0],e.duration),e.untilEvent&&ro(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,kn(e.targets,e=>{Ln(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&to(t,"attribute",e.name,e.duration),e.untilEvent&&ro(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return kn(e.targets,t=>function(e,t){const r=window.getComputedStyle(e);switch(t){case"display":"none"===r.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=r.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=function(e){const{element:t,property:r}=e;return r.startsWith("*")?function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,r.substring(1)):$(t,r)}(e),r=e.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof t||so.has(n)||so.has(n.toLowerCase())){const r=!t;return uo(e,r),r}if("number"==typeof t){const r=0===t?1:0;return uo(e,r),r}if("string"==typeof t){const n="__ht_"+r,o=e.element[n];return""===t&&void 0!==o?(uo(e,o),o):(e.element[n]=t,uo(e,""),"")}uo(e,!t)}(e.target),[e.target.element];case"dialog":return kn(e.targets,t=>{return n=e.mode,void((r=t).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return kn(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return kn(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const r=t.classList.contains(e.classA),n=t.classList.contains(e.classB);r?(t.classList.remove(e.classA),t.classList.add(e.classB)):n?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&to(t,"class",e.classA,e.duration),e.untilEvent&&ro(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},cn(t,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());const ho=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"put",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("put requires arguments");const n=e=>e?.type||"unknown",o=["into","before","after","at","at start of","at end of"];let i=-1,s=null;for(let t=0;e.args.length>t;t++){const r=e.args[t],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&o.includes(c)){i=t,s=c;break}}let a=null,c=null;if(-1===i)if(e.modifiers.into||e.modifiers.before||e.modifiers.after){const t=e.modifiers.into?"into":e.modifiers.before?"before":"after";a=e.args[0],s=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],s=e.args[1]?.value||e.args[1]?.name||"into"}else a=e.args[0],s=e.args[1]?.value||e.args[1]?.name||null,c=e.args[2];else a=e.args.slice(0,i)[0]||null,c=e.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!s)throw Error("put requires position keyword");const l=await t.evaluate(a,r),u=this.mapPosition(s);let f,d,p=null;if(c){const e=n(c),o=await lo(c,t,r);if(o)return{value:l,targets:[o.element],position:"replace",memberPath:o.property};if("memberExpression"===e){const e=c.object,n=c.property;if("selector"===e?.type?p=e.value:"identifier"===e?.type&&(p=e.name),p&&n?.name)f=n.name;else{const e=await t.evaluate(c,r);"string"==typeof e&&(p=e)}}else if("identifier"===e&&"me"===c.name)p=null;else if("selector"===e||"cssSelector"===e)p=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&ao(e)){const t=co(e,r);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?p=e:d=e+""}else if("identifier"===e){const e=c.name;if(this.looksLikeCss(e))p=e;else{const n=await t.evaluate(c,r),o=this.resolveEvaluatedAsElements(n);if(o)return{value:l,targets:o,position:u,memberPath:f};d=e}}else{const e=await t.evaluate(c,r),n=this.resolveEvaluatedAsElements(e);if(n)return{value:l,targets:n,position:u,memberPath:f};"string"==typeof e&&(this.looksLikeCss(e)?p=e:d=e)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(p,r),position:u,memberPath:f}}async execute(e,t){const{value:r,targets:n,position:o,memberPath:i,variableName:s}=e;if(s)return t.locals&&t.locals.set(s,r),t[s]=r,void Object.assign(t,{it:r});if(i)for(const e of n)this.setProperty(e,i,r);else for(const e of n){const t=this.parseValue(r);this.insertContent(e,t,o)}return n}mapPosition(e){switch(e){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!hn(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>hn(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return hn(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(hn(t)){const n=t;switch(r){case"beforebegin":e.parentElement?.insertBefore(n,e);break;case"afterbegin":e.insertBefore(n,e.firstChild);break;case"beforeend":e.appendChild(n);break;case"afterend":e.parentElement?.insertBefore(n,e.nextSibling)}}else t.includes("<")&&t.includes(">")?e.insertAdjacentHTML(r,t):e.insertAdjacentText(r,t);else hn(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}resolveEvaluatedAsElements(e){if(hn(e))return[e];if(Array.isArray(e)){const t=e.filter(hn);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(hn);return t.length>0?t:null}return null}looksLikeCss(e){return!!e&&(!!/^[#.\[]/.test(e)||(!(!/[>+~\s]/.test(e)||1>=e.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(e.toLowerCase())))}setProperty(e,t,r){const n=t.split(".");let o=e;for(let e=0;n.length-1>e;e++){if(!o[n[e]])throw Error(`Property path "${t}" does not exist`);o=o[n[e]]}o[n[n.length-1]]=r}},cn(t,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());function yo(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 vo(e,t,r){return"global"===r&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==r&&t.locals&&t.locals.has(e)?t.locals.get(e):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===r&&t.locals&&t.locals.has(e)?t.locals.get(e):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function go(e,t,r,n){if("global"===n)return r.globals.set(e,t),void("undefined"!=typeof window&&(window[e]=t));if(r.locals&&r.locals.has(e))r.locals.set(e,t);else{if(r.globals&&r.globals.has(e))return r.globals.set(e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(!r.variables||!r.variables.has(e))return"undefined"!=typeof window&&e in window?(window[e]=t,void r.globals.set(e,t)):void r.locals.set(e,t);r.variables.set(e,t)}}function bo(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:vo(e,t)}const wo=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"make",category:"dom"})],n=[];return t=class{async parseInput(e,t,r){const n=e.args.length>0?await t.evaluate(e.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const o=void 0!==e.modifiers.an?"an":"a",i=await async function(e,t,r){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const n=[];for(const o of e.args)n.push(await t.evaluate(o,r));return n}const n=await t.evaluate(e,r);return Array.isArray(n)?n:[n]}(e.modifiers.from,t,r),s=await async function(e,t,r){if(!e)return;if("symbol"===e.type&&"string"==typeof e.name)return e.name;const n=await t.evaluate(e,r);return"string"==typeof n?n:n+""}(e.modifiers.called,t,r);return{article:o,expression:n,constructorArgs:i,variableName:s}}async execute(e,t){const{expression:r,constructorArgs:n=[],variableName:o}=e,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(e){const t=e.slice(1,-2);let r="div",n=t;const o=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);o&&(r=o[1],n=t.slice(o[0].length));const i=document.createElement(r),s=n.split(/(?=[.#])/);for(const e of s)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(r):function(e,t,r){if(hn(e))return e;const n=e+"";let o;if("undefined"!=typeof window&&(o=window[n]),o||"undefined"==typeof global||(o=global[n]),!o&&r.variables?.has(n)&&(o=r.variables.get(n)),!o||"function"!=typeof o)throw Error(`Constructor '${n}' not found or is not a function`);return 0===t.length?new o:new o(...t)}(r,n,t);return Object.assign(t,{it:i}),o&&go(o,i,t),i}},cn(t,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());function Eo(e,t,r){return e?new Promise(r=>{const n=Ao(()=>{e.removeEventListener(t,o)},r),o=e=>{n({event:e,timedOut:!1,cancelled:!1})};e.addEventListener(t,o)}):Promise.reject(Error("waitForEvent: no target provided"))}function xo(e){return new Promise(t=>setTimeout(t,e))}function Ao(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}const So=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"wait",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("wait command requires an argument");if(e.modifiers.or)return this.parseRaceCondition(e,t,r);if(e.modifiers.for)return this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r);const n=e.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,e.args[1],t,r):this.parseTimeWait(e.args[0],t,r)}async execute(e,t){const r=Date.now();if("time"===e.type)return await xo(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,o=(await Eo(n,e.eventName)).event;if(Object.assign(t,{it:o}),e.destructure)for(const r of e.destructure)r in o&&t.locals.set(r,o[r]);return{type:"event",result:o,duration:Date.now()-r}}const{result:n,winningCondition:o}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:n}),n instanceof Event&&"event"===o?.type&&o.destructure)for(const e of o.destructure)e in n&&t.locals.set(e,n[e]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(e,t,r){return{type:"time",milliseconds:Xn(await t.evaluate(e,r))}}async parseEventWait(e,t,r,n){const o=await r.evaluate(e,n);if("string"!=typeof o)throw Error("wait for: event name must be a string");const i=o.match(/^(\w+)\(([^)]+)\)$/),s=i?i[1]:o,a=i?i[2].split(",").map(e=>e.trim()):void 0;let c;if(t){const e=await r.evaluate(t,n);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");c=e}else c=n.me??void 0;return{type:"event",eventName:s,target:c,destructure:a}}async parseEventArrayWait(e,t,r,n){const o=[];for(const t of e){const e=t;if("objectLiteral"===e.type&&e.properties){let t="",r=[];for(const n of e.properties){const e=n.key?.name||n.key?.value;"name"===e&&n.value?t=n.value.value||"":"args"===e&&n.value?.elements&&(r=n.value.elements.map(e=>e.value||e.name||""))}t&&o.push({name:t,params:r})}}let i;if(t){const e=await r.evaluate(t,n);e&&"object"==typeof e&&"addEventListener"in e&&(i=e)}return i||(i=n.me??void 0),1===o.length?{type:"event",eventName:o[0].name,target:i,destructure:o[0].params.length>0?o[0].params:void 0}:{type:"race",conditions:o.map(e=>({type:"event",eventName:e.name,target:i,destructure:e.params.length>0?e.params:void 0}))}}async parseRaceCondition(e,t,r){const n=[];e.modifiers.for?n.push(await this.parseEventWait(e.modifiers.for,e.modifiers.from,t,r)):e.args[0]&&n.push(await this.parseTimeWait(e.args[0],t,r));const o=await t.evaluate(e.modifiers.or,r),i=Array.isArray(o)?o:[o];for(const e of i)try{n.push({type:"time",milliseconds:Xn(e)})}catch{if("string"==typeof e){const t=e.match(/^(\w+)\(([^)]+)\)$/);n.push(t?{type:"event",eventName:t[1],target:r.me??void 0,destructure:t[2].split(",").map(e=>e.trim())}:{type:"event",eventName:e,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(e,t){const r=e.map(e=>"time"===e.type?xo(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Eo(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},cn(t,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),To=new Map;const No=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"fetch",category:"async"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("fetch requires a URL");return{url:await this.parseURL(e.args[0],t,r),responseType:this.parseResponseType(e.modifiers.as),options:await this.parseRequestOptions(e.modifiers.with,t,r)}}async execute(e,t){const r=Date.now(),{url:n,responseType:o,options:i}=e,s=new AbortController;let a;t.me&&(a=()=>s.abort(),t.me.addEventListener("fetch:abort",a,{once:!0}));const c={...i,signal:s.signal},l=To.get(o);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>s.abort(),i.timeout));try{let e=await fetch(n,c);if(t.me){const r={response:e};this.dispatchEvent(t.me,"fetch:afterResponse",r),e=r.response}const i=await this.handleResponse(e,o,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:i});const s={status:e.status,statusText:e.statusText,headers:e.headers,data:i,url:e.url,duration:Date.now()-r};return Object.assign(t,{it:i}),s}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+n);throw Error(`Fetch failed for ${n}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&a&&t.me.removeEventListener("fetch:abort",a)}}async parseURL(e,t,r){const n=await t.evaluate(e,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(To.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,r){if(!e)return{};const n=await t.evaluate(e,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const o={};return"method"in n&&(o.method=(n.method+"").toUpperCase()),"headers"in n&&(o.headers=this.parseHeaders(n.headers)),"body"in n&&(o.body=this.parseBody(n.body)),"credentials"in n&&(o.credentials=n.credentials),"mode"in n&&(o.mode=n.mode),"cache"in n&&(o.cache=n.cache),o}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[r,n]of Object.entries(e))t.set(r,n+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,r){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const n=To.get(t);return n?n.handler(e,r):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),r=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),1===r.childNodes.length&&hn(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},cn(t,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),Oo=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"set",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("set command requires a target");const n=e.args[0],o=n?.name||n?.value,i=await lo(n,t,r);if(i){const n=await this.extractValue(e,t,r);if(i.property.startsWith("*")){const e=i.property.substring(1);return{type:"style",element:i.element,property:e,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const o=await this.tryParseMemberExpression(n,e,t,r);if(o)return o}let s;if(s="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof o?await t.evaluate(n,r):o,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(hn(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(s))return{type:"object-literal",properties:s,targets:await this.resolveTargets(e.modifiers.on,t,r)};if(ao(s)){const n=co(s,r);if(n){const o=await this.extractValue(e,t,r);return{type:"property",element:n.element,property:n.property,value:o}}return this.parseTheXofY(s,e,t,r)}if("string"==typeof s&&Dn(s)){const n=s.substring(1).trim(),o=await this.extractValue(e,t,r);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,r),property:n,value:o+""}}if("string"==typeof s&&On(s)){const n=s.substring(1).trim(),o=await this.extractValue(e,t,r);return{type:"attribute",element:await this.resolveElement(e.modifiers.on,t,r),name:n,value:o}}if("string"==typeof s){const n=s.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const o=bn(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:o,property:n[2],value:i}}}if(hn(s))return{type:"property",element:s,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(s)&&s.length>0&&hn(s[0])){const n=await this.extractValue(e,t,r);return{type:"property",element:s[0],property:"textContent",value:n}}if("string"!=typeof s)throw Error("set command target must be a string or object literal");return{type:"variable",name:s,value:await this.extractValue(e,t,r)}}async execute(e,t){switch(e.type){case"variable":return t.locals.set(e.name,e.value),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":return e.element.setAttribute(e.name,e.value+""),Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return no(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return Pn(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[r,n]of Object.entries(e.properties))no(t,r,n);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,r,n){const o=e.object,i=e.property;if(o?.name&&i?.name){const e=o.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const o=bn(e,n),s=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.name,value:s}}}const s=e.object,a=e.computed;if(s){const o=await r.evaluate(s,n);if(null!=o&&"object"==typeof o){const s=a?await r.evaluate(e.property,n)+"":i?.name||"";if(s)return{type:"member-assignment",container:o,property:s,value:await this.extractValue(t,r,n)}}}return null}async extractValue(e,t,r){if(e.modifiers.to)return t.evaluate(e.modifiers.to,r);const n=e.args.findIndex(e=>"identifier"===e.type&&"to"===e.name);if(n>=0&&e.args.length>n+1)return t.evaluate(e.args[n+1],r);if(e.args.length>=2)return t.evaluate(e.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,r){return yn(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return vn(e?await t.evaluate(e,r):void 0,r)}async parseTheXofY(e,t,r,n){const o=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!o)throw Error('Invalid "the X of Y" syntax');const[,i,s]=o,a=yn(s,n),c=await this.extractValue(t,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&hn(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&hn(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&hn(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}}},cn(t,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());let Co=(()=>{let e,t,r=[pn({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"]}),dn({name:"increment",category:"data"})],n=[];return t=class{async parseInput(e,t,r){const n="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",o=await async function(e,t,r,n){if(!e.args||0===e.args.length)throw Error(n+" command requires a target");const o=e.args[0];let i,s;const a=(c=o)&&"object"==typeof c&&c.type||"unknown";var c;if("identifier"===a)i=o.name,o.scope&&(s=o.scope);else if("literal"===a)i=o.value;else{const e=await t.evaluate(o,r);i=Array.isArray(e)&&e.length>0?e[0]:e}let l=1,u=s;for(let n=1;e.args.length>n;n++){const o=e.args[n];if(o&&"literal"===o.type){const e=o.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(o&&"literal"!==o.type){const e=await t.evaluate(o,r);"number"==typeof e&&(l=e)}}return{target:i,amount:l,...u&&{scope:u}}}(e,t,r,n);return{...o,operation:n}}async execute(e,t){const{target:r,property:n,scope:o,amount:i=1,operation:s="increment"}=e,a=function(e,t,r,n){if("number"==typeof e)return e;if(hn(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?yo(r.getAttribute(t)):yo(r[t]):yo(r.value||r.textContent)}return"string"==typeof e?"global"===r?yo(vo(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],o=bo(r[0],t);return o?yo(o[n]):0}(e,n):yo("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:vo(e,n)):yo(e)}(r,n,o,t);let c;if(isNaN(a))c=NaN;else{const e=isFinite(i)?i:1;c="increment"===s?a+e:a-e}return function(e,t,r,n,o){if(hn(e)){const r=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?r.setAttribute(t,n+""):r[t]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof e){if("global"===r)return void go(e,n,o,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),o=n[1],i=bo(n[0],r);i&&(i[o]=t)}(e,n,o);if("me"===e&&o.me)return void(o.me.value=n);if("it"===e)return void Object.assign(o,{it:n});if("you"===e&&o.you)return void(o.you.value=n);go(e,n,o)}}(r,n,o,c,t),Object.assign(t,{it:c}),c}},cn(t,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})();const ko=mn(Co),jo=mn(Co),Lo=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"log",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{values:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{values:[]}}async execute(e,t){const r="undefined"!=typeof window?window.console:console;0===e.values.length?r.log():r.log(...e.values)}validate(e){return"object"==typeof e&&null!==e&&Array.isArray(e.values)}},cn(t,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());function Io(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}let Ro=(()=>{let e,t,r=[pn({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"]}),dn({name:"trigger",category:"event"})],n=[];return t=class{async parseInput(e,t,r){const n="send"===e.commandName?.toLowerCase()?"send":"trigger",o=n;if(!e.args?.length)throw Error(o+" command requires an event name");const i=e=>e?.type||"unknown",s=e.args[0];let a,c,l;if("functionCall"===i(s)||"callExpression"===i(s)){a=s.name||s.callee?.name;const e=s.args||s.arguments;e?.length&&(c=await this.parseEventDetail(e,t,r))}else if("identifier"===i(s)||"keyword"===i(s))a=s.name;else{const e=await t.evaluate(s,r);a="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,r,o);else{const n=e.args.findIndex((e,t)=>{if(0===t)return!1;const r=e.name||e.value;return"on"===r||"to"===r});if(-1!==n&&e.args.length-1>n){const i=e.args.slice(n+1),s=i.findIndex(e=>"with"===(e.name||e.value)),a=-1===s?i:i.slice(0,s);l=await this.resolveTargets(a,t,r,o)}else{if(!r.me)throw Error(o+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(e.args,t,r),mode:n}}async execute(e,t){const r=function(e,t,r={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(r);t.it=r}async resolveTargets(e,t,r,n){const o=[];for(const n of e){const e=await t.evaluate(n,r);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&r.me)o.push(r.me);else if("you"===e&&r.you)o.push(r.you);else if("it"===e&&r.it)o.push(r.it);else if(hn(e))o.push(e);else if(e instanceof NodeList)o.push(...Array.from(e).filter(hn));else if(Array.isArray(e))o.push(...e.filter(hn));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);o.push(...Array.from(t).filter(hn));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);o.push(e)}else o.push(document);else o.push(window)}if(!o.length)throw Error(n+": no valid targets");return o}async parseEventDetail(e,t,r){if(!e?.length)return;if(1===e.length){const n=e[0];if("objectLiteral"!==n?.type)return await t.evaluate(n,r)}const n={};for(const o of e){const e=await t.evaluate(o,r);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,r]=e.split(":",2);n[t.trim()]=Io(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:!0,cancelable:!0,composed:!1},o=e.findIndex(e=>"with"===(e.name||e.value));if(-1===o)return n;for(const i of e.slice(o+1)){const e=await t.evaluate(i,r);if("string"==typeof e){const t=e.toLowerCase();"bubbles"===t?n.bubbles=!0:"nobubbles"===t?n.bubbles=!1:"cancelable"===t?n.cancelable=!0:"nocancelable"===t?n.cancelable=!1:"composed"===t&&(n.composed=!0)}}return n}},cn(t,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})();const $o=mn(Ro),Mo=mn(Ro),Do=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"go",category:"navigation"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{args:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}:{args:[]}}async execute(e,t){const{args:r}=e;if(0===r.length)throw Error("Go command requires arguments");return"string"==typeof r[0]&&"back"===r[0].toLowerCase()?(await this.goBack(),{result:"back",type:"back"}):this.isUrlNavigation(r)?{result:await this.navigateToUrl(r,t),type:"url"}:{result:await this.scrollToElement(r,t),type:"scroll"}}isUrlNavigation(e){return-1!==e.findIndex(e=>"url"===e)}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(e,t){const r=e.findIndex(e=>"url"===e),n=e[r+1];if(!n)throw Error('URL is required after "url" keyword');const o="string"==typeof n?n:n+"",i=e.includes("new")&&e.includes("window");if(!this.isValidUrl(o))throw Error(`Invalid URL: "${o}"`);if(i){if("undefined"!=typeof window&&window.open){const e=window.open(o,"_blank");e?.focus&&e.focus()}}else o.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=o):"undefined"!=typeof window&&(window.location.assign?.(o)??(window.location.href=o));return o}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}async scrollToElement(e,t){const r=this.parseScrollPosition(e),n=this.parseScrollTarget(e),o=this.parseScrollOffset(e),i=!e.includes("instantly"),s=this.resolveScrollTarget(n,t);if(!s)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const e=i?"smooth":"instant",t=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==o){s.scrollIntoView?.({behavior:e,block:t,inline:n});const{x:i,y:a}=this.calculateScrollPosition(s,r,o);window.scrollTo?.({left:i,top:a,behavior:e})}else s.scrollIntoView?.({behavior:e,block:t,inline:n})}return s}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}parseScrollPosition(e){const t={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let o=!1,i=!1;for(const s of e)"string"==typeof s&&(r.includes(s)?(t.vertical=s,o=!0):n.includes(s)&&(t.horizontal=s,i=!0));return i&&!o&&(t.vertical="nearest"),t}parseScrollTarget(e){const t=e.findIndex(e=>"of"===e);if(-1!==t&&e.length>t+1){let r=e[t+1];return"the"===r&&e.length>t+2&&(r=e[t+2]),r}for(const t of e)if("object"==typeof t&&t&&t.nodeType)return t;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const t of e)if("string"==typeof t&&!r.includes(t)&&(t.startsWith("#")||t.startsWith(".")||t.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)))return t;return"body"}parseScrollOffset(e){for(let t=0;e.length>t;t++){const r=e[t];if("string"==typeof r){const e=r.match(/^([+-]?\d+)(px)?$/);if(e)return parseInt(e[1],10)}if(("+"===r||"-"===r)&&e.length>t+1){const n=e[t+1],o="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(o))return"-"===r?-o:o}}return 0}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const r="string"==typeof e?e:e+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&hn(t.me))return t.me;if("it"===r&&hn(t.it))return t.it;if("you"===r&&hn(t.you))return t.you;const n=vo(r,t);if(hn(n))return n;if("undefined"!=typeof document)try{const e=document.querySelector(r);if(e)return e}catch{try{const e=document.getElementsByTagName(r);if(e.length>0)return e[0]}catch{}}return null}calculateScrollPosition(e,t,r){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const n=e.getBoundingClientRect(),o=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,s=window.innerWidth||800,a=window.innerHeight||600;let c=o,l=i;switch(t.horizontal){case"left":c=n.left+o;break;case"center":c=n.left+o+n.width/2-s/2;break;case"right":c=n.right+o-s}switch(t.vertical){case"top":l=n.top+i+r;break;case"middle":l=n.top+i+n.height/2-a/2+r;break;case"bottom":l=n.bottom+i-a+r}return{x:Math.max(0,c),y:Math.max(0,l)}}},cn(t,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());function Vo(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const r=vo(e,t);return void 0!==r?!!r:!!e}return!!e}const Po=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"if",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){const n="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(n+" command requires a condition to evaluate");let o,i;if("unless"===n){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");o=e.args.slice(1)}else if(e.args.length>=2&&e.args[1]?(o=e.args[1],i=3>e.args.length?void 0:e.args[2]):e.modifiers?.then&&(o=e.modifiers.then,i=e.modifiers.else),!o)throw Error('if command requires "then" branch with commands');return{mode:n,condition:await t.evaluate(e.args[0],r),thenCommands:o,elseCommands:i}}async execute(e,t){const{mode:r,condition:n,thenCommands:o,elseCommands:i}=e,s=Vo(n,t);let a,c;return("unless"===r?!s:s)?(a="then",c=await this.executeCommandsOrBlock(o,t),"unless"===r&&Object.assign(t,{it:c})):i&&"if"===r?(a="else",c=await this.executeCommandsOrBlock(i,t)):a="none",{mode:r,conditionResult:s,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 r=t.locals.get("_runtimeExecute");if(!r)throw Error("Runtime execute function not available");let n;if(e.commands?.length)for(const o of e.commands)n=await r(o,t);return n}async executeCommands(e,t){let r;for(const n of e)r=n?.execute?await n.execute(t):"function"==typeof n?await n():n;return r}},cn(t,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),Bo=Po,_o=Po;let qo=(()=>{let e,t,r=[pn({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"]}),dn({name:"repeat",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){let n;if(e.modifiers?.index){const o=await t.evaluate(e.modifiers.index,r);"string"==typeof o&&(n=o)}let o=e.modifiers?.block||e.modifiers?.commands;if(!o)for(let t=e.args.length-1;t>=0;t--){const r=e.args[t];if("block"===r?.type&&r.commands){o=r;break}}const i=e.args[0],s="identifier"===i?.type?i.name:null;if("for"===s||e.modifiers?.for){const i=e.args[1],s=i?.value||i?.name,a=e.args[2]?await t.evaluate(e.args[2],r):void 0;if(!s||void 0===a)throw Error("for loops require variable and collection");return{type:"for",variable:s,collection:Array.isArray(a)?a:[a],indexVariable:n,commands:o}}if("times"===s||e.modifiers?.times){const i=e.args[1],s=i?await t.evaluate(i,r):void 0,a="number"==typeof s?s:parseInt(s+"",10);if(isNaN(a))throw Error("times loops require a count number");return{type:"times",count:a,indexVariable:n,commands:o}}if("while"===s||e.modifiers?.while){const t=e.args[1]||e.modifiers?.while;if(!t)throw Error("while loops require a condition");return{type:"while",condition:t,indexVariable:n,commands:o}}if("until"===s&&e.modifiers?.from||"until-event"===s){const i=e.args[1],s=i?.value||i?.name;if(!s)throw Error("until-event loops require an event name");let a=r.me;if(e.args[2]){const n=await t.evaluate(e.args[2],r);n instanceof EventTarget?a=n:"document"===n&&(a=document)}return{type:"until-event",eventName:s,eventTarget:a,indexVariable:n,commands:o}}if("until"===s||e.modifiers?.until){const t=e.args[1]||e.modifiers?.until;if(!t)throw Error("until loops require a condition");return{type:"until",condition:t,indexVariable:n,commands:o}}if("forever"===s||e.modifiers?.forever)return{type:"forever",indexVariable:n,commands:o};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(e,t){const{type:r,variable:n,collection:o,condition:i,count:s,indexVariable:a,commands:c,eventName:l,eventTarget:u}=e;let f,d;switch(r){case"for":({config:f,iterCtx:d}=function(e,t,r){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:r}}}(o,n,a));break;case"times":({config:f,iterCtx:d}=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}}}(s,a));break;case"while":({config:f,iterCtx:d}=function(e,t,r,n){return{config:{type:"while",shouldContinue:()=>t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,Vo,t,a));break;case"until":({config:f,iterCtx:d}=function(e,t,r,n){return{config:{type:"until",shouldContinue:()=>!t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(i,Vo,t,a));break;case"until-event":({config:f,iterCtx:d}=function(e,t,r){const n={index:0,eventFired:!1,indexVariable:r};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{n.eventFired=!0}}},iterCtx:n}}(l,u,a));break;case"forever":({config:f,iterCtx:d}=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: "+r)}try{const e=await async function(e,t,r,n,o){const i=e.maxIterations??1e4;let s,a=0,c=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>a&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,r),n.indexVariable&&r.locals&&r.locals.set(n.indexVariable,a);try{s=await o(t,r)}catch(t){if(t instanceof Error){if(t.message.includes("BREAK")){c=!0;break}if(t.message.includes("CONTINUE")){a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}}throw t}a++,n.index=a,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:a,lastResult:s,interrupted:c}}(f,c,t,d,this.executeCommands.bind(this));return Object.assign(t,{it:e.lastResult}),{type:r,iterations:e.iterations,completed:!e.interrupted,lastResult:e.lastResult,interrupted:e.interrupted}}catch(e){if(e instanceof Error&&(e.message.includes("BREAK")||e.message.includes("CONTINUE")))return{type:r,iterations:0,completed:!0,interrupted:e.message.includes("BREAK")};throw e}}async executeCommands(e,t){if(e&&"object"==typeof e&&"block"===e.type){const r=e,n=t.locals.get("_runtimeExecute");if(!n)throw Error("Runtime execute function not available");let o;if(r.commands)for(const e of r.commands)o=await n(e,t);return o}if(Array.isArray(e)){let r;for(const n of e)r="function"==typeof n?await n(t):n&&"function"==typeof n.execute?await n.execute(t):n;return r}return"function"==typeof e?await e(t):e}},cn(t,"RepeatCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})();const Fo=mn(qo);class Ho{async parseInput(e,t,r){return{signalType:this.signalType}}async execute(e,t){const r=Error(this.errorMessage);throw r[this.errorFlag]=!0,"exit"===this.signalType&&(r.returnValue=void 0,r.timestamp=Date.now()),r}}let Uo=(()=>{let e,t,r=[pn({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"]}),dn({name:"break",category:"control-flow"})],n=[],o=Ho;return t=class extends o{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},cn(t,"BreakCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const Wo=mn(Uo);let Jo=(()=>{let e,t,r=[pn({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"]}),dn({name:"continue",category:"control-flow"})],n=[],o=Ho;return t=class extends o{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},cn(t,"ContinueCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const zo=mn(Jo),Zo=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"halt",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(e.args&&e.args.length>0){const n=e.args[0],o=e.args.length>1?e.args[1]:null;return"identifier"===n.type&&"the"===n.name&&o&&"identifier"===o.type&&"event"===o.name?{target:r.event}:{target:await t.evaluate(e.args[0],r)}}return{}}async execute(e,t){let r=e.target;if(("the"===r&&t.event||"object"==typeof r&&null!==r&&"the"===r.target&&t.event)&&(r=t.event),this.isEvent(r)){const e=r;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}"halted"in t&&(t.halted=!0);const n=Error("HALT_EXECUTION");throw n.isHalt=!0,n}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}},cn(t,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),Go=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"return",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){return e.args&&0!==e.args.length?{value:await t.evaluate(e.args[0],r)}:{value:void 0}}async execute(e,t){const{value:r}=e;"returnValue"in t&&(t.returnValue=r),Object.assign(t,{it:r});const n=Error("RETURN_VALUE");throw n.isReturn=!0,n.returnValue=r,n}},cn(t,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());let Xo=(()=>{let e,t,r=[pn({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"]}),dn({name:"exit",category:"control-flow"})],n=[],o=Ho;return t=class extends o{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},cn(t,"ExitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),an(t,n)})(),t})();const Yo=mn(Xo),Ko=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"call",category:"execution"})],n=[];return t=class{parseInput(e,t,r){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:r}=e,n=t.locals?.get("__evaluator");if(!n)throw Error("[CALL.execute] No evaluator available in context");const o=await n.evaluate(r,t);let i,s,a=!1;return"function"==typeof o?(s="function",i=o(),i instanceof Promise&&(a=!0,i=await i)):o instanceof Promise?(s="promise",a=!0,i=await o):(s="value",i=o),Object.assign(t,{it:i,result:i}),{result:i,wasAsync:a,expressionType:s}}},cn(t,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),Qo=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"append",category:"content"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("append requires content");const n=await t.evaluate(e.args[0],r);let o;return e.modifiers?.to?o=await t.evaluate(e.modifiers.to,r):e.target&&(o=e.target),{content:n,target:o}}async execute(e,t){const{content:r,target:n}=e,o=r+"";if(!n)return Object.assign(t,void 0===t.it?{it:o}:{it:t.it+""+o}),{result:t.it,targetType:"result"};if("string"==typeof n){if(n.startsWith("#")||n.startsWith(".")||n.includes("[")){const e=this.resolveDOMElement(n);return e.innerHTML+=o,{result:e,targetType:"element",target:e}}if("me"===n||"it"===n||"you"===n){const e=this.resolveContextRef(n,t);if(hn(e))return e.innerHTML+=o,{result:e,targetType:"element",target:e}}const e=vo(n,t);if(void 0!==e){if(Array.isArray(e))return e.push(r),{result:e,targetType:"array",target:n};const i=(null==e?"":e+"")+o;return go(n,i,t),{result:i,targetType:"variable",target:n}}return go(n,o,t),{result:o,targetType:"variable",target:n}}if(Array.isArray(n))return n.push(r),{result:n,targetType:"array"};if(hn(n))return n.innerHTML+=o,{result:n,targetType:"element",target:n};{const e=n+""+o;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)}}},cn(t,"AppendCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),ei=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"transition",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args?.length)throw Error("transition requires property and value");let n,o;const i=await t.evaluate(e.args[0],r);if(hn(i)||"string"==typeof i&&/^[#.]|^(?:me|it|you)$/.test(i)?(o=i,n=await t.evaluate(e.args[1],r)+""):n=i+"",!n)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let s=await t.evaluate(e.modifiers.to,r);void 0===s&&"identifier"===e.modifiers.to.type&&(s=e.modifiers.to.name);const a={property:n,value:s};return void 0!==o&&(a.target=o),e.modifiers?.over&&(a.duration=await t.evaluate(e.modifiers.over,r)),e.modifiers?.with&&(a.timingFunction=await t.evaluate(e.modifiers.with,r)+""),a}async execute(e,t){let{property:r}=e;const{target:n,value:o,duration:i,timingFunction:s}=e;r.startsWith("*")&&(r=r.substring(1)),r=r.replace(/([A-Z])/g,"-$1").toLowerCase();const a=yn(n,t),c=Gn(i,300),l=getComputedStyle(a).getPropertyValue(r),u=a.style.transition,f=`${r} ${c}ms ${s||"ease"}`;a.style.transition=u?`${u}, ${f}`:f;let d=o+"",p=!1;if("initial"===d||"inherit"===d||"unset"===d||"revert"===d){const e=a.style.getPropertyValue(r);a.style.removeProperty(r),d=getComputedStyle(a).getPropertyValue(r),e&&a.style.setProperty(r,e),p=!0}a.style.setProperty(r,d);const m=await function(e,t,r){return new Promise(n=>{const o=r=>{r.target===e&&r.propertyName===t&&s({completed:!0,cancelled:!1})},i=r=>{r.target===e&&r.propertyName===t&&s({completed:!1,cancelled:!0})},s=Ao(()=>{e.removeEventListener("transitionend",o),e.removeEventListener("transitioncancel",i),clearTimeout(a)},n);e.addEventListener("transitionend",o),e.addEventListener("transitioncancel",i);const a=setTimeout(()=>{s({completed:!0,cancelled:!1})},r+50)})}(a,r,c);return a.style.transition=u,p&&a.style.removeProperty(r),Object.assign(t,{it:a}),{element:a,property:r,fromValue:l,toValue:d,duration:c,completed:m.completed}}},cn(t,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),ti=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"measure",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,o,i;if(e.args?.length){const i=e.args[0];if("identifier"===i.type&&i.name){const s=i.name.toLowerCase();if("me"===s||"it"===s||"you"===s){const s=await t.evaluate(i,r);if(hn(s)&&(n=s,e.args.length>1)){const n=e.args[1];o="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else o=i.name}else{const s=await t.evaluate(i,r);if(hn(s)||"string"==typeof s&&/^[#.]/.test(s)){if(n=s,e.args.length>1){const n=e.args[1];o="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else"string"==typeof s&&(o=s)}}e.modifiers?.set&&(i=await t.evaluate(e.modifiers.set,r)+"");const s={};return void 0!==n&&(s.target=n),void 0!==o&&(s.property=o),void 0!==i&&(s.variable=i),s}async execute(e,t){const r=yn(e.target,t),n=e.property||"width",o=this.getMeasurement(r,n);return e.variable&&t.locals&&t.locals.set(e.variable,o.value),Object.assign(t,{it:o.value}),{result:o.value,wasAsync:!1,element:r,property:n,value:o.value,unit:o.unit,stored:!!e.variable}}getMeasurement(e,t){const r=getComputedStyle(e);if(t.startsWith("*")){const e=r.getPropertyValue(t.substring(1)),n=parseFloat(e);if(!isNaN(n)){const t=e.match(/([a-zA-Z%]+)$/);return{value:n,unit:t?t[1]:""}}return{value:e,unit:""}}const n=t.toLowerCase(),o=e.getBoundingClientRect(),i={width:()=>o.width,height:()=>o.height,top:()=>o.top,left:()=>o.left,right:()=>o.right,bottom:()=>o.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(i[n])return{value:i[n](),unit:"px"};const s=r.getPropertyValue(t),a=parseFloat(s);if(!isNaN(a)){const e=s.match(/([a-zA-Z%]+)$/);return{value:a,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}},cn(t,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),ri=mn((()=>{let e,t,r=[pn({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),dn({name:"settle",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){let n,o;if(e.args&&e.args.length>0){const o=await t.evaluate(e.args[0],r);(hn(o)||"string"==typeof o&&(o.startsWith("#")||o.startsWith(".")||"me"===o||"it"===o||"you"===o))&&(n=o)}e.modifiers?.for&&(o=await t.evaluate(e.modifiers.for,r));const i={};return void 0!==n&&(i.target=n),void 0!==o&&(i.timeout=o),i}async execute(e,t){const{target:r,timeout:n}=e,o=yn(r,t),i=Gn(n,5e3),s=Date.now(),a=getComputedStyle(o),c=Yn(a.transitionDuration),l=Yn(a.transitionDelay),u=Yn(a.animationDuration),f=Yn(a.animationDelay),d=Kn(c,l),p=Kn(u,f),m=Math.max(d,p),h=await(y=o,v=m,g=i,v>0?new Promise(e=>{const t=e=>{e.target===y&&n({completed:!0,type:"transition"})},r=e=>{e.target===y&&n({completed:!0,type:"animation"})},n=Ao(()=>{y.removeEventListener("transitionend",t),y.removeEventListener("animationend",r),clearTimeout(o),clearTimeout(i)},e);y.addEventListener("transitionend",t),y.addEventListener("animationend",r);const o=setTimeout(()=>{n({completed:!0,type:"timeout"})},v+50),i=setTimeout(()=>{n({completed:!1,type:"timeout"})},g)}):Promise.resolve({completed:!0,type:"timeout"}));var y,v,g;const b=Date.now()-s;return Object.assign(t,{it:o}),{element:o,settled:h.completed,timeout:i,duration:b}}},cn(t,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),ni=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"js",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){let n,o;if(0===e.args.length)throw Error("js command requires JavaScript code");const i=e.args[0],s=e.args[1];if(i&&"literal"===i.type&&"string"==typeof i.value)n=i.value;else{if(!i||void 0===i.value)throw Error("js command requires JavaScript code");n=i.value+""}s&&"arrayLiteral"===s.type&&Array.isArray(s.elements)&&(o=s.elements.map(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const a={code:n};return o&&o.length>0&&(a.parameters=o),a}async execute(e,t){const{code:r,parameters:n=[]}=e;if(!r.trim())return{result:void 0,executed:!1,codeLength:r.length,parameters:n,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,n),o=Function(...Object.keys(e),r),i=await o(...Object.values(e));return void 0!==i&&Object.assign(t,{it:i}),{result:i,executed:!0,codeLength:r.length,parameters:n,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,r)=>{let n=e.locals?.get(r);return void 0===n&&(n=e.variables?.get(r)),void 0===n&&(n=e[r]),t[r]=n,t},{})}}},cn(t,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),oi=mn((()=>{let e,t,r=[pn({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),dn({name:"async",category:"advanced"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("async command requires at least one command to execute");return{commands:e.args}}async execute(e,t){const{commands:r}=e,n=Date.now();try{const e=await this.executeCommandsAsync(t,r),o=Date.now()-n;return e.length>0&&Object.assign(t,{it:e[e.length-1]}),{commandCount:r.length,results:e,executed:!0,duration:o}}catch(e){throw Error("Async command execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}async executeCommandsAsync(e,t){const r=[];for(let n=0;t.length>n;n++){const o=t[n];try{const t=await this.executeCommand(o,e);r.push(t),Object.assign(e,{it:t})}catch(e){const r=this.getCommandName(o);throw Error(`Command '${r}' (${n+1}/${t.length}) failed: ${e instanceof Error?e.message:"Unknown error"}`)}}return r}async executeCommand(e,t){if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}getCommandName(e){return"function"==typeof e?e.name||"anonymous function":e&&"object"==typeof e?e.name||"unnamed command":"unknown"}},cn(t,"AsyncCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),ii=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"default",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("default command requires a target");const n=await t.evaluate(e.args[0],r);let o;if(e.modifiers?.to)o=await t.evaluate(e.modifiers.to,r);else{if(2>e.args.length)throw Error('default command requires a value (use "to <value>")');o=await t.evaluate(e.args[1],r)}return{target:n,value:o}}async execute(e,t){const{target:r,value:n}=e;if("string"==typeof r){if(r.startsWith("@"))return this.defaultAttribute(t,r.substring(1),n);const e=r.match(/^(my|its?|your?)\s+(.+)$/);if(e){const[,r,o]=e;return this.defaultElementProperty(t,r,o,n)}return this.defaultVariable(t,r,n)}if(hn(r))return this.defaultElementValue(t,r,n);throw Error("Invalid target type: "+typeof r)}defaultVariable(e,t,r){const n=vo(t,e);return void 0!==n?{target:t,value:r,wasSet:!1,existingValue:n,targetType:"variable"}:(go(t,r,e),Object.assign(e,{it:r}),{target:t,value:r,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,r){if(!e.me)throw Error("No element context available for attribute default");const n=e.me.getAttribute(t);return null!==n?{target:"@"+t,value:r,wasSet:!1,existingValue:n,targetType:"attribute"}:(e.me.setAttribute(t,r+""),Object.assign(e,{it:r}),{target:"@"+t,value:r,wasSet:!0,targetType:"attribute"})}defaultElementProperty(e,t,r,n){const o=bn(t,e),i=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const r=t.split(".");let n=e;for(const e of r){if(null==n)break;n=n[e]}return n}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(o,r),s=`${t} ${r}`;return oo(i)?(no(o,r,n),Object.assign(e,{it:n}),{target:s,value:n,wasSet:!0,targetType:"property"}):{target:s,value:n,wasSet:!1,existingValue:i,targetType:"property"}}defaultElementValue(e,t,r){const n=function(e){return"value"in e?e.value:e.textContent}(t);return oo(n)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,r),Object.assign(e,{it:r}),{target:"element",value:r,wasSet:!0,targetType:"element"}):{target:"element",value:r,wasSet:!1,existingValue:n,targetType:"element"}}},cn(t,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());class si{constructor(){this.name="pseudo-command"}get metadata(){return si.metadata}async parseInput(e,t,r){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const n=e.args[0].properties||[];let o,i,s="",a=[];for(const e of n){const n=e.value;switch(e.key?.name||e.key?.value){case"methodName":s=n?.value||await t.evaluate(n,r)+"";break;case"methodArgs":"arrayLiteral"===n?.type&&n.elements?a=await Promise.all(n.elements.map(e=>t.evaluate(e,r))):"literal"===n?.type&&Array.isArray(n.value)&&(a=await Promise.all(n.value.map(e=>t.evaluate(e,r))));break;case"preposition":const e=n?.value;e&&"null"!==e&&(o=e);break;case"target":case"targetExpression":i=await t.evaluate(n,r)}}if(!s)throw Error("pseudo-command requires method name");if(null==i)throw Error("pseudo-command requires a target expression");return{methodName:s,methodArgs:a,preposition:o,targetExpression:i}}if(2>e.args.length)throw Error("pseudo-command requires method name and target expression");const n=await t.evaluate(e.args[0],r)+"",o=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,r))):[];let i,s;const a=["from","on","with","into","at","to"];for(const n of a)if(e.modifiers?.[n]){s=n,i=await t.evaluate(e.modifiers[n],r);break}if(i||3>e.args.length||(i=await t.evaluate(e.args[2],r)),!i)throw Error("pseudo-command requires a target expression");return{methodName:n,methodArgs:o,preposition:s,targetExpression:i}}async execute(e,t){const{methodName:r,methodArgs:n,targetExpression:o}=e;try{const e=await this.resolveTarget(o,t);if(null==e)throw Error("Target expression resolved to "+e);const i=this.resolveMethod(e,r);if(!i)throw Error(`Method "${r}" not found on target object`);if("function"!=typeof i)throw Error(`"${r}" is not a function (it's a ${typeof i})`);const s=await this.executeMethod(i,e,n);return t.locals.set("result",s),Object.assign(t,{it:s}),{result:s,methodName:r,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const r=e.split(".");let n="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(r[0])?(n=t.locals.get(r[0]),r.shift()):t.variables?.has(r[0])?(n=t.variables.get(r[0]),r.shift()):t.globals.has(r[0])&&(n=t.globals.get(r[0]),r.shift());for(const e of r){if(null==n)return null;n=n[e]}return n}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const r=t.split(".");let n=e;for(let e=0;r.length>e;e++){const t=r[e];if(null==n)return null;if(!(t in n))return null;if(n=n[t],e===r.length-1&&"function"==typeof n)return n}return null}async executeMethod(e,t,r){try{const n=e.apply(t,r);return n&&"object"==typeof n&&"then"in n?await n:n}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}function ai(){return new si}si.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 ci=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"tell",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],r),commands:e.args.slice(1)}}async execute(e,t){const{target:r,commands:n}=e,o=vn(r,t);if(0===o.length)throw Error("tell command found no target elements");const i=t.locals.get("_runtimeExecute"),s=[];for(const e of o){const r={...t,me:e,you:e};for(const e of n)try{const t=await this.executeCommand(e,r,i);s.push(t),Object.assign(r,{it:t})}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}}return{targetElements:o,commandResults:s,executionCount:o.length*n.length}}async executeCommand(e,t,r){if(e&&"object"==typeof e&&"command"===e.type&&r)return await r(e,t);if("function"==typeof e)return await e(t);if(e&&"object"==typeof e&&"function"==typeof e.execute)return await e.execute(t);throw Error("Invalid command: must be a function or object with execute method")}},cn(t,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());let li=(()=>{let e,t,r=[pn({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"]}),dn({name:"copy",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("copy command requires a source (text or element)");const n=await t.evaluate(e.args[0],r);let o="text";if(e.modifiers?.format){const n=await t.evaluate(e.modifiers.format,r);"html"!==n&&"text"!==n||(o=n)}return{source:n,format:o}}async execute(e,t){const{source:r,format:n="text"}=e,o=this.extractText(r,n,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(o),this.dispatchCopyEvent(t,"copy:success",{text:o,method:"clipboard-api"}),{success:!0,text:o,format:n,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(o))return this.dispatchCopyEvent(t,"copy:success",{text:o,method:"execCommand"}),{success:!0,text:o,format:n,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:o,error:"All copy methods failed"}),{success:!1,text:o,format:n,method:"fallback"}}extractText(e,t,r){if("string"==typeof e)return e;if(hn(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&hn(r.me)){const e=r.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,r){if(hn(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},cn(t,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})();const ui=mn(li),fi=mn((()=>{let e,t,r=[pn({description:"Select a random element from a collection",syntax:["pick <item1>, <item2>, ...","pick from <array>"],examples:['pick "red", "green", "blue"',"pick from colors","pick 1, 2, 3, 4, 5"],sideEffects:["random-selection"]}),dn({name:"pick",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){if(e.modifiers?.from){const n=await t.evaluate(e.modifiers.from,r);if(!Array.isArray(n))throw Error("pick from requires an array");if(0===n.length)throw Error("Cannot pick from empty array");return{array:n}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{items:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const{items:r,array:n}=e,o=r||n,i=r?"items":"array",s=Math.floor(Math.random()*o.length),a=o[s];return Object.assign(t,{it:a}),{selectedItem:a,selectedIndex:s,sourceLength:o.length,sourceType:i}}},cn(t,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})()),di=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"throw",category:"control-flow"})],n=[];return t=class{async parseInput(e,t,r){if(1>e.args.length)throw Error("throw command requires a message or error object");return{message:await t.evaluate(e.args[0],r)}}async execute(e,t){const{message:r}=e;let n;throw n=r instanceof Error?r:Error("string"==typeof r?r:r+""),n}},cn(t,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());const pi=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"beep",category:"utility"})],n=[];return t=class{async parseInput(e,t,r){return 0===e.args.length?{expressions:[]}:{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.expressions||[];if(0===r.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const n=[];console.group("🔔 beep! Debug Output");for(const e of r){const t=this.debugExpression(e);n.push(t),console.log("Value:",e),console.log("Type:",t.type),console.log("Representation:",t.representation),console.log("---")}return console.groupEnd(),{expressionCount:r.length,debugged:!0,outputs:n}}debugContext(e){console.group("🔔 beep! Context Debug"),console.log("me:",e.me),console.log("it:",e.it),console.log("you:",e.you),console.log("locals:",e.locals),console.log("globals:",e.globals),console.log("variables:",e.variables),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":hn(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(hn(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+""}},cn(t,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());class mi{constructor(){this.name="install"}get metadata(){return mi.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("install command requires a behavior name");const n=e.args[0];let o,i,s;if(o="identifier"===n?.type&&"string"==typeof n.name?n.name:await t.evaluate(n,r)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(o))throw Error(`Behavior name must be PascalCase (start with uppercase): "${o}"`);if(e.args.length>=2){const n=await t.evaluate(e.args[1],r);if(n&&"object"==typeof n&&!Array.isArray(n)){i=n;for(const e of Object.keys(i))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}return e.modifiers?.on&&(s=await t.evaluate(e.modifiers.on,r)),{behaviorName:o,parameters:i,target:s}}async execute(e,t){const{behaviorName:r,parameters:n={},target:o}=e;try{const e=this.resolveTarget(o,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(r,t))throw Error(`Behavior "${r}" is not defined. Define it using the 'behavior' keyword before installing.`);const i=[];for(const o of e){const e=await this.installBehavior(r,o,n,t);i.push(e)}return{success:!0,behaviorName:r,installedCount:i.length,instances:i}}catch(e){throw Error(`Failed to install behavior "${r}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(hn(e))return[e];throw Error('No target specified and "me" is not available in context')}if(hn(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>hn(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(hn(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),r=Array.from(t).filter(e=>hn(e));if(0===r.length)throw Error(`No elements found matching selector: "${e}"`);return r}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>hn(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(hn(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+e)}behaviorExists(e,t){const r=t.locals.get("_behaviors");if(r&&"object"==typeof r)return r.has(e);if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors)return t.behaviors.has(e)}return!1}async installBehavior(e,t,r,n){const o=n.locals.get("_behaviors");if(o&&"object"==typeof o){const n=o;if(n.install&&"function"==typeof n.install)return await n.install(e,t,r)}if("undefined"!=typeof globalThis){const n=globalThis._hyperscript;if(n?.behaviors?.install)return await n.behaviors.install(e,t,r)}throw Error("Behavior system not available in context")}}function hi(){return new mi}mi.metadata={description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",sideEffects:["behavior-installation","element-modification"]};const yi=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"take",category:"animation"})],n=[];return t=class{async parseInput(e,t,r){if(3>e.args.length)throw Error('take requires property, "from", and source');const n=await t.evaluate(e.args[0],r)+"";if("from"!==await t.evaluate(e.args[1],r))throw Error("take syntax: take <property> from <source>");const o=await t.evaluate(e.args[2],r);let i;if(8>e.args.length)e.args.length>3&&(i=await t.evaluate(e.args[3],r));else{const n=await Promise.all([3,4,5,6].map(n=>t.evaluate(e.args[n],r)));"and"===n[0]&&"put"===n[1]&&"it"===n[2]&&"on"===n[3]&&e.args[7]&&(i=await t.evaluate(e.args[7],r))}return!i&&e.modifiers?.on&&(i=await t.evaluate(e.modifiers.on,r)),{property:n,source:o,target:i}}async execute(e,t){const r=yn(e.source,t),n=yn(e.target?e.target:void 0,t),o=this.takeProperty(r,e.property);return this.putProperty(n,e.property,o),{targetElement:n,property:e.property,value:o}}takeProperty(e,t){const r=t.trim(),n=r.toLowerCase();if("class"===n||"classes"===n){const t=Array.from(e.classList);return e.className="",t}if(r.startsWith(".")){const t=r.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(r.startsWith("@")){const t=r.substring(1),n=e.getAttribute(t);return e.removeAttribute(t),n}if(r.startsWith("data-")){const t=e.getAttribute(r);return e.removeAttribute(r),t}if("id"===n){const t=e.id;return e.id="",t}if("title"===n){const t=e.title;return e.title="",t}if("value"===n&&"value"in e){const t=e.value;return e.value="",t}const o=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(r.includes("-")||o in e.style||r in e.style){let t;return o in e.style?(t=e.style[o],e.style[o]=""):r in e.style?(t=e.style[r],e.style[r]=""):(t=e.style.getPropertyValue(r),e.style.removeProperty(r)),t}const i=e.getAttribute(t);return null!==i?(e.removeAttribute(t),i):null}putProperty(e,t,r){if(null==r)return;const n=t.trim(),o=n.toLowerCase();if("class"===o||"classes"===o)return void(Array.isArray(r)?r.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof r&&(e.className=r));if(n.startsWith("."))return void(r&&e.classList.add(n.substring(1)));if(n.startsWith("@"))return void e.setAttribute(n.substring(1),r+"");if(n.startsWith("data-"))return void e.setAttribute(n,r+"");if("id"===o)return void(e.id=r+"");if("title"===o)return void(e.title=r+"");if("value"===o&&"value"in e)return void(e.value=r+"");const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());n.includes("-")||i in e.style||n in e.style?i in e.style?e.style[i]=r+"":n in e.style?e.style[n]=r+"":e.style.setProperty(n,r+""):e.setAttribute(t,r+"")}},cn(t,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());class vi{constructor(){this.name="render"}get metadata(){return vi.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("render command requires a template");const n=await t.evaluate(e.args[0],r);let o;if(e.args.length>=3&&"with"===await t.evaluate(e.args[1],r)){const n=await t.evaluate(e.args[2],r);n&&"object"==typeof n&&(o=n)}if(!o&&e.modifiers?.with){const n=await t.evaluate(e.modifiers.with,r);n&&"object"==typeof n&&(o=n)}return{template:n,variables:o}}async execute(e,t){const{template:r,variables:n={}}=e,o=this.extractTemplateContent(r,t),i=this.createTemplateContext(t,n),s=[],a=await this.processTemplate(o,i,s),c=this.createDOMElement(a);return Object.assign(t,{it:c}),{element:c,rendered:a,directivesProcessed:s}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let r=e;if(!r.includes("<")&&!r.includes("$")){const e=this.resolveVariable(r,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(r=e)}const n=r.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return n?n[1]:r}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,r){const n=e.split("\n"),o=[];let i=0;for(;n.length>i;){const e=n[i].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:s}=await this.processRepeatDirective(n,i,t);o.push(s),i=e,r.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:s}=await this.processIfDirective(n,i,t,r);o.push(s),i=e,r.push("@if")}else if("@else"===e||"@end"===e)i++;else{const r=this.processVariableInterpolation(e,t);o.push(r),i++}}return o.join("\n")}async processRepeatDirective(e,t,r){const n=e[t].trim(),o=n.match(/^@repeat\s+in\s+(.+)$/);if(!o)throw Error("Invalid @repeat syntax: "+n);const i=this.evaluateExpression(o[1],r),{endIndex:s,blockContent:a}=this.extractDirectiveBlock(e,t+1),c=[];if(Array.isArray(i))for(const e of i){const t={...r,locals:new Map([...r.locals.entries(),["it",e]])},n=await this.processTemplate(a.join("\n"),t,[]);c.push(n)}return{nextIndex:s+1,rendered:c.join("\n")}}async processIfDirective(e,t,r,n){const o=e[t].trim(),i=o.match(/^@if\s+(.+)$/);if(!i)throw Error("Invalid @if syntax: "+o);const s=!!this.evaluateExpression(i[1],r),{endIndex:a,blockContent:c,elseContent:l}=this.extractIfElseBlock(e,t+1);let u="";return s?u=await this.processTemplate(c.join("\n"),r,[]):l.length>0&&(u=await this.processTemplate(l.join("\n"),r,[]),n.push("@else")),{nextIndex:a+1,rendered:u}}extractDirectiveBlock(e,t){const r=[];let n=1,o=t;for(;e.length>o&&n>0;){const t=e[o].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(n++,r.push(e[o])):"@end"===t?(n--,n>0&&r.push(e[o])):r.push(e[o]),o++}return{endIndex:o-1,blockContent:r}}extractIfElseBlock(e,t){const r=[],n=[];let o=1,i=t,s=!1;for(;e.length>i&&o>0;){const t=e[i].trim();if(t.startsWith("@if "))o++;else{if("@else"===t&&1===o){s=!0,i++;continue}if("@end"===t&&(o--,0===o))break}s?n.push(e[i]):r.push(e[i]),i++}return{endIndex:i,blockContent:r,elseContent:n}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=r.trim();if(e.startsWith("unescaped ")){const r=e.substring(10).trim();return(this.evaluateExpression(r,t)||"")+""}const n=this.evaluateExpression(e,t);return this.escapeHtml((n||"")+"")}catch(t){return console.warn(`Template interpolation error for ${r}:`,t),e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const r=Number(e);if(!isNaN(r)&&""!==e.trim())return r;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++){if("object"!=typeof n||null===n)return;n=n[r[e]]}return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:"result"===e?t.result:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&").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 gi(){return new vi}vi.metadata={description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",sideEffects:["dom-creation","template-execution"]};class bi extends rn{constructor(e={}){const t=e.registry||new zr;let r;e.registry||(t.register(Sn()),t.register(Nn()),t.register(Un()),t.register(zn()),t.register(mo()),t.register(ho()),t.register(wo()),t.register(So()),t.register(No()),t.register(Oo()),t.register(ko()),t.register(jo()),t.register(Lo()),t.register($o()),t.register(Mo()),t.register(Do()),t.register(Bo()),t.register(Fo()),t.register(Wo()),t.register(zo()),t.register(Zo()),t.register(Go()),t.register(Yo()),t.register(Ko()),t.register(Qo()),t.register(ei()),t.register(ti()),t.register(ri()),t.register(ni()),t.register(oi()),t.register(_o()),t.register(ii()),t.register(ai()),t.register(ci()),t.register(ui()),t.register(fi()),t.register(di()),t.register(pi()),t.register(hi()),t.register(yi()),t.register(gi()),console.log("RuntimeExperimental: Registered 43 V2 commands (Phase 6 COMPLETE - All commands migrated)")),r=e.expressionEvaluator?e.expressionEvaluator:e.lazyLoad?new on({preload:e.expressionPreload||"core"}):new Ur;const n={registry:t,expressionEvaluator:r};void 0!==e.enableAsyncCommands&&(n.enableAsyncCommands=e.enableAsyncCommands),void 0!==e.commandTimeout&&(n.commandTimeout=e.commandTimeout),void 0!==e.enableErrorReporting&&(n.enableErrorReporting=e.enableErrorReporting),super(n)}}const wi=mn((()=>{let e,t,r=[pn({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"]}),dn({name:"get",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const n=e.args[0],o=await t.evaluate(n,r);return o instanceof NodeList&&1===o.length||Array.isArray(o)&&1===o.length?{value:o[0]}:{value:o}}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}},cn(t,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;sn(null,e={value:t},r,{kind:"class",name:t.name,metadata:o},null,n),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),an(t,n)})(),t})());function Ei(){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>')}const xi=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],Ai=function(e,t={}){const r=new zr;for(const t of e)r.register(t);return new bi({...t,registry:r})}([Sn(),Nn(),Un(),zn(),mo(),ho(),wo(),So(),No(),Oo(),wi(),ko(),jo(),ii(),$o(),Mo(),Do(),Bo(),Fo(),Wo(),zo(),Zo(),Go(),Yo(),_o(),di(),Ko(),ai(),Qo(),ei(),ti(),ri(),yi(),ni(),oi(),Lo(),ci(),ui(),fi(),pi(),hi(),gi()],{expressionPreload:"all"}),Si={async execute(e,t,r){const n=Ei(),o=n.createSemanticAnalyzer().analyze(e,t);if(.5>o.confidence||!o.node)throw Error(`Failed to parse "${e}" in language "${t}" (confidence: ${o.confidence.toFixed(2)})`);const i=n.buildAST(o.node),s=w(r);return Ai.execute(i.ast,s)},parse(e,t){const r=Ei(),n=r.createSemanticAnalyzer().analyze(e,t);return.5>n.confidence||!n.node?null:r.buildAST(n.node).ast},translate:(e,t,r)=>Ei().translate(e,t,r),getAllTranslations:(e,t)=>Ei().getAllTranslations(e,t),createContext:b,runtime:Ai,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:xi,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await Ci():e instanceof HTMLElement&&await Oi(e)},process:async e=>Si.processNode(e)},Ti=new WeakSet;let Ni=null;async function Oi(e){if(Ti.has(e))return;const t=e.getAttribute("_");if(t)try{const r=function(e){const t=e.getAttribute("data-lang");if(t&&xi.includes(t))return t;let r=e;for(;r;){const e=r.getAttribute("lang");if(e){const t=e.split("-")[0].toLowerCase();if(xi.includes(t))return t}r=r.parentElement}return"en"}(e);m(`ATTR-ML: Processing element with lang="${r}":`,t.substring(0,60));const n=Ei(),o=n.createSemanticAnalyzer().analyze(t,r);if(.5>o.confidence||!o.node)return void m(`ATTR-ML: Low confidence (${o.confidence.toFixed(2)}) for: ${t}`);const i=n.buildAST(o.node),s=w(e);await Ai.execute(i.ast,s),Ti.add(e),m("ATTR-ML: Successfully processed element")}catch(e){m("ATTR-ML: Error processing element:",e.message)}}async function Ci(){const e=document.querySelectorAll("[_]");m(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(Oi(e))}),await Promise.all(t),m("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("hyperfixi:initialized",{detail:{elementsProcessed:e.length}}))}function ki(){"undefined"!=typeof MutationObserver&&(Ni=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&Oi(t).catch(e=>{m("ATTR-ML: Error processing dynamic element:",e)});const r=t.querySelectorAll?.("[_]");r?.forEach(e=>{e instanceof HTMLElement&&Oi(e).catch(e=>{m("ATTR-ML: Error processing dynamic descendant:",e)})})})}),Ni.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.hyperfixi=Si,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",()=>{Ci().then(()=>ki())}):Ci().then(()=>ki())),e.default=Si,e.hyperfixi=Si,Object.defineProperty(e,"u",{value:!0}),e}({});
|
|
2
2
|
//# sourceMappingURL=hyperfixi-multilingual.js.map
|