@lokascript/core 1.2.0 → 1.3.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.
@@ -1,2 +1,2 @@
1
- var _lokascriptMultilingualInternal=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{ok:!0,value:e}}function n(e){return{ok:!1,error:e}}function o(e){return!0===e.ok}const i=function(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),s=i,a=i,c=i,l=i,u=(...e)=>{s&&console.log("🔧",...e)},f=(...e)=>{a&&console.log("🎯",...e)},d=(...e)=>{c&&console.log("🔍",...e)},m=(...e)=>{c&&console.log("🔍",...e)},p=(...e)=>{l&&console.log("🚀",...e)};class y{constructor(e){this.elementCleanups=new WeakMap,this.trackedElements=new Set,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&&p(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&p("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&p("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&p("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&&p("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e)||[];r.push(t),this.elementCleanups.set(e,r),this.trackedElements.add(e),this.debugMode&&p(`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&&p("CleanupRegistry: Error during cleanup:",e)}return this.elementCleanups.delete(e),this.trackedElements.delete(e),this.debugMode&&p(`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&&p("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&p(`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.trackedElements){const s=this.elementCleanups.get(i);if(s)for(const i of s)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":o++}}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.trackedElements.size,listeners:e,observers:t,intervals:r,timeouts:n,custom:o,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}const h=new Map;function v(e,t){return{me:e||null,it:null,you:null,result:null,locals:new Map,globals:t||h,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class g{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 b{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 w=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 E(e){const t=w.get("String");return t?t.isType(e):"string"==typeof e}function x(e){const t=w.get("Number");return t?t.isType(e):"number"==typeof e}function A(e){const t=w.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function S(e){const t=w.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function T(e){const t=w.get("Function");return t?t.isType(e):"function"==typeof e}function O(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}function C(e){return e instanceof Element}const N={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=>O(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=>O(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,hidden:e=>function(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}(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};function k(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}const r=N[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return function(e,t){return e.getAttribute(t)}(e,t);const n=e[t];return T(n)?n.bind(e):n}class j{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 m("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||e.content||"";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);default:throw Error("Unsupported AST node type for evaluation: "+e.type)}}async evaluateWithResult(e,t){try{return r(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return n({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return n({type:"exit",returnValue:t.returnValue});if(t.isBreak)return n({type:"break"});if(t.isContinue)return n({type:"continue"});if(t.isReturn)return n({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){let r=e.value||"";m("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 this.resolveTemplateVariable(i,t);m(`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);const n=r.indexOf("}",e);if(-1===n)throw Error("Unterminated template expression in: "+r);const o=r.slice(e+2,n);let i;m("TEMPLATE: Evaluating expression:",o);const c=o.trim();t.locals.has(c)?(i=t.locals.get(c),m(`TEMPLATE: Found in locals: ${c} =`,i)):t.variables&&t.variables.has(c)?(i=t.variables.get(c),m(`TEMPLATE: Found in variables: ${c} =`,i)):t.globals&&t.globals.has(c)?(i=t.globals.get(c),m(`TEMPLATE: Found in globals: ${c} =`,i)):(i=await this.evaluateSimpleExpression(o,t),m(`TEMPLATE: Evaluated expression "${o}" =`,i)),s+=i+"",a=n+1}return s}async resolveTemplateVariable(e,t){if(e.includes(".")){const r=e.split(".");let n=this.lookupTemplateVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.lookupTemplateVariable(e,t)}lookupTemplateVariable(e,t){return 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:"it"===e?t.it:"result"===e?t.result:void 0}async evaluateSimpleExpression(e,t){m("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,o]=r;m("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:o});const i=await this.resolveValue(e.trim(),t);if(m("EVAL: Ternary condition value:",i),i){const e=await this.resolveValue(n.trim(),t);return m("EVAL: Ternary returned true branch:",e),e}{const e=await this.resolveValue(o.trim(),t);return m("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;m("EVAL: Parsed arithmetic:",{left:e,operator:r,right:o});const i=await this.resolveValue(e.trim(),t),s=await this.resolveValue(o.trim(),t);m("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 m("EVAL: Arithmetic result:",e),e}}const o=await this.resolveValue(e.trim(),t);return m("EVAL: Fallback result:",o),o}async resolveValue(e,t){if(m(`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 m(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return m(`RESOLVE: Found '${e}' in variables:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return m(`RESOLVE: Found '${e}' in globals:`,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.variables&&t.variables.has(n)?o=t.variables.get(n):t.globals&&t.globals.has(n)&&(o=t.globals.get(n)),null!=o){for(let e=1;r.length>e;e++){if(null==o)return void m(`RESOLVE: Property access failed at '${r[e-1]}'`);o=o[r[e]]}return m(`RESOLVE: Property access '${e}' =`,o),o}}return e}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;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 m("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=n.name||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)];{i=this.unwrapSelectorResult(i);const e=n.name||n;if("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.getAttribute(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}}async evaluateBinaryExpression(e,t){const{operator:r,left:n,right:o}=e;if("in"===r&&"selector"===n.type){let e=n.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const r=this.unwrapSelectorResult(await this.evaluate(o,t));if(!r||"function"!=typeof r.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof r})`);const i=r.querySelectorAll(e);return Array.from(i)}if("in"===r&&"queryReference"===n.type){let e=n.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const r=this.unwrapSelectorResult(await this.evaluate(o,t));if(!r||"function"!=typeof r.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof r})`);const i=r.querySelectorAll(e);return Array.from(i)}if("in"===r){let e=null,r=null;if("positionalExpression"===n.type){e=n.operator;const o=n.argument;"cssSelector"===o?.type?r=o.selector:"selector"===o?.type?r=o.value:"classSelector"===o?.type?r="."+o.className:"idSelector"===o?.type?r="#"+o.id:o&&(r=await this.evaluate(o,t)+"")}else if("memberExpression"!==n.type||"identifier"!==n.object?.type||"first"!==n.object.name&&"last"!==n.object.name){if("callExpression"===n.type&&"identifier"===n.callee?.type&&("first"===n.callee.name||"last"===n.callee.name)){e=n.callee.name;const o=n.arguments?.[0];"selector"===o?.type?r=o.value:"cssSelector"===o?.type?r=o.selector:"classSelector"===o?.type?r="."+o.className:"idSelector"===o?.type?r="#"+o.id:o&&(r=await this.evaluate(o,t)+"")}}else e=n.object.name,"identifier"===n.property?.type&&n.property.name&&(r="."+n.property.name);if(e&&r){const n=this.unwrapSelectorResult(await this.evaluate(o,t));if(!n||"function"!=typeof n.querySelectorAll)return;const i=n.querySelectorAll(r),s=Array.from(i);return"first"===e?s.length>0?s[0]:void 0:"last"===e?s.length>0?s[s.length-1]:void 0:s}}if("matches"===r&&("selector"===o.type||"cssSelector"===o.type||"classSelector"===o.type)){const e=await this.evaluate(n,t),r=o.value||o.selector;if(e&&"function"==typeof e.matches)try{return e.matches(r)}catch{return!1}return!1}const i=await this.evaluate(n,t),s=await this.evaluate(o,t);if("has"===r||"have"===r){if(i instanceof Element&&("cssSelector"===o.type&&"class"===o.selectorType||"selector"===o.type&&o.value?.startsWith("."))){const e=o.selector?.slice(1)||o.value?.slice(1)||"";return i.classList.contains(e)}return!1}switch(r){case">":case"is greater than":return i>s;case"<":case"is less than":return s>i;case">=":case"is greater than or equal to":return i>=s;case"<=":case"is less than or equal to":return s>=i;case"==":case"equals":case"is equal to":return i==s;case"===":case"is really equal to":case"really equals":return i===s;case"!=":case"is not equal to":return i!=s;case"!==":case"is not really equal to":return i!==s;case"+":if("string"==typeof i||"string"==typeof s){const e=this.expressionRegistry.get("stringConcatenation");if(e){m("Using string concatenation for:",{leftValue:i,rightValue:s});const r=await e.evaluate(t,{left:i,right:s});return r.success?r.value:i+s}}else{const e=this.expressionRegistry.get("addition");if(e){m("Using numeric addition for:",{leftValue:i,rightValue:s});const r=await e.evaluate(t,{left:i,right:s});return r.success?r.value:i+s}}return i+s;case"-":return i-s;case"*":return i*s;case"/":return i/s;case"%":case"mod":return i%s;case"as":const e="string"==typeof s?s:"identifier"===o.type?o.name:"literal"===o.type?o.value:s+"",a=this.expressionRegistry.get("as");return a?a.evaluate(t,i,e):i;case"&&":case"and":return i&&s;case"||":case"or":return i||s;case"is":return i===s;case"is not":return i!==s;case"is a":case"is an":switch("identifier"===o.type?o.name.toLowerCase():(s+"").toLowerCase()){case"string":return"string"==typeof i;case"number":return"number"==typeof i;case"boolean":return"boolean"==typeof i;case"object":return"object"==typeof i&&null!==i;case"array":return Array.isArray(i);case"function":return"function"==typeof i;case"null":return null===i;case"undefined":return void 0===i;default:const e="identifier"===o.type?o.name:s+"";return null!=i&&i.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===o.type?o.name.toLowerCase():(s+"").toLowerCase()){case"string":return"string"!=typeof i;case"number":return"number"!=typeof i;case"boolean":return"boolean"!=typeof i;case"object":return!("object"==typeof i&&null!==i);case"array":return!Array.isArray(i);case"function":return"function"!=typeof i;case"null":return null!==i;case"undefined":return void 0!==i;default:const e="identifier"===o.type?o.name:s+"";return!(null!=i&&i.constructor?.name===e)}case"=":if("identifier"===n.type){const e=n.name;return"result"===e?Object.assign(t,{result:s}):"it"===e?Object.assign(t,{it:s}):"you"===e?t.you=s:(t.variables||Object.assign(t,{variables:new Map}),t.variables.set(e,s)),s}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(i)?i.includes(s):"string"==typeof i?i.includes(s+""):!(!i||"function"!=typeof i.matches)&&i.matches(s+"");case"match":case"matches":if(i&&"function"==typeof i.matches){const e="string"==typeof s?s:s+"";try{return i.matches(e)}catch{return!1}}return!1;case"in":const c="string"==typeof i?i:i+"",l=s;if(!l||"function"!=typeof l.querySelector){if(Array.isArray(l))return l.includes(i);if("object"==typeof l&&null!==l)return c in l;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof l})`)}return l.querySelector(c);case" ":return"string"==typeof i&&"string"==typeof s?{command:i,selector:s}:"identifier"===n.type&&"selector"===o.type?{command:n.name,selector:o.value}:s;default:throw Error(`Unsupported binary operator: "${r}" (length: ${r.length})`)}}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){const{callee:r,arguments:n,isConstructor:o}=e;if(o){const e=r.name,o=t.globals?.get(e)||window[e];if("function"==typeof o)return new o(...await Promise.all(n.map(e=>this.evaluate(e,t))));throw Error("Unknown constructor: "+e)}if("memberExpression"===r.type||"propertyAccess"===r.type)return await this.evaluateMethodCall(r,n,t);const i=r.name||r,s=this.expressionRegistry.get(i);if(s){const e=["first","last","random","at"],r=["closest","previous","next"].includes(i),o=e.includes(i),a=await Promise.all(n.map(e=>r&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:r&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:o&&e&&"selector"===e.type&&"string"==typeof e.value?this.evaluateSelector(e,t):this.evaluate(e,t)));return s.evaluate(t,...a)}const a=t.globals?.get(i)||window[i];if("function"==typeof a)return a(...await Promise.all(n.map(e=>this.evaluate(e,t))));throw Error("Unknown function: "+i)}async evaluateMethodCall(e,t,r){try{const n=await this.evaluate(e.object,r),o=this.unwrapSelectorResult(n);if(null==o)throw Error("Cannot call method on null or undefined");const i=e.property?.name||e.property?.value||e.property;if(!i||"string"!=typeof i)throw Error("Invalid method name: "+i);const s=o[i];if("function"!=typeof s)throw Error(`Property "${i}" is not a function on ${o.constructor?.name||typeof o}`);const a=await Promise.all(t.map(e=>this.evaluate(e,r)));return s.apply(o,a)}catch(e){if(e instanceof Error)throw e;throw Error("Failed to evaluate method call: "+e)}}async evaluateSelector(e,t){let r=e.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);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)}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):""}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=n.name||n.value||n;if("string"==typeof i){if(i.startsWith("@")){const e=i.substring(1);if(o&&"function"==typeof o.getAttribute)return o.getAttribute(e)}if(i.startsWith("computed-")){const e=i.substring(9);if(o&&"undefined"!=typeof window&&o instanceof Element)return window.getComputedStyle(o).getPropertyValue(e)}if(i.startsWith("style.")){const e=i.substring(6);if(o&&o.style)return o.style[e]}return o[i]}return o[i]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){let r=e.selector;if(r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim()),"id"===e.selectorType){const e=r.startsWith("#")?r.slice(1):r;return document.getElementById(e)}if("class"===e.selectorType){const e=r.replace(/:/g,"\\:"),t=document.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const n=document.querySelectorAll(r);return Array.from(n).filter(e=>e instanceof HTMLElement)}async evaluateIdSelector(e,t){const r=e.value.startsWith("#")?e.value.slice(1):e.value;return document.getElementById(r)}async evaluateQueryReference(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());try{return document.querySelectorAll(r)}catch{return document.createDocumentFragment().childNodes}}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=C(r)?k(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=C(o)?k(o,n):o[n],"function"==typeof e?e.bind(o):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const L={1:"one",2:"two",3:"three",4:"four",5:"five"};function I(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${o=t,L[o]??o+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var o;return null}function R(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function $(e,t,r){return I(e,1,t,r)??R(e,0,t,r)}function M(e,t){return I(e,2,t,"left, right")}function V(){return null}function D(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 _(e,t,r,n,o){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${o?` (${o})`:""}`:null}function B(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const P="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 q;function F(){return q({validate:e=>({success:!0,data:e})})}function U(e,t){if(P)return F();const r=q({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:B("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:B("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=t in n,i=r.validate(n[t]);if(!i.success)return{success:!1,error:B("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};if(!e&&void 0===i.data&&!r.t)return{success:!1,error:B("missing-argument",`Required field "${t}" is missing`,t)};void 0!==i.data&&(o[t]=i.data)}return{success:!0,data:o}}});return r.strict=()=>U(e,{strict:!0}),r}q=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 q(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:B("runtime-error",`String must be at least ${e} characters long`)}:n}};return q(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:B("runtime-error",`String must be at most ${e} characters long`)}:n}};return q(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 q(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){return this}),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 H=e=>q(function(e={}){return P?F():q({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:B("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:B("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:B("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:B("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:B("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{})),W=e=>q(function(e={}){return P?F():q({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:B("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:B("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:B("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{})),J=()=>q(P?F():q({validate:e=>"boolean"!=typeof e?{success:!1,error:B("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}})),z=e=>q(U(e)),Z=e=>q(function(e){return P?F():q({validate:t=>{if(!Array.isArray(t))return{success:!1,error:B("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:B("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:B("runtime-error",o.error.message,o.error.path?`${n}.${o.error.path}`:""+n)};r.push(o.data)}return{success:!0,data:r}}})}(e)),G=()=>q(F()),Y=()=>q(F()),X=()=>q(function(e,t="Custom validation failed"){return P?F():q({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:B("runtime-error",t)}})}(e=>void 0===e,"Expected undefined"));class K{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||x(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&&S(e)&&1===e.nodeType}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":S(e)?"object":typeof e}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):E(e)?e.split(""):null==e?[]:S(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(x(e)&&Number.isFinite(e))return e;if(E(e)){const t=Number(e);return Number.isFinite(t)?t:null}return A(e)?e?1:0:null}}class Q extends K{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=X(),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 ee extends K{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=X(),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 te extends K{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=X(),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 re=z({selector:H().min(1),single:J().optional().default(!1)});class ne extends K{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=re,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 Q,new ee,new te,new ne;const oe={name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:V},ie={name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:V},se={name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:V},ae={name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:V},ce={name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:V},le={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=>$(e,"querySelector","selector")},ue={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=>$(e,"querySelectorAll","selector")},fe={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=>$(e,"getElementById","ID")},de={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=>$(e,"getElementsByClassName","className")},me={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"}},pe={name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:V},ye={name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:V},he={name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:V},ve={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=>$(e,"elementWithSelector","selector")},ge={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=>_(e,1,2,"styleRef","property, optional element")??R(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},be={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.result&&(o=e.result),o){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(n)||void 0}},validate:e=>I(e,2,"possessiveStyleRef","possessor, property")??R(e,0,"possessiveStyleRef","possessor")??R(e,1,"possessiveStyleRef","property")},we={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.result&&(o=e.result),o){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(r)||void 0}},validate:e=>I(e,2,"ofStyleRef","property, reference")??R(e,0,"ofStyleRef","property")??R(e,1,"ofStyleRef","reference")},Ee={me:oe,you:ie,it:se,its:ae,result:ce,querySelector:le,querySelectorAll:ue,getElementById:fe,getElementsByClassName:de,closest:me,parent:pe,window:ye,document:he,elementWithSelector:ve,styleRef:ge,possessiveStyleRef:be,ofStyleRef:we};var xe=Object.freeze({__proto__:null,CSSSelectorExpression:ne,ItExpression:te,MeExpression:Q,YouExpression:ee,classExpression:de,closestExpression:me,createItExpression:function(){return new te},createMeExpression:function(){return new Q},createYouExpression:function(){return new ee},documentExpression:he,elementWithSelectorExpression:ve,idExpression:fe,itExpression:se,itsExpression:ae,meExpression:oe,ofStyleRefExpression:we,parentExpression:pe,possessiveStyleRefExpression:be,querySelectorAllExpression:ue,querySelectorExpression:le,referencesExpressions:Ee,resultExpression:ce,styleRefExpression:ge,windowExpression:ye,youExpression:ie});class Ae{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 Se=new class{constructor(){this.domQueryCache=new Ae(200,3e3),this.exprResultCache=new Ae(500,2e3),this.cssMatchCache=new Ae(100,5e3),this.formValueCache=new Ae(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)})})}};var Te,Oe;"undefined"!=typeof window&&setInterval(()=>{Se.cleanup()},1e4),function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(Te||(Te={})),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"}(Oe||(Oe={}));const Ce=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=Se.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 Ne(){Se.cleanup(),Ce.getMetrics().memoryUsage>52428800&&Ce.reset()}let ke=null;function je(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){const t=e.valueOf();if("number"==typeof t&&Number.isFinite(t))return t}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Le(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){ke&&clearInterval(ke),ke=setInterval(Ne,e)}();const Ie=z({left:G().describe("Left operand value"),right:G().describe("Right operand value")}).strict(),Re=z({operand:G().describe("Operand value to negate")}).strict();class $e extends K{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=Ie,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 Me extends K{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=Ie,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 Ve extends K{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=Re,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 De(){return new $e}function _e(){return new Me}function Be(){return new Ve}De(),_e(),Be();const Pe=Z([G(),G()]),qe=Z([G(),H()]),Fe={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return Le(this,e,[t,r],t==r,n)}catch(o){throw Le(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>M(e,"equals"),inputSchema:Pe,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"]}},Ue={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,r)=>t===r,validate:e=>M(e,"strictEquals")},He={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],evaluate:async(e,t,r)=>t!=r,validate:e=>M(e,"notEquals")},We={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,r)=>t!==r,validate:e=>M(e,"strictNotEquals")},Je={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,r)=>r>t,validate:e=>M(e,"lessThan")},ze={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],evaluate:async(e,t,r)=>r>=t,validate:e=>M(e,"lessThanOrEqual")},Ze={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,r)=>t>r,validate:e=>M(e,"greaterThan")},Ge={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],evaluate:async(e,t,r)=>t>=r,validate:e=>M(e,"greaterThanOrEqual")},Ye={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return Le(this,e,[t,r],t&&r,n)}catch(o){throw Le(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>M(e,"and"),inputSchema:Pe,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"]}},Xe={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,r)=>t||r,validate:e=>M(e,"or")},Ke={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>I(e,1,"not","operand")},Qe={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],evaluate:async(e,t)=>null==t||(E(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!S(t)||0!==Object.keys(t).length)),validate:e=>I(e,1,"isEmpty","value")},et={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],evaluate:async(e,t)=>null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!(E(t)||t instanceof Node||t instanceof Element||!S(t)||0!==Object.keys(t).length)),validate:e=>I(e,1,"no","value")},tt={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await Qe.evaluate(e,t),validate:e=>I(e,1,"isNotEmpty","value")},rt={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>null!=t,validate:e=>I(e,1,"exists","value")},nt={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>null==t,validate:e=>I(e,1,"doesNotExist","value")},ot={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){if(t&&r){if(1===t.nodeType&&1===r.nodeType)return t.contains(r);if(E(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&1===r.nodeType)return e.contains(r);if(e&&E(r)&&r.match(/^[.#][\w-]+$/)){const t=document.querySelector(r);return!!t&&e.contains(t)}}if(E(r)&&r.match(/^[.#][\w-]+$/)&&1===t.nodeType){const e=document.querySelector(r);return!!e&&t.contains(e)}}return E(t)&&E(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!S(t)||!E(r))&&r in t},validate:e=>I(e,2,"contains","container, value")},it={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,r)=>!await ot.evaluate(e,t,r),validate:e=>I(e,2,"doesNotContain","container, value")},st={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,r)=>!(!E(t)||!E(r))&&t.startsWith(r),validate:e=>I(e,2,"startsWith","str, prefix")},at={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,r)=>!(!E(t)||!E(r))&&t.endsWith(r),validate:e=>I(e,2,"endsWith","str, suffix")},ct={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){const n=Date.now();try{let o;if(t instanceof Element&&E(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 Se.matches(e,t)}(t,e)}catch(e){o=!1}else o=!1}else if(E(t)&&E(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 Le(this,e,[t,r],o,n)}catch(o){throw Le(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>I(e,2,"matches","element, selector"),inputSchema:qe,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"]}},lt={equals:Fe,strictEquals:Ue,notEquals:He,strictNotEquals:We,lessThan:Je,lessThanOrEqual:ze,greaterThan:Ze,greaterThanOrEqual:Ge,and:Ye,or:Xe,not:Ke,no:et,isEmpty:Qe,isNotEmpty:tt,exists:rt,doesNotExist:nt,contains:ot,doesNotContain:it,startsWith:st,endsWith:at,matches:ct};var ut=Object.freeze({__proto__:null,AndExpression:$e,NotExpression:Ve,OrExpression:Me,andExpression:Ye,containsExpression:ot,createAndExpression:De,createNotExpression:Be,createOrExpression:_e,doesNotContainExpression:it,doesNotExistExpression:nt,endsWithExpression:at,equalsExpression:Fe,existsExpression:rt,greaterThanExpression:Ze,greaterThanOrEqualExpression:Ge,isEmptyExpression:Qe,isNotEmptyExpression:tt,lessThanExpression:Je,lessThanOrEqualExpression:ze,logicalExpressions:lt,matchesExpression:ct,noExpression:et,notEqualsExpression:He,notExpression:Ke,orExpression:Xe,startsWithExpression:st,strictEqualsExpression:Ue,strictNotEqualsExpression:We});function ft(e,t,r,n,o="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:o,message:r,code:t,suggestions:n}}}function dt(e,t){return{success:!0,value:e,type:t}}function mt(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const pt={Array:(e,t)=>{try{return Array.isArray(e)?dt(e,"array"):e instanceof NodeList?dt(Array.from(e),"array"):dt(null==e?[]:[e],"array")}catch(e){return ft("Array","ARRAY_CONVERSION_FAILED",mt("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?dt("","string"):E(e)?dt(e,"string"):S(e)?dt(JSON.stringify(e),"string"):dt(e+"","string")}catch(e){return ft("String","STRING_CONVERSION_FAILED",mt("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(A(e))return dt(e,"boolean");if(null==e)return dt(!1,"boolean");if(E(e)){const t=e.toLowerCase().trim();return dt("false"!==t&&"0"!==t&&""!==t,"boolean")}return x(e)?dt(0!==e&&!isNaN(e),"boolean"):dt(!!e,"boolean")}catch(e){return ft("Boolean","BOOLEAN_CONVERSION_FAILED",mt("Failed to convert value to Boolean",e),["Use explicit true/false values","Check for unexpected data types"])}},Number:(e,t)=>{try{if(x(e))return dt(e,"number");if(null==e)return dt(0,"number");const t=Number(e);return isNaN(t)?ft("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):dt(t,"number")}catch(e){return ft("Number","NUMBER_CONVERSION_FAILED",mt("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=pt.Number(e,t);return r.success?dt(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=pt.Number(e,t);return r.success?dt(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return dt(e,"object");if(null==e)return dt(new Date(""),"object");if(E(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return dt(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?ft("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"):dt(t,"object")}catch(e){return ft("Date","DATE_CONVERSION_FAILED",mt("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return dt(JSON.stringify(e),"string")}catch(e){return ft("JSON","JSON_STRINGIFY_FAILED",mt("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(S(e))return dt(e,"object");if(E(e))try{return dt(JSON.parse(e),"object")}catch(e){return ft("Object","JSON_PARSE_FAILED",mt("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return dt({},"object")}catch(e){return ft("Object","OBJECT_CONVERSION_FAILED",mt("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 dt(function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=gt(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}(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=gt(t);void 0!==e&&(r[t.name]=e)}}),dt(r,"object")}return dt({},"object")}catch(e){return ft("FormValues","FORM_VALUES_EXTRACTION_FAILED",mt("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},yt=z({value:Y(),type:H().min(1)});class ht extends K{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=yt,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=pt.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=pt[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=pt[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=z({value:Y(),type:H().min(1)});function gt(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}new ht,new class extends K{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=E(o);break;case"number":a=x(o)&&!isNaN(o);break;case"boolean":a=A(o);break;case"object":a=S(o);break;case"array":a=Array.isArray(o);break;case"function":a=T(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||S(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 bt={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":E(e)?e:S(e)?JSON.stringify(e):e+"",Boolean:e=>{if(A(e))return e;if(null==e)return!1;if(E(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return x(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(x(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(x(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(!x(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=bt.Number(e);return Math.trunc(t)},Float:e=>{const t=bt.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if(E(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,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(S(e))return e;if(E(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{E(e)||(e=bt.String(e));const t=document.createElement("template");return t.innerHTML=e+"",t.content},HTML:e=>E(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:bt.String(e)).join(""):e instanceof Element?e.outerHTML:bt.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return wt(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=Et(e))}),r}return{}},"Values:Form":(e,t)=>{const r=bt.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=bt.Values(e,t);return JSON.stringify(r)}};function wt(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Et(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 Et(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 xt(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}const At={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}=xt(n);return bt.Number(r).toFixed(e||2)}let o=bt[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=bt[i],o)?o(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>I(e,2,"as","value, type")??R(e,1,"as","conversion type")},St={name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!E(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 E(r);case"number":return x(r)&&!isNaN(r);case"boolean":return A(r);case"object":return S(r);case"array":return Array.isArray(r);case"function":return T(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||S(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>I(e,2,"is","value, type")??R(e,1,"is","type")},Tt={name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>I(e,1,"async","expression")},Ot={as:At,is:St,async:Tt};var Ct=Object.freeze({__proto__:null,AsExpression:ht,asExpression:At,asyncExpression:Tt,conversionExpressions:Ot,createAsExpression:function(){return new ht},defaultConversions:bt,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:wt,getInputValue:Et,isExpression:St,parseFixedPrecision:xt});const Nt={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"},kt=z({collection:G().describe("Collection to operate on (array, NodeList, or string)")}).strict(),jt=z({collection:G().describe("Collection to access"),index:W().describe("Index position to access")}).strict(),Lt=z({collection:G().describe("Collection to select random item from")}).strict();class It extends K{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=kt,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:Nt[this.inferResultTypeLocal(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"])}}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":E(e)?"String":x(e)?"Number":A(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}}class Rt extends K{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=kt,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:Nt[this.inferResultTypeLocal(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"])}}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":E(e)?"String":x(e)?"Number":A(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}}function $t(){return new It}function Mt(){return new Rt}$t(),Mt(),new class extends K{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=jt,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:Nt[this.inferResultTypeLocal(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}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":E(e)?"String":x(e)?"Number":A(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends K{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=Lt,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:Nt[this.inferResultTypeLocal(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)}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":E(e)?"String":x(e)?"Number":A(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}};const Vt={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:E(r)?r.length>0?r[0]:null:S(r)&&"length"in r&&x(r.length)&&r.length>0?r[0]:null},validate:e=>D(e,1,"first","collection")},Dt={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 E(r)?r.length>0?r[r.length-1]:null:S(r)&&"length"in r&&x(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>D(e,1,"last","collection")},_t={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!x(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(E(i)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}if(S(i)&&"length"in i&&x(i.length)){const e=0>o?i.length+o:o;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>_(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)},Bt={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?qt(o,r):o.nextElementSibling:null},validate:e=>D(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")},Pt={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?Ft(o,r):o.previousElementSibling:null},validate:e=>D(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 qt(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?qt(n,t):null}function Ft(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?Ft(n,t):null}const Ut={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?Wt(i,r,s):null},validate:e=>_(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")},Ht={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?Jt(i,r,s):null},validate:e=>_(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 Wt(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=zt(e);for(const e of n)if(zt(e)>o)return e;return null}function Jt(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=zt(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(o>zt(t))return t}return null}function zt(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 Zt={first:Vt,last:Dt,at:_t,next:Bt,previous:Pt,nextWithin:Ut,previousWithin:Ht};var Gt=Object.freeze({__proto__:null,FirstExpression:It,LastExpression:Rt,atExpression:_t,createFirstExpression:$t,createLastExpression:Mt,findNextElementInDOM:qt,findNextElementWithinContainer:Wt,findPreviousElementInDOM:Ft,findPreviousElementWithinContainer:Jt,firstExpression:Vt,getElementPosition:zt,lastExpression:Dt,nextExpression:Bt,nextWithinExpression:Ut,positionalExpressions:Zt,previousExpression:Pt,previousWithinExpression:Ht});const Yt={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");return r instanceof Element?k(r,n):(S(r),r[n])}},validate:e=>I(e,2,"possessive","element, property")??R(e,1,"possessive","property name")},Xt={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");return e.me instanceof Element?k(e.me,r):(S(e.me),e.me[r])}},validate:e=>$(e,"my","property")},Kt={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;return n instanceof Element?k(n,r):(S(n),n[r])},validate:e=>$(e,"its","property")},Qt={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");return e.you instanceof Element?k(e.you,r):(S(e.you),e.you[r])}},validate:e=>$(e,"your","property")},er={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");return n instanceof Element?k(n,r):(S(n),n[r])}},validate:e=>I(e,2,"of","property, object")??R(e,0,"of","property name")},tr={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=>_(e,1,2,"attribute","attributeName, optional element")??R(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},rr={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=>_(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??R(e,0,"attributeWithValue","attribute name")??R(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},nr={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=>$(e,"classReference","className")},or={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=>$(e,"idReference","idValue")},ir={possessive:Yt,my:Xt,its:Kt,your:Qt,of:er,attribute:tr,attributeWithValue:rr,classReference:nr,idReference:or};var sr=Object.freeze({__proto__:null,attributeExpression:tr,attributeWithValueExpression:rr,classReferenceExpression:nr,getElementProperty:k,idReferenceExpression:or,isAriaAttribute:function(e){return e.startsWith("aria-")||"aria"===e},isDataAttribute:function(e){return e.startsWith("data-")||"data"===e},itsExpression:Kt,myExpression:Xt,ofExpression:er,possessiveExpression:Yt,propertiesExpressions:ir,yourExpression:Qt});const ar=z({value:H().describe("String literal value")}).strict(),cr=z({value:W().describe("Number literal value")}).strict(),lr=z({value:J().describe("Boolean literal value")}).strict(),ur=z({left:G().describe("Left operand"),right:G().describe("Right operand")}).strict();class fr extends K{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=ar,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 dr extends K{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?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?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 mr extends K{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=lr,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 pr extends K{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=ur,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=je(t.left,"left operand")+je(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 yr extends K{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=ur,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=ur.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if(E(e))return e;if(x(e))return""+e;if(A(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}class hr extends K{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=ur,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=je(t.left,"left operand")*je(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 fr}function gr(){return new dr}function br(){return new mr}function wr(){return new pr}function Er(){return new yr}function xr(){return new hr}const Ar={stringLiteral:vr(),numberLiteral:gr(),booleanLiteral:br(),addition:wr(),stringConcatenation:Er(),multiplication:xr()};var Sr=Object.freeze({__proto__:null,AdditionExpression:pr,BooleanLiteralExpression:mr,MultiplicationExpression:hr,NumberLiteralExpression:dr,StringConcatenationExpression:yr,StringLiteralExpression:fr,createAdditionExpression:wr,createBooleanLiteralExpression:br,createMultiplicationExpression:xr,createNumberLiteralExpression:gr,createStringConcatenationExpression:Er,createStringLiteralExpression:vr,specialExpressions:Ar});class Tr extends j{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Ee),this.registerCategory(lt),this.registerCategory(Ot),this.registerCategory(Zt),d("About to register properties expressions:",Object.keys(ir)),this.registerCategory(ir),d("Total expressions registered:",this.expressionRegistry.size),d('Registry has "possessive":',this.expressionRegistry.has("possessive")),d('Registry has "my":',this.expressionRegistry.has("my")),this.registerCategory(Ar)}}class Or{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 Cr{constructor(e,t,r){this.impl=e,this.expressionEvaluator=t??new Tr,this.hookRegistry=r??null}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(u(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void u(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const o=Or.toTyped(e);let i,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(u(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers?.when||r.modifiers?.where;if(t&&!await this.expressionEvaluator.evaluate(t,e))return void u(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:r.modifiers||{},commandName:r.commandName},this.expressionEvaluator,e)}else i=t;else u(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return u("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),u("CommandAdapterV2: Command result:",s),Object.assign(e,Or.fromTyped(o,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,s),s}catch(e){if(u(`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 Nr{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e,p("CommandRegistryV2: Hook registry set")}getHookRegistry(){return this.hookRegistry}register(e){const t=(e.name||e.metadata?.name).toLowerCase();p(`CommandRegistryV2: Registering command '${t}'`),this.implementations.set(t,e);const r=new Cr(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(t,r);const n=e.metadata?.aliases;if(n&&Array.isArray(n))for(const t of n){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,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 kr=null;function jr(){return kr||(kr=function(e){const t=e?.commands??new Nr,r=e?.eventSources??new g,n=e?.context??new b,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}()),kr}class Lr{constructor(e={}){this.contextCache=new WeakMap;const t=jr();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,p(`[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),p(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return p("[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 p(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return p(`[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 p(`[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,p("[RegistryIntegration] Destroyed")}}class Ir{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=h,this.hookRegistry=new t,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new y,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration&&(this.registryIntegration=new Lr("object"==typeof e.registryIntegration?e.registryIntegration:{}),p("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=>{for(const t of e)for(const e of t.removedNodes)if(e instanceof Element){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&p(`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(),p("RuntimeBase: Destroyed")}async execute(e,t){p(`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(!o(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}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(!o(n)){const e=n.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}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(!o(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}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(u(`RUNTIME BASE: Processing command '${i}'`),console.log("[RUNTIME DEBUG] executeCommand called with:",i),this.registry.has(i)){console.log("[RUNTIME DEBUG] Found command:",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 e instanceof Error&&(!0===e.isHalt||!0===e.isExit||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message)||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){if(e instanceof Error){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}return null}async processCommandWithResult(e,t){const{name:o,args:i,modifiers:s}=e,a=o.toLowerCase();if(u(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${o}. 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 r(await c.execute(t,{args:i||[],modifiers:s||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return n(t);throw console.error(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const i of e)if("command"===i.type){const e=await this.processCommandWithResult(i,t);if(!o(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),r(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(i,t);if(!o(e))return e;n=e.value}return r(n)}async evaluateExpression(e,t){const r=await this.expressionEvaluator.evaluate(e,t);return r&&"object"==typeof r&&r.command&&r.selector?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const i=await this.expressionEvaluator.evaluateWithResult(e,t);if(!o(i))return i;const s=i.value;if(s&&"object"==typeof s&&s.command&&s.selector){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return r(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return n(t);throw e}}return r(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(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}for(const e of o)try{r=await this.execute(e,t)}catch(e){if(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(e instanceof Error&&(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(e instanceof Error&&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){const r=e;if(r.isHalt||r.isExit)break;if(r.isReturn){if(void 0!==r.returnValue)return Object.assign(t,{it:r.returnValue,result:r.returnValue}),r.returnValue;break}if(r.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;this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:o,initBlock:i}),p(`RUNTIME BASE: Registered behavior '${r}'`)}async installBehaviorOnElement(e,t,r){p("BEHAVIOR: installBehaviorOnElement called: "+e);const n=this.behaviorRegistry.get(e);if(!n)throw Error(`Behavior "${e}" not found`);p("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){p("BEHAVIOR: Running init block for "+e);try{await this.execute(n.initBlock,i),p("BEHAVIOR: Init block completed for "+e)}catch(t){if(p(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&t.isHalt))throw t}}if(p(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers)for(const e of n.eventHandlers)await this.executeEventHandler(e,i);p("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];p(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let d=[],m=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)m=window;else if("document"===e||"the document"===e||"body"===e)m=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);p(`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 p(`BEHAVIOR: Target resolution: querying for '${i}'`),d=this.queryElements(i,t)}else d=t.me?[t.me]:[];if(0===d.length&&!m)return void p(`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 y=e.customEventSource;if(y&&this.registryIntegration){p(`BEHAVIOR: executeEventHandler - Using custom event source '${y}' 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);p(`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(y,{event:r,handler:e,target:i,selector:a},t);p(`BEHAVIOR: Subscribed to custom event source '${y}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${y}' subscription ${n.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${y}':`,e)}return}const h=async e=>{const r=e.l||0;if(r>=100)return;if(e.l=r+1,a&&e.target instanceof Element&&!e.target.matches(a)&&!e.target.closest(a))return;const n=new Map(t.locals),i={...t,locals:n,it:e,event:e};n.has("target")||i.locals.set("target",e.target);const c=this.enhanceContext(i);if(s&&s.length>0)for(const t of s)c.locals.set(t,e[t]||e.detail?.[t]||null);for(const e of o)try{const t=await this.execute(e,c);if(void 0!==t){let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult){void 0!==e&&Object.assign(c,{it:e,result:e});continue}}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)continue;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}Array.isArray(e)&&e.length>0&&(e=e[0]),Object.assign(c,{it:e,result:e})}}catch(e){const t=e;if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(c,{it:t.returnValue,result:t.returnValue});break}throw console.error("COMMAND FAILED:",e),e}};let v;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)}}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 g=u?.once?{once:!0}:void 0;if(m)for(const e of f)m.addEventListener(e,v,g),d.length>0?this.cleanupRegistry.registerListener(d[0],m,e,v):this.cleanupRegistry.registerGlobal(()=>m.removeEventListener(e,v),"listener",`Global ${e} listener`);else for(const e of d)for(const t of f)e.addEventListener(t,v,g),this.cleanupRegistry.registerListener(e,e,t,v)}setupMutationObserver(e,t,r,n){p(`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){f(`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){console.error("❌ Error executing mutation handler command:",e)}}});e.observe(o,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(o,e),p("RUNTIME BASE: MutationObserver attached to",o,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){p("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))),p(`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){f("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){console.error("❌ Error executing change handler command:",e)}}});n.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),p("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)return[];let n=e;return n.startsWith("<")&&n.endsWith("/>")&&(n=n.slice(1,-2).trim()),Array.from(r.querySelectorAll(n))}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||e&&"object"==typeof e&&e.style&&e.classList}}const Rr={core:["references","logical","special"],common:["properties","conversion"],optional:["positional"]};class $r extends j{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=Rr[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.u(e);this.loadPromises.set(e,t);try{await t,this.loadedCategories.add(e),m("✅ Loaded expression category: "+e)}finally{this.loadPromises.delete(e)}}async u(e){try{let t;switch(m("📦 Loading expression category: "+e),e){case"references":t=await Promise.resolve().then(function(){return xe});break;case"logical":t=await Promise.resolve().then(function(){return ut});break;case"special":t=await Promise.resolve().then(function(){return Sr});break;case"properties":t=await Promise.resolve().then(function(){return sr});break;case"conversion":t=await Promise.resolve().then(function(){return Ct});break;case"positional":t=await Promise.resolve().then(function(){return Gt});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),m(` ✓ 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 m("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)&&(m(`🔄 Auto-loading category for node type: ${e.type} → ${r}`),await this.loadCategory(r)),super.evaluate(e,t)}async warmupExpressions(e){m("🔥 Warming up expression categories: "+e.join(", ")),await Promise.all(e.map(e=>this.loadCategory(e)))}getLoadedCategories(){return Array.from(this.loadedCategories)}}function Mr(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,m=r.length-1;m>=0;m--){var p={};for(var y in n)p[y]="access"===y?{}:n[y];for(var y in n.access)p.access[y]=n.access[y];p.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var h=(0,r[m])("accessor"===c?{get:f.get,set:f.set}:f[l],p);if("accessor"===c){if(void 0===h)continue;if(null===h||"object"!=typeof h)throw new TypeError("Object expected");(a=s(h.get))&&(f.get=a),(a=s(h.set))&&(f.set=a),(a=s(h.init))&&o.unshift(a)}else(a=s(h))&&("field"===c?o.unshift(a):f[l]=a)}u&&Object.defineProperty(u,n.name,f),d=!0}function Vr(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 Dr(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 _r=Symbol("command:name"),Br=Symbol("command:category"),Pr=Symbol("command:metadata");function qr(e){return function(t,r){const n=t;n[_r]=e.name,n[Br]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Fr(e){return function(t,r){const n=t,o=n[Br];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"};n[Pr]=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 Ur(e){return()=>new e}function Hr(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function Wr(e,t){if(Hr(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 zr(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return zr(t.me)}if("it"===r){if(!Hr(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 zr(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(!Hr(o))throw Error("Element found but is not an HTMLElement: "+r);return o}throw Error("Invalid target type: "+typeof e)}function Jr(e,t){if(Array.isArray(e))return e.filter(Hr);if(e instanceof NodeList)return Array.from(e).filter(Hr);if(Hr(e))return[e];if(!e){const e=t.me;return e&&Hr(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&Hr(t.me)?[t.me]:[];if("it"===r)return Hr(t.it)?[t.it]:[];if("you"===r)return t.you&&Hr(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(Hr)}}return[]}function zr(e){if(Hr(e))return e;throw Error("Value is not an HTMLElement")}function Zr(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!Hr(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(!Hr(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(!Hr(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const Gr=["on","from","to","in","with","at"];async function Yr(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||!Gr.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(!Hr(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(Hr(o))a.push(o);else if(o instanceof NodeList){const e=Array.from(o).filter(Hr);a.push(...e)}else if(Array.isArray(o)){const e=o.filter(Hr);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(Hr);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(!Hr(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}class Xr{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await Yr(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=>Hr(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 Kr=(()=>{let e,t,r=[Fr({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),qr({name:"hide",category:"dom"})],n=[],o=Xr;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=>Hr(e))}},Dr(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const Qr=Ur(Kr);let en=(()=>{let e,t,r=[Fr({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),qr({name:"show",category:"dom"})],n=[],o=Xr;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=>Hr(e))&&"string"==typeof t.defaultDisplay}},Dr(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const tn=Ur(en);function rn(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function nn(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 on(e,t){for(const r of e)t(r);return e}function sn(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function an(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 cn(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&&un(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&&un(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&un(r)?[r]:[]}function ln(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function un(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!ln(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function fn(e,t){return e.map(e=>{if(ln(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 mn(e,t,r){e.style.setProperty(t,r)}const pn=["dialog","details","summary","select"];function yn(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 hn(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=yn(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=yn(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:yn(e),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1}}class vn{async resolveTargets(e,t,r,n){return Yr(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return hn(e,t,r)}parseClassNames(e){return cn(e)}isAttribute(e){return rn(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=>Hr(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 gn=(()=>{let e,t,r=[Fr({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"]}),qr({name:"add",category:"dom"})],n=[],o=vn;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=nn(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=fn(e.classes,t);r.length>0&&sn(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":r=e.name,n=e.value,on(e.targets,e=>{e.setAttribute(r,n)});break;case"styles":!function(e,t){sn(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}},Dr(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const bn=Ur(gn);function wn(e){return!!e.parentNode&&(e.remove(),!0)}let En=(()=>{let e,t,r=[Fr({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"]}),qr({name:"remove",category:"dom"})],n=[],o=vn;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(Hr(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&Hr(n[0]))return{type:"element",targets:n.filter(e=>Hr(e))};if("string"==typeof n){const o=n.trim();if(this.isAttribute(o))return{type:"attribute",name:nn(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=fn(e.classes,t);r.length>0&&sn(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,on(e.targets,e=>{e.removeAttribute(r)});break;case"styles":!function(e,t){sn(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}},Dr(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const xn=Ur(En);function An(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 Sn(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=An(e);return r?r.milliseconds:t}return t}function Tn(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=An(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function On(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 Cn(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 Nn(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function kn(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&an(e,r)}}function jn(e,t,r,n){const o=kn(e,t,r),i=setTimeout(o,n);return()=>{clearTimeout(i)}}function Ln(e,t,r,n){const o=kn(e,t,r),i=()=>{o(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function In(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]}function Rn(e,t,r){if(t.startsWith("@"))return void e.setAttribute(t.substring(1),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 $n(e){return null==e||""===e}const Mn=/^the\s+(.+?)\s+of\s+(.+)$/i,Vn=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 Dn(e){return"string"==typeof e&&Mn.test(e)}function _n(e,t){const r=e.match(Mn);if(!r)return null;try{return{element:Wr(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function Bn(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]),Hr(o)?{element:o,property:n}:null}(e,t,r);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&"string"==typeof e.property}(e))return async function(e,t,r){const n=e.property;if(!n)return null;let o=await t.evaluate(e.object,r);return Array.isArray(o)&&(o=o[0]),Hr(o)?{element:o,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type){const e=n.object,o=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!Hr(i))return null;const s=o?.name||o?.value;return s?{element:i,property:s}:null}return null}function Pn(e,t){const{element:r,property:n}=e;n.startsWith("*")?mn(r,n.substring(1),t+""):Rn(r,n,t)}async function qn(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?Sn(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 Fn(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(Hr(e)||Array.isArray(e)&&e.every(e=>Hr(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 Un=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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 qn(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 Yr(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 Bn(n,t,r);if(i)return{type:"property",target:i};const{duration:s,untilEvent:a}=await qn(e.modifiers,t,r),{value:c}=await hn(n,t,r);if(Dn(c)){const e=_n(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=Fn(c,n),f={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:o}=nn(u);return{type:"attribute",name:n,value:o,targets:await Yr(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 Yr(e.args.slice(1),t,r,"toggle",f,e.modifiers)}}case"element":{let o;if(Hr(c))o=[c];else if(Array.isArray(c)&&c.every(e=>Hr(e)))o=c;else if(u){const e=document.querySelectorAll(u);o=Array.from(e).filter(e=>Hr(e))}else o=await Yr([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:Nn(o)}:"select"===i?{type:"select",targets:o}:{type:"classes",classes:cn(u),targets:o,duration:s,untilEvent:a}}default:{const n=cn(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Yr(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=fn(e.classes,t);if(0===r.length)return[...e.targets];if(sn(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&jn(t,"class",r[0],e.duration),e.untilEvent&&Ln(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,on(e.targets,e=>{an(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&jn(t,"attribute",e.name,e.duration),e.untilEvent&&Ln(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return on(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)):In(t,r)}(e),r=e.property;if("boolean"==typeof t||Vn.has(r)||Vn.has(r.toLowerCase())){const r=!t;return Pn(e,r),r}if("number"==typeof t){const r=0===t?1:0;return Pn(e,r),r}if("string"==typeof t){const n="__ht_"+r,o=e.element[n];return""===t&&void 0!==o?(Pn(e,o),o):(e.element[n]=t,Pn(e,""),"")}Pn(e,!t)}(e.target),[e.target.element];case"dialog":return on(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 on(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return on(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&&jn(t,"class",e.classA,e.duration),e.untilEvent&&Ln(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},Dr(t,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());const Hn=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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,m=null;if(c){const e=n(c),o=await Bn(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?m=e.value:"identifier"===e?.type&&(m=e.name),m&&n?.name)f=n.name;else{const e=await t.evaluate(c,r);"string"==typeof e&&(m=e)}}else if("identifier"===e&&"me"===c.name)m=null;else if("selector"===e||"cssSelector"===e)m=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&Dn(e)){const t=_n(e,r);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?m=e:d=e+""}else if("identifier"===e){const e=c.name;this.looksLikeCss(e)?m=e:d=e}else{const e=await t.evaluate(c,r);"string"==typeof e&&(this.looksLikeCss(e)?m=e:d=e)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(m,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,[];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||!Hr(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>Hr(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return Hr(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(Hr(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 Hr(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}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}},Dr(t,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());function Wn(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 Jn(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 zn(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 Zn(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Jn(e,t)}const Gn=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(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&&zn(o,i,t),i}},Dr(t,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());function Yn(e,t,r){return e?new Promise(r=>{const n=Kn(()=>{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 Xn(e){return new Promise(t=>setTimeout(t,e))}function Kn(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}const Qn=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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 Xn(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,o=(await Yn(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:Tn(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:Tn(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?Xn(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Yn(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},Dr(t,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());const eo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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};if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let l;i.timeout&&(l=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.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{l&&clearTimeout(l),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(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":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){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();default:return 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&&Hr(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},Dr(t,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),to=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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 Bn(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){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(Hr(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(Dn(s)){const n=_n(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&&rn(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=Zr(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:o,property:n[2],value:i}}}if(Hr(s))return{type:"property",element:s,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(s)&&s.length>0&&Hr(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 Rn(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return mn(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))Rn(t,r,n);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,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=Zr(e,n),s=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.name,value:s}}}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 Wr(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return Jr(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=Wr(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&&Hr(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&Hr(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&Hr(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}}},Dr(t,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());let ro=(()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?Wn(r.getAttribute(t)):Wn(r[t]):Wn(r.value||r.textContent)}return"string"==typeof e?"global"===r?Wn(Jn(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],o=Zn(r[0],t);return o?Wn(o[n]):0}(e,n):Wn("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:Jn(e,n)):Wn(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(Hr(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 zn(e,n,o,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),o=n[1],i=Zn(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);zn(e,n,o)}}(r,n,o,c,t),Object.assign(t,{it:c}),c}},Dr(t,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})();const no=Ur(ro),oo=Ur(ro),io=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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)}},Dr(t,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());function so(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 ao=(()=>{let e,t,r=[Fr({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"]}),qr({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))a=s.name,s.args?.length&&(c=await this.parseEventDetail(s.args,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(Hr(e))o.push(e);else if(e instanceof NodeList)o.push(...Array.from(e).filter(Hr));else if(Array.isArray(e))o.push(...e.filter(Hr));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(Hr));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)return await t.evaluate(e[0],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()]=so(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}},Dr(t,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})();const co=Ur(ao),lo=Ur(ao),uo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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&&Hr(t.me))return t.me;if("it"===r&&Hr(t.it))return t.it;if("you"===r&&Hr(t.you))return t.you;const n=Jn(r,t);if(Hr(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)}}},Dr(t,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());function fo(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=Jn(e,t);return void 0!==r?!!r:!!e}return!!e}const mo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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=fo(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}},Dr(t,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),po=mo,yo=mo;let ho=(()=>{let e,t,r=[Fr({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"]}),qr({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,fo,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,fo,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}},Dr(t,"RepeatCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})();const vo=Ur(ho);class go{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 bo=(()=>{let e,t,r=[Fr({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"]}),qr({name:"break",category:"control-flow"})],n=[],o=go;return t=class extends o{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},Dr(t,"BreakCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const wo=Ur(bo);let Eo=(()=>{let e,t,r=[Fr({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"]}),qr({name:"continue",category:"control-flow"})],n=[],o=go;return t=class extends o{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},Dr(t,"ContinueCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const xo=Ur(Eo),Ao=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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}},Dr(t,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),So=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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}},Dr(t,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());let To=(()=>{let e,t,r=[Fr({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"]}),qr({name:"exit",category:"control-flow"})],n=[],o=go;return t=class extends o{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},Dr(t,"ExitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})(),t})();const Oo=Ur(To),Co=new Map,No=Ur((()=>{let e,t,r=[Fr({description:"Create two-way data binding between variables and DOM elements",syntax:["bind :variable to <element>.<property>","bind :variable from <element>.<property>","bind :variable to <element>.<property> bidirectional"],examples:["bind :username to my.value","bind :count from #display.textContent","bind :message to #input.value bidirectional"],sideEffects:["data-binding","event-listeners","dom-observation"]}),qr({name:"bind",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args||1>e.args.length)throw Error("bind command requires a variable name");const n=await t.evaluate(e.args[0],r),o="string"==typeof n&&n.startsWith(":")?n.substring(1):n+"";let i,s="to";e.modifiers?.bidirectional||e.bidirectional?s="bidirectional":e.modifiers?.to||"to"===e.direction?s="to":(e.modifiers?.from||"from"===e.direction)&&(s="from");let a="value";if(e.modifiers?.to||e.modifiers?.from){const n=e.modifiers.to||e.modifiers.from,o=await t.evaluate(n,r);if(Hr(o))i=o;else if("string"==typeof o){const e=o.split(".");e.length>1?(i=e[0],a=e.slice(1).join(".")):i=o}else i=o}else{if(!e.target)throw Error("bind command requires a target element (to/from)");i=e.target,a=e.property||"value"}const c=await this.resolveElement(i,t,r);if(!c)throw Error("Cannot resolve target element: "+i);return{variable:o,target:c,property:a,direction:s}}async execute(e,t){const{variable:r,target:n,property:o,direction:i}=e,s=this.createBinding(r,n,o,i,t);return this.dispatchEvent(t,"bind:created",{variable:r,element:n,property:o,direction:i,bindingId:s}),{success:!0,variable:r,element:n,property:o,direction:i,bindingId:s}}createBinding(e,t,r,n,o){const i=`bind-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s=[];if("to"===n||"bidirectional"===n){const i=()=>{const n=In(t,r);o.locals.set(e,n);const i=new CustomEvent(`variable:${e}:change`,{detail:{value:n,source:"variable",originElement:t},bubbles:!0});t.dispatchEvent(i)},a=this.getEventTypeForProperty(r);t.addEventListener(a,i),s.push(()=>t.removeEventListener(a,i)),"to"===n&&i()}if("from"===n||"bidirectional"===n){const n=n=>{const i=n,s=i.detail?.value??o.locals.get(e),a=i.detail?.originElement;a&&a===t||Rn(t,r,s)};if(t.addEventListener(`variable:${e}:change`,n),s.push(()=>t.removeEventListener(`variable:${e}:change`,n)),r.startsWith("@")||"textContent"===r||"innerHTML"===r){const n=new MutationObserver(()=>{const n=o.locals.get(e);Rn(t,r,n)});n.observe(t,{attributes:!0,childList:!0,characterData:!0}),s.push(()=>n.disconnect())}const i=o.locals.get(e);void 0!==i&&Rn(t,r,i)}return Co.set(i,{id:i,variable:e,element:t,property:r,direction:n,cleanup:()=>s.forEach(e=>e())}),i}async resolveElement(e,t,r){if(Hr(e))return e;if(e&&"object"==typeof e&&e.type&&(e=await t.evaluate(e,r)),"string"==typeof e){if(["me","my","it","its","you","your"].includes(e.toLowerCase()))try{return Zr(e,r)}catch{return null}if("undefined"!=typeof document)try{return document.querySelector(e)}catch{return null}}return null}getEventTypeForProperty(e){return{value:"input",checked:"change",textContent:"input",innerHTML:"input"}[e]||"change"}dispatchEvent(e,t,r){if(Hr(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Dr(t,"BindCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());let ko=(()=>{let e,t,r=[Fr({description:"Evaluate an expression and store the result in the it variable",syntax:["call <expression>","get <expression>"],examples:["call myFunction()","get user.name",'call fetch("/api/data")'],sideEffects:["function-execution","context-mutation"]}),qr({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],alias:e.alias||"call"})}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}}},Dr(t,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})();(()=>{let e,t,r=[Fr({description:"Alias for call - evaluate an expression and store the result in the it variable",syntax:["get <expression>"],examples:["get user.profile","get document.title"],sideEffects:["function-execution","context-mutation"]}),qr({name:"get",category:"execution"})],n=[],o=ko;t=class extends o{},Dr(t,"GetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;Mr(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}),Vr(t,n)})()})();const jo=Ur(ko),Lo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(e))return e.innerHTML+=o,{result:e,targetType:"element",target:e}}const e=Jn(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 zn(n,i,t),{result:i,targetType:"variable",target:n}}return zn(n,o,t),{result:o,targetType:"variable",target:n}}if(Array.isArray(n))return n.push(r),{result:n,targetType:"array"};if(Hr(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)}}},Dr(t,"AppendCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),Io=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(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=Wr(n,t),c=Sn(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+"",m=!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),m=!0}a.style.setProperty(r,d);const p=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=Kn(()=>{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,m&&a.style.removeProperty(r),Object.assign(t,{it:a}),{element:a,property:r,fromValue:l,toValue:d,duration:c,completed:p.completed}}},Dr(t,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),Ro=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(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(Hr(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=Wr(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"}}},Dr(t,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),$o=Ur((()=>{let e,t,r=[Fr({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),qr({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);(Hr(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=Wr(r,t),i=Sn(n,5e3),s=Date.now(),a=getComputedStyle(o),c=On(a.transitionDuration),l=On(a.transitionDelay),u=On(a.animationDuration),f=On(a.animationDelay),d=Cn(c,l),m=Cn(u,f),p=Math.max(d,m),y=await(h=o,v=p,g=i,v>0?new Promise(e=>{const t=e=>{e.target===h&&n({completed:!0,type:"transition"})},r=e=>{e.target===h&&n({completed:!0,type:"animation"})},n=Kn(()=>{h.removeEventListener("transitionend",t),h.removeEventListener("animationend",r),clearTimeout(o),clearTimeout(i)},e);h.addEventListener("transitionend",t),h.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 h,v,g;const b=Date.now()-s;return Object.assign(t,{it:o}),{element:o,settled:y.completed,timeout:i,duration:b}}},Dr(t,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),Mo=Ur((()=>{let e,t,r=[Fr({description:"Save and restore values from browser storage with TTL support",syntax:["persist <value> to <storage> as <key>","restore <key> from <storage>","remove <key> from <storage>"],examples:['persist myValue to local as "username"','persist formData to session as "draft"','restore "username" from local'],sideEffects:["storage","data-mutation"]}),qr({name:"persist",category:"data"})],n=[];return t=class{async parseInput(e,t,r){let n,o,i,s,a="save";if(e.modifiers?.from)a="restore",n=await t.evaluate(e.args[0],r)+"",i=await t.evaluate(e.modifiers.from,r)+"";else{if(a="save",o=await t.evaluate(e.args[0],r),e.modifiers?.to&&(i=await t.evaluate(e.modifiers.to,r)+""),!e.modifiers?.as)throw Error('persist command requires "as <key>" modifier');n=await t.evaluate(e.modifiers.as,r)+"",e.modifiers?.ttl&&(s=Number(await t.evaluate(e.modifiers.ttl,r)))}return{key:n,value:o,storage:i||"local",ttl:s,operation:a}}async execute(e,t){const{key:r,value:n,storage:o="local",ttl:i,operation:s="save"}=e;if(!r||"string"!=typeof r||""===r.trim())throw Error("persist command requires a valid storage key");const a=this.getStorage(o);if(!a)throw Error(`Storage not available: ${o}Storage`);switch(s){case"save":return await this.saveValue(r,n,a,o,i,t);case"restore":return await this.restoreValue(r,a,o,t);case"remove":return await this.removeValue(r,a,o,t);default:throw Error("Unknown persist operation: "+s)}}getStorage(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch(t){return console.warn(`Storage not available: ${e}Storage`,t),null}}async saveValue(e,t,r,n,o,i){const s=Date.now(),a={value:t,timestamp:s,...void 0!==o&&{ttl:o}};try{const c=JSON.stringify(a);return r.setItem(e,c),this.dispatchEvent(i,"persist:save",{key:e,value:t,storage:n,timestamp:s,ttl:o}),{success:!0,operation:"save",key:e,value:t,storage:n,timestamp:s}}catch(t){throw this.dispatchEvent(i,"persist:error",{key:e,operation:"save",error:t instanceof Error?t.message:"Unknown error"}),Error("Failed to persist value: "+(t instanceof Error?t.message:"Unknown error"))}}async restoreValue(e,t,r,n){try{const o=t.getItem(e);if(null===o)return this.dispatchEvent(n,"persist:notfound",{key:e}),{success:!1,operation:"restore",key:e,value:null,storage:r};const i=JSON.parse(o),{value:s,timestamp:a,ttl:c}=i,l=Date.now();return void 0!==c&&l-a>c?(t.removeItem(e),this.dispatchEvent(n,"persist:expired",{key:e,timestamp:a,ttl:c}),{success:!1,operation:"restore",key:e,value:null,storage:r,expired:!0}):(this.dispatchEvent(n,"persist:restore",{key:e,value:s,storage:r}),Object.assign(n,{it:s}),{success:!0,operation:"restore",key:e,value:s,storage:r,timestamp:a})}catch(t){throw this.dispatchEvent(n,"persist:error",{key:e,operation:"restore",error:t instanceof Error?t.message:"Unknown error"}),Error("Failed to restore value: "+(t instanceof Error?t.message:"Unknown error"))}}async removeValue(e,t,r,n){try{return t.removeItem(e),this.dispatchEvent(n,"persist:remove",{key:e,storage:r}),{success:!0,operation:"remove",key:e,storage:r}}catch(t){throw this.dispatchEvent(n,"persist:error",{key:e,operation:"remove",error:t instanceof Error?t.message:"Unknown error"}),Error("Failed to remove value: "+(t instanceof Error?t.message:"Unknown error"))}}dispatchEvent(e,t,r){if(Hr(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Dr(t,"PersistCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),Vo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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},{})}}},Dr(t,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),Do=Ur((()=>{let e,t,r=[Fr({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),qr({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"}},Dr(t,"AsyncCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),_o=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(r))return this.defaultElementValue(t,r,n);throw Error("Invalid target type: "+typeof r)}defaultVariable(e,t,r){const n=Jn(t,e);return void 0!==n?{target:t,value:r,wasSet:!1,existingValue:n,targetType:"variable"}:(zn(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=Zr(t,e),i=In(o,r),s=`${t} ${r}`;return $n(i)?(Rn(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 $n(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"}}},Dr(t,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());class Bo{constructor(){this.name="pseudo-command"}get metadata(){return Bo.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 Po(){return new Bo}Bo.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 qo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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=Jr(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")}},Dr(t,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());let Fo=(()=>{let e,t,r=[Fr({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"]}),qr({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(Hr(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&Hr(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(Hr(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Dr(t,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})();const Uo=Ur(Fo),Ho=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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}}},Dr(t,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})()),Wo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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}},Dr(t,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());const Jo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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":Hr(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(Hr(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+""}},Dr(t,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());class zo{constructor(){this.name="install"}get metadata(){return zo.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(Hr(e))return[e];throw Error('No target specified and "me" is not available in context')}if(Hr(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>Hr(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(Hr(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=>Hr(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=>Hr(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(Hr(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 Zo(){return new zo}zo.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 Go=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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=Wr(e.source,t),n=Wr(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+"")}},Dr(t,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(t,n)})(),t})());class Yo{constructor(){this.name="render"}get metadata(){return Yo.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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}function Xo(){return new Yo}Yo.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 Ko extends Ir{constructor(e={}){const t=e.registry||new Nr;let r;e.registry||(t.register(Qr()),t.register(tn()),t.register(bn()),t.register(xn()),t.register(Un()),t.register(Hn()),t.register(Gn()),t.register(Qn()),t.register(eo()),t.register(to()),t.register(no()),t.register(oo()),t.register(io()),t.register(co()),t.register(lo()),t.register(uo()),t.register(po()),t.register(vo()),t.register(wo()),t.register(xo()),t.register(Ao()),t.register(So()),t.register(Oo()),t.register(No()),t.register(jo()),t.register(Lo()),t.register(Io()),t.register(Ro()),t.register($o()),t.register(Mo()),t.register(Vo()),t.register(Do()),t.register(yo()),t.register(_o()),t.register(Po()),t.register(qo()),t.register(Uo()),t.register(Ho()),t.register(Wo()),t.register(Jo()),t.register(Zo()),t.register(Go()),t.register(Xo()),console.log("RuntimeExperimental: Registered 43 V2 commands (Phase 6 COMPLETE - All commands migrated)")),r=e.expressionEvaluator?e.expressionEvaluator:e.lazyLoad?new $r({preload:e.expressionPreload||"core"}):new Tr;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 Qo=Ur((()=>{let e,t,r=[Fr({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"]}),qr({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}},Dr(t,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Mr(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}),Vr(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="lokascript-multilingual.js"><\/script>')}const ti=function(e,t={}){const r=new Nr;for(const t of e)r.register(t);return new Ko({...t,registry:r})}([Qr(),tn(),bn(),xn(),Un(),Hn(),Gn(),Qn(),eo(),to(),Qo(),no(),oo(),No(),_o(),Mo(),co(),lo(),uo(),po(),vo(),wo(),xo(),Ao(),So(),Oo(),yo(),Wo(),jo(),Po(),Lo(),Io(),Ro(),$o(),Go(),Vo(),Do(),io(),qo(),Uo(),Ho(),Jo(),Zo(),Xo()],{expressionPreload:"all"}),ri={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=function(e){if(!e)return v();if(e.locals instanceof Map&&e.globals instanceof Map&&e.flags)return e;const t=v(e.me instanceof Element?e.me:null);return void 0!==e.it&&Object.assign(t,{it:e.it}),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&Object.assign(t,{result:e.result}),void 0!==e.event&&Object.assign(t,{event:e.event}),t}(r);return ti.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:v,runtime:ti,version:"1.0.0-multilingual",commands:["hide","show","add","remove","toggle","put","make","wait","fetch","set","get","increment","decrement","bind","default","persist","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:["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],bundleType:"multilingual"};return"undefined"!=typeof window&&(window.hyperfixi=ri),e.default=ri,e.hyperfixi=ri,Object.defineProperty(e,"m",{value:!0}),e}({});
1
+ var _lokascriptMultilingualInternal=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{ok:!0,value:e}}function n(e){return{ok:!1,error:e}}function o(e){return!0===e.ok}const i=function(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),s=i,a=i,c=i,l=i,u=i,f=(...e)=>{s&&console.log("🔧",...e)},d=(...e)=>{a&&console.log("🎯",...e)},m=(...e)=>{c&&console.log("📝",...e)},p=(...e)=>{l&&console.log("🔍",...e)},y=(...e)=>{l&&console.log("🔍",...e)},h=(...e)=>{u&&console.log("🚀",...e)};class v{constructor(e){this.elementCleanups=new WeakMap,this.trackedElements=new Set,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&&h(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect(),this.debugMode&&h("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t),this.debugMode&&h("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t),this.debugMode&&h("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&&h("CleanupRegistry: Registered global cleanup: "+(r||t))}addCleanup(e,t){const r=this.elementCleanups.get(e)||[];r.push(t),this.elementCleanups.set(e,r),this.trackedElements.add(e),this.debugMode&&h(`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&&h("CleanupRegistry: Error during cleanup:",e)}return this.elementCleanups.delete(e),this.trackedElements.delete(e),this.debugMode&&h(`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&&h("CleanupRegistry: Error during global cleanup:",e)}return this.globalCleanups=[],this.debugMode&&h(`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.trackedElements){const s=this.elementCleanups.get(i);if(s)for(const i of s)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":o++}}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.trackedElements.size,listeners:e,observers:t,intervals:r,timeouts:n,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&&Object.assign(t,{it:e.it}),void 0!==e.you&&(t.you=e.you),void 0!==e.result&&Object.assign(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 O(e){const t=A.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function C(e){const t=A.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function N(e){const t=A.get("Function");return t?t.isType(e):"function"==typeof e}function k(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}function j(e){return e instanceof Element}const L={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=>k(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=>k(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,hidden:e=>function(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}(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};function I(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}const r=L[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return function(e,t){return e.getAttribute(t)}(e,t);const n=e[t];return N(n)?n.bind(e):n}class R{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 y("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||e.content||"";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);default:throw Error("Unsupported AST node type for evaluation: "+e.type)}}async evaluateWithResult(e,t){try{return r(await this.evaluate(e,t))}catch(e){if(e instanceof Error){const t=e;if(t.isHalt||"HALT_EXECUTION"===t.message)return n({type:"halt"});if(t.isExit||"EXIT_COMMAND"===t.message)return n({type:"exit",returnValue:t.returnValue});if(t.isBreak)return n({type:"break"});if(t.isContinue)return n({type:"continue"});if(t.isReturn)return n({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){let r=e.value||"";y("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 this.resolveTemplateVariable(i,t);y(`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);const n=r.indexOf("}",e);if(-1===n)throw Error("Unterminated template expression in: "+r);const o=r.slice(e+2,n);let i;y("TEMPLATE: Evaluating expression:",o);const c=o.trim();t.locals.has(c)?(i=t.locals.get(c),y(`TEMPLATE: Found in locals: ${c} =`,i)):t.variables&&t.variables.has(c)?(i=t.variables.get(c),y(`TEMPLATE: Found in variables: ${c} =`,i)):t.globals&&t.globals.has(c)?(i=t.globals.get(c),y(`TEMPLATE: Found in globals: ${c} =`,i)):(i=await this.evaluateSimpleExpression(o,t),y(`TEMPLATE: Evaluated expression "${o}" =`,i)),s+=i+"",a=n+1}return s}async resolveTemplateVariable(e,t){if(e.includes(".")){const r=e.split(".");let n=this.lookupTemplateVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.lookupTemplateVariable(e,t)}lookupTemplateVariable(e,t){return 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:"it"===e?t.it:"result"===e?t.result:void 0}async evaluateSimpleExpression(e,t){y("EVAL: Evaluating expression:",e);const r=e.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);if(r){const[,e,n,o]=r;y("EVAL: Parsed ternary:",{conditionExpr:e,trueExpr:n,falseExpr:o});const i=await this.resolveValue(e.trim(),t);if(y("EVAL: Ternary condition value:",i),i){const e=await this.resolveValue(n.trim(),t);return y("EVAL: Ternary returned true branch:",e),e}{const e=await this.resolveValue(o.trim(),t);return y("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;y("EVAL: Parsed arithmetic:",{left:e,operator:r,right:o});const i=await this.resolveValue(e.trim(),t),s=await this.resolveValue(o.trim(),t);y("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 y("EVAL: Arithmetic result:",e),e}}const o=await this.resolveValue(e.trim(),t);return y("EVAL: Fallback result:",o),o}async resolveValue(e,t){if(y(`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 y(`RESOLVE: Found '${e}' in locals:`,r),r}if(t.variables&&t.variables.has(e)){const r=t.variables.get(e);return y(`RESOLVE: Found '${e}' in variables:`,r),r}if(t.globals&&t.globals.has(e)){const r=t.globals.get(e);return y(`RESOLVE: Found '${e}' in globals:`,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.variables&&t.variables.has(n)?o=t.variables.get(n):t.globals&&t.globals.has(n)&&(o=t.globals.get(n)),null!=o){for(let e=1;r.length>e;e++){if(null==o)return void y(`RESOLVE: Property access failed at '${r[e-1]}'`);o=o[r[e]]}return y(`RESOLVE: Property access '${e}' =`,o),o}}return e}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;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 y("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=n.name||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)];{i=this.unwrapSelectorResult(i);const e=n.name||n;if("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.getAttribute(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}}async evaluateBinaryExpression(e,t){const{operator:r,left:n,right:o}=e;if("in"===r&&"selector"===n.type){let e=n.value;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const r=this.unwrapSelectorResult(await this.evaluate(o,t));if(!r||"function"!=typeof r.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof r})`);const i=r.querySelectorAll(e);return Array.from(i)}if("in"===r&&"queryReference"===n.type){let e=n.selector;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const r=this.unwrapSelectorResult(await this.evaluate(o,t));if(!r||"function"!=typeof r.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof r})`);const i=r.querySelectorAll(e);return Array.from(i)}if("in"===r){let e=null,r=null;if("positionalExpression"===n.type){e=n.operator;const o=n.argument;"cssSelector"===o?.type?r=o.selector:"selector"===o?.type?r=o.value:"classSelector"===o?.type?r="."+o.className:"idSelector"===o?.type?r="#"+o.id:o&&(r=await this.evaluate(o,t)+"")}else if("memberExpression"!==n.type||"identifier"!==n.object?.type||"first"!==n.object.name&&"last"!==n.object.name){if("callExpression"===n.type&&"identifier"===n.callee?.type&&("first"===n.callee.name||"last"===n.callee.name)){e=n.callee.name;const o=n.arguments?.[0];"selector"===o?.type?r=o.value:"cssSelector"===o?.type?r=o.selector:"classSelector"===o?.type?r="."+o.className:"idSelector"===o?.type?r="#"+o.id:o&&(r=await this.evaluate(o,t)+"")}}else e=n.object.name,"identifier"===n.property?.type&&n.property.name&&(r="."+n.property.name);if(e&&r){const n=this.unwrapSelectorResult(await this.evaluate(o,t));if(!n||"function"!=typeof n.querySelectorAll)return;const i=n.querySelectorAll(r),s=Array.from(i);return"first"===e?s.length>0?s[0]:void 0:"last"===e?s.length>0?s[s.length-1]:void 0:s}}if("matches"===r&&("selector"===o.type||"cssSelector"===o.type||"classSelector"===o.type)){const e=await this.evaluate(n,t),r=o.value||o.selector;if(e&&"function"==typeof e.matches)try{return e.matches(r)}catch{return!1}return!1}const i=await this.evaluate(n,t),s=await this.evaluate(o,t);if("has"===r||"have"===r){if(i instanceof Element&&("cssSelector"===o.type&&"class"===o.selectorType||"selector"===o.type&&o.value?.startsWith("."))){const e=o.selector?.slice(1)||o.value?.slice(1)||"";return i.classList.contains(e)}return!1}switch(r){case">":case"is greater than":return i>s;case"<":case"is less than":return s>i;case">=":case"is greater than or equal to":return i>=s;case"<=":case"is less than or equal to":return s>=i;case"==":case"equals":case"is equal to":return i==s;case"===":case"is really equal to":case"really equals":return i===s;case"!=":case"is not equal to":return i!=s;case"!==":case"is not really equal to":return i!==s;case"+":if("string"==typeof i||"string"==typeof s){const e=this.expressionRegistry.get("stringConcatenation");if(e){y("Using string concatenation for:",{leftValue:i,rightValue:s});const r=await e.evaluate(t,{left:i,right:s});return r.success?r.value:i+s}}else{const e=this.expressionRegistry.get("addition");if(e){y("Using numeric addition for:",{leftValue:i,rightValue:s});const r=await e.evaluate(t,{left:i,right:s});return r.success?r.value:i+s}}return i+s;case"-":return i-s;case"*":return i*s;case"/":return i/s;case"%":case"mod":return i%s;case"as":const e="string"==typeof s?s:"identifier"===o.type?o.name:"literal"===o.type?o.value:s+"",a=this.expressionRegistry.get("as");return a?a.evaluate(t,i,e):i;case"&&":case"and":return i&&s;case"||":case"or":return i||s;case"is":return i===s;case"is not":return i!==s;case"is a":case"is an":switch("identifier"===o.type?o.name.toLowerCase():(s+"").toLowerCase()){case"string":return"string"==typeof i;case"number":return"number"==typeof i;case"boolean":return"boolean"==typeof i;case"object":return"object"==typeof i&&null!==i;case"array":return Array.isArray(i);case"function":return"function"==typeof i;case"null":return null===i;case"undefined":return void 0===i;default:const e="identifier"===o.type?o.name:s+"";return null!=i&&i.constructor?.name===e}case"is not a":case"is not an":switch("identifier"===o.type?o.name.toLowerCase():(s+"").toLowerCase()){case"string":return"string"!=typeof i;case"number":return"number"!=typeof i;case"boolean":return"boolean"!=typeof i;case"object":return!("object"==typeof i&&null!==i);case"array":return!Array.isArray(i);case"function":return"function"!=typeof i;case"null":return null!==i;case"undefined":return void 0!==i;default:const e="identifier"===o.type?o.name:s+"";return!(null!=i&&i.constructor?.name===e)}case"=":if("identifier"===n.type){const e=n.name;return"result"===e?Object.assign(t,{result:s}):"it"===e?Object.assign(t,{it:s}):"you"===e?t.you=s:(t.variables||Object.assign(t,{variables:new Map}),t.variables.set(e,s)),s}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(i)?i.includes(s):"string"==typeof i?i.includes(s+""):!(!i||"function"!=typeof i.matches)&&i.matches(s+"");case"match":case"matches":if(i&&"function"==typeof i.matches){const e="string"==typeof s?s:s+"";try{return i.matches(e)}catch{return!1}}return!1;case"in":const c="string"==typeof i?i:i+"",l=s;if(!l||"function"!=typeof l.querySelector){if(Array.isArray(l))return l.includes(i);if("object"==typeof l&&null!==l)return c in l;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof l})`)}return l.querySelector(c);case" ":return"string"==typeof i&&"string"==typeof s?{command:i,selector:s}:"identifier"===n.type&&"selector"===o.type?{command:n.name,selector:o.value}:s;default:throw Error(`Unsupported binary operator: "${r}" (length: ${r.length})`)}}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){const{callee:r,arguments:n,isConstructor:o}=e;if(o){const e=r.name,o=t.globals?.get(e)||window[e];if("function"==typeof o)return new o(...await Promise.all(n.map(e=>this.evaluate(e,t))));throw Error("Unknown constructor: "+e)}if("memberExpression"===r.type||"propertyAccess"===r.type)return await this.evaluateMethodCall(r,n,t);const i=r.name||r,s=this.expressionRegistry.get(i);if(s){const e=["first","last","random","at"],r=["closest","previous","next"].includes(i),o=e.includes(i),a=await Promise.all(n.map(e=>r&&e&&"selector"===e.type&&"string"==typeof e.value?e.value:r&&e&&"identifier"===e.type&&"string"==typeof e.name?e.name:o&&e&&"selector"===e.type&&"string"==typeof e.value?this.evaluateSelector(e,t):this.evaluate(e,t)));return s.evaluate(t,...a)}const a=t.globals?.get(i)||window[i];if("function"==typeof a)return a(...await Promise.all(n.map(e=>this.evaluate(e,t))));throw Error("Unknown function: "+i)}async evaluateMethodCall(e,t,r){try{const n=await this.evaluate(e.object,r),o=this.unwrapSelectorResult(n);if(null==o)throw Error("Cannot call method on null or undefined");const i=e.property?.name||e.property?.value||e.property;if(!i||"string"!=typeof i)throw Error("Invalid method name: "+i);const s=o[i];if("function"!=typeof s)throw Error(`Property "${i}" is not a function on ${o.constructor?.name||typeof o}`);const a=await Promise.all(t.map(e=>this.evaluate(e,r)));return s.apply(o,a)}catch(e){if(e instanceof Error)throw e;throw Error("Failed to evaluate method call: "+e)}}async evaluateSelector(e,t){let r=e.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);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)}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):""}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=n.name||n.value||n;if("string"==typeof i){if(i.startsWith("@")){const e=i.substring(1);if(o&&"function"==typeof o.getAttribute)return o.getAttribute(e)}if(i.startsWith("computed-")){const e=i.substring(9);if(o&&"undefined"!=typeof window&&o instanceof Element)return window.getComputedStyle(o).getPropertyValue(e)}if(i.startsWith("style.")){const e=i.substring(6);if(o&&o.style)return o.style[e]}return o[i]}return o[i]}hasExpression(e){return this.expressionRegistry.has(e)}async evaluateCSSSelector(e,t){let r=e.selector;if(r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim()),"id"===e.selectorType){const e=r.startsWith("#")?r.slice(1):r;return document.getElementById(e)}if("class"===e.selectorType){const e=r.replace(/:/g,"\\:"),t=document.querySelectorAll(e);return Array.from(t).filter(e=>e instanceof HTMLElement)}const n=document.querySelectorAll(r);return Array.from(n).filter(e=>e instanceof HTMLElement)}async evaluateIdSelector(e,t){const r=e.value.startsWith("#")?e.value.slice(1):e.value;return document.getElementById(r)}async evaluateQueryReference(e,t){let r=e.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());try{return document.querySelectorAll(r)}catch{return document.createDocumentFragment().childNodes}}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)?I(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)?I(o,n):o[n],"function"==typeof e?e.bind(o):e}catch(e){throw Error(`Failed to access property "${n}" on target: ${e}`)}}}const $={1:"one",2:"two",3:"three",4:"four",5:"five"};function M(e,t,r,n){if(e.length!==t){return`${r} requires exactly ${o=t,$[o]??o+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}var o;return null}function V(e,t,r,n){return"string"!=typeof e[t]?`${r} ${n||"argument "+(t+1)} must be a string`:null}function D(e,t,r){return M(e,1,t,r)??V(e,0,t,r)}function _(e,t){return M(e,2,t,"left, right")}function B(){return null}function P(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 q(e,t,r,n,o){return t>e.length||e.length>r?`${n} requires ${t}-${r} arguments${o?` (${o})`:""}`:null}function F(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const U="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 H;function W(){return H({validate:e=>({success:!0,data:e})})}function J(e,t){if(U)return W();const r=H({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:F("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:F("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=t in n,i=r.validate(n[t]);if(!i.success)return{success:!1,error:F("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)};if(!e&&void 0===i.data&&!r.t)return{success:!1,error:F("missing-argument",`Required field "${t}" is missing`,t)};void 0!==i.data&&(o[t]=i.data)}return{success:!0,data:o}}});return r.strict=()=>J(e,{strict:!0}),r}H=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 H(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:F("runtime-error",`String must be at least ${e} characters long`)}:n}};return H(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:F("runtime-error",`String must be at most ${e} characters long`)}:n}};return H(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 H(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){return this}),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 z=e=>H(function(e={}){return U?W():H({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:F("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:F("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:F("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:F("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:F("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{})),Z=e=>H(function(e={}){return U?W():H({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:F("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:F("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:F("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{})),G=()=>H(U?W():H({validate:e=>"boolean"!=typeof e?{success:!1,error:F("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}})),Y=e=>H(J(e)),X=e=>H(function(e){return U?W():H({validate:t=>{if(!Array.isArray(t))return{success:!1,error:F("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:F("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:F("runtime-error",o.error.message,o.error.path?`${n}.${o.error.path}`:""+n)};r.push(o.data)}return{success:!0,data:r}}})}(e)),K=()=>H(W()),Q=()=>H(W()),ee=()=>H(function(e,t="Custom validation failed"){return U?W():H({validate:r=>e(r)?{success:!0,data:r}:{success:!1,error:F("runtime-error",t)}})}(e=>void 0===e,"Expected undefined"));class te{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&&C(e)&&1===e.nodeType}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":C(e)?"object":typeof e}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):S(e)?e.split(""):null==e?[]:C(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 O(e)?e?1:0:null}}class re extends te{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=ee(),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 ne extends te{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=ee(),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 oe extends te{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=ee(),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 ie=Y({selector:z().min(1),single:G().optional().default(!1)});class se extends te{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=ie,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 re,new ne,new oe,new se;const ae={name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me instanceof HTMLElement?e.me:null,validate:B},ce={name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you instanceof HTMLElement?e.you:null,validate:B},le={name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:B},ue={name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it,validate:B},fe={name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result,validate:B},de={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=>D(e,"querySelector","selector")},me={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=>D(e,"querySelectorAll","selector")},pe={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=>D(e,"getElementById","ID")},ye={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=>D(e,"getElementsByClassName","className")},he={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"}},ve={name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:B},ge={name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:B},be={name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:B},we={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=>D(e,"elementWithSelector","selector")},Ee={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=>q(e,1,2,"styleRef","property, optional element")??V(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},xe={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.result&&(o=e.result),o){if(n.startsWith("computed-")){const e=n.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(n)||void 0}},validate:e=>M(e,2,"possessiveStyleRef","possessor, property")??V(e,0,"possessiveStyleRef","possessor")??V(e,1,"possessiveStyleRef","property")},Ae={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.result&&(o=e.result),o){if(r.startsWith("computed-")){const e=r.substring(9);return getComputedStyle(o).getPropertyValue(e)||""}return o.style.getPropertyValue(r)||void 0}},validate:e=>M(e,2,"ofStyleRef","property, reference")??V(e,0,"ofStyleRef","property")??V(e,1,"ofStyleRef","reference")},Se={me:ae,you:ce,it:le,its:ue,result:fe,querySelector:de,querySelectorAll:me,getElementById:pe,getElementsByClassName:ye,closest:he,parent:ve,window:ge,document:be,elementWithSelector:we,styleRef:Ee,possessiveStyleRef:xe,ofStyleRef:Ae};var Te=Object.freeze({__proto__:null,CSSSelectorExpression:se,ItExpression:oe,MeExpression:re,YouExpression:ne,classExpression:ye,closestExpression:he,createItExpression:function(){return new oe},createMeExpression:function(){return new re},createYouExpression:function(){return new ne},documentExpression:be,elementWithSelectorExpression:we,idExpression:pe,itExpression:le,itsExpression:ue,meExpression:ae,ofStyleRefExpression:Ae,parentExpression:ve,possessiveStyleRefExpression:xe,querySelectorAllExpression:me,querySelectorExpression:de,referencesExpressions:Se,resultExpression:fe,styleRefExpression:Ee,windowExpression:ge,youExpression:ce});class Oe{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 Ce=new class{constructor(){this.domQueryCache=new Oe(200,3e3),this.exprResultCache=new Oe(500,2e3),this.cssMatchCache=new Oe(100,5e3),this.formValueCache=new Oe(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)})})}};var Ne,ke;"undefined"!=typeof window&&setInterval(()=>{Ce.cleanup()},1e4),function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(Ne||(Ne={})),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"}(ke||(ke={}));const je=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=Ce.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 Le(){Ce.cleanup(),je.getMetrics().memoryUsage>52428800&&je.reset()}let Ie=null;function Re(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){const t=e.valueOf();if("number"==typeof t&&Number.isFinite(t))return t}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function $e(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){Ie&&clearInterval(Ie),Ie=setInterval(Le,e)}();const Me=Y({left:K().describe("Left operand value"),right:K().describe("Right operand value")}).strict(),Ve=Y({operand:K().describe("Operand value to negate")}).strict();class De extends te{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=Me,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 _e extends te{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=Me,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 Be extends te{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=Ve,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 Pe(){return new De}function qe(){return new _e}function Fe(){return new Be}Pe(),qe(),Fe();const Ue=X([K(),K()]),He=X([K(),z()]),We={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){const n=Date.now();try{return $e(this,e,[t,r],t==r,n)}catch(o){throw $e(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>_(e,"equals"),inputSchema:Ue,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"]}},Je={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,r)=>t===r,validate:e=>_(e,"strictEquals")},ze={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],evaluate:async(e,t,r)=>t!=r,validate:e=>_(e,"notEquals")},Ze={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,r)=>t!==r,validate:e=>_(e,"strictNotEquals")},Ge={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,r)=>r>t,validate:e=>_(e,"lessThan")},Ye={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],evaluate:async(e,t,r)=>r>=t,validate:e=>_(e,"lessThanOrEqual")},Xe={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,r)=>t>r,validate:e=>_(e,"greaterThan")},Ke={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],evaluate:async(e,t,r)=>t>=r,validate:e=>_(e,"greaterThanOrEqual")},Qe={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){const n=Date.now();try{return $e(this,e,[t,r],t&&r,n)}catch(o){throw $e(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>_(e,"and"),inputSchema:Ue,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"]}},et={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,r)=>t||r,validate:e=>_(e,"or")},tt={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>M(e,1,"not","operand")},rt={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],evaluate:async(e,t)=>null==t||(S(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element||!C(t)||0!==Object.keys(t).length)),validate:e=>M(e,1,"isEmpty","value")},nt={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],evaluate:async(e,t)=>null==t||!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:!(S(t)||t instanceof Node||t instanceof Element||!C(t)||0!==Object.keys(t).length)),validate:e=>M(e,1,"no","value")},ot={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await rt.evaluate(e,t),validate:e=>M(e,1,"isNotEmpty","value")},it={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>null!=t,validate:e=>M(e,1,"exists","value")},st={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>null==t,validate:e=>M(e,1,"doesNotExist","value")},at={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){if(t&&r){if(1===t.nodeType&&1===r.nodeType)return t.contains(r);if(S(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&1===r.nodeType)return e.contains(r);if(e&&S(r)&&r.match(/^[.#][\w-]+$/)){const t=document.querySelector(r);return!!t&&e.contains(t)}}if(S(r)&&r.match(/^[.#][\w-]+$/)&&1===t.nodeType){const e=document.querySelector(r);return!!e&&t.contains(e)}}return S(t)&&S(r)||Array.isArray(t)?t.includes(r):"undefined"!=typeof NodeList&&t instanceof NodeList?Array.from(t).includes(r):!(!C(t)||!S(r))&&r in t},validate:e=>M(e,2,"contains","container, value")},ct={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,r)=>!await at.evaluate(e,t,r),validate:e=>M(e,2,"doesNotContain","container, value")},lt={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,r)=>!(!S(t)||!S(r))&&t.startsWith(r),validate:e=>M(e,2,"startsWith","str, prefix")},ut={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,r)=>!(!S(t)||!S(r))&&t.endsWith(r),validate:e=>M(e,2,"endsWith","str, suffix")},ft={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 Ce.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 $e(this,e,[t,r],o,n)}catch(o){throw $e(this,e,[t,r],!1,n,!1,o instanceof Error?o:Error(o+"")),o}},validate:e=>M(e,2,"matches","element, selector"),inputSchema:He,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"]}},dt={equals:We,strictEquals:Je,notEquals:ze,strictNotEquals:Ze,lessThan:Ge,lessThanOrEqual:Ye,greaterThan:Xe,greaterThanOrEqual:Ke,and:Qe,or:et,not:tt,no:nt,isEmpty:rt,isNotEmpty:ot,exists:it,doesNotExist:st,contains:at,doesNotContain:ct,startsWith:lt,endsWith:ut,matches:ft};var mt=Object.freeze({__proto__:null,AndExpression:De,NotExpression:Be,OrExpression:_e,andExpression:Qe,containsExpression:at,createAndExpression:Pe,createNotExpression:Fe,createOrExpression:qe,doesNotContainExpression:ct,doesNotExistExpression:st,endsWithExpression:ut,equalsExpression:We,existsExpression:it,greaterThanExpression:Xe,greaterThanOrEqualExpression:Ke,isEmptyExpression:rt,isNotEmptyExpression:ot,lessThanExpression:Ge,lessThanOrEqualExpression:Ye,logicalExpressions:dt,matchesExpression:ft,noExpression:nt,notEqualsExpression:ze,notExpression:tt,orExpression:et,startsWithExpression:lt,strictEqualsExpression:Je,strictNotEqualsExpression:Ze});function pt(e,t,r,n,o="runtime-error"){return{success:!1,error:{name:e+"ConversionError",type:o,message:r,code:t,suggestions:n}}}function yt(e,t){return{success:!0,value:e,type:t}}function ht(e,t){return`${e}: ${t instanceof Error?t.message:t+""}`}const vt={Array:(e,t)=>{try{return Array.isArray(e)?yt(e,"array"):e instanceof NodeList?yt(Array.from(e),"array"):yt(null==e?[]:[e],"array")}catch(e){return pt("Array","ARRAY_CONVERSION_FAILED",ht("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?yt("","string"):S(e)?yt(e,"string"):C(e)?yt(JSON.stringify(e),"string"):yt(e+"","string")}catch(e){return pt("String","STRING_CONVERSION_FAILED",ht("Failed to convert value to String",e),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(e,t)=>{try{if(O(e))return yt(e,"boolean");if(null==e)return yt(!1,"boolean");if(S(e)){const t=e.toLowerCase().trim();return yt("false"!==t&&"0"!==t&&""!==t,"boolean")}return T(e)?yt(0!==e&&!isNaN(e),"boolean"):yt(!!e,"boolean")}catch(e){return pt("Boolean","BOOLEAN_CONVERSION_FAILED",ht("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 yt(e,"number");if(null==e)return yt(0,"number");const t=Number(e);return isNaN(t)?pt("Number","INVALID_NUMBER",`Cannot convert "${e}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):yt(t,"number")}catch(e){return pt("Number","NUMBER_CONVERSION_FAILED",ht("Failed to convert value to Number",e),["Ensure value is convertible to number","Check for special characters"])}},Int:(e,t)=>{const r=vt.Number(e,t);return r.success?yt(Math.trunc(r.value),"number"):r},Float:(e,t)=>{const r=vt.Number(e,t);return r.success?yt(parseFloat(""+r.value),"number"):r},Date:(e,t)=>{try{if(e instanceof Date)return yt(e,"object");if(null==e)return yt(new Date(""),"object");if(S(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return yt(new Date(t,r-1,n),"object")}const t=new Date(e);return isNaN(t.getTime())?pt("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"):yt(t,"object")}catch(e){return pt("Date","DATE_CONVERSION_FAILED",ht("Failed to convert value to Date",e),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(e,t)=>{try{return yt(JSON.stringify(e),"string")}catch(e){return pt("JSON","JSON_STRINGIFY_FAILED",ht("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(C(e))return yt(e,"object");if(S(e))try{return yt(JSON.parse(e),"object")}catch(e){return pt("Object","JSON_PARSE_FAILED",ht("Cannot parse JSON string",e),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return yt({},"object")}catch(e){return pt("Object","OBJECT_CONVERSION_FAILED",ht("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 yt(function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=Et(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}(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=Et(t);void 0!==e&&(r[t.name]=e)}}),yt(r,"object")}return yt({},"object")}catch(e){return pt("FormValues","FORM_VALUES_EXTRACTION_FAILED",ht("Failed to extract form values",e),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},gt=Y({value:Q(),type:z().min(1)});class bt extends te{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=gt,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=vt.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=vt[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=vt[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 wt=Y({value:Q(),type:z().min(1)});function Et(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}new bt,new class extends te{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=wt,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=O(o);break;case"object":a=C(o);break;case"array":a=Array.isArray(o);break;case"function":a=N(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||C(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 xt={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":S(e)?e:C(e)?JSON.stringify(e):e+"",Boolean:e=>{if(O(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=xt.Number(e);return Math.trunc(t)},Float:e=>{const t=xt.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(C(e))return e;if(S(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{S(e)||(e=xt.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:xt.String(e)).join(""):e instanceof Element?e.outerHTML:xt.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return At(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=St(e))}),r}return{}},"Values:Form":(e,t)=>{const r=xt.Values(e,t);return""+new URLSearchParams(r)},"Values:JSON":(e,t)=>{const r=xt.Values(e,t);return JSON.stringify(r)}};function At(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=St(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 St(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 Tt(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):2}:{}}const Ot={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}=Tt(n);return xt.Number(r).toFixed(e||2)}let o=xt[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=xt[i],o)?o(r,e):(console.warn("Unknown conversion type: "+n),r)},validate:e=>M(e,2,"as","value, type")??V(e,1,"as","conversion type")},Ct={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 O(r);case"object":return C(r);case"array":return Array.isArray(r);case"function":return N(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||C(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>M(e,2,"is","value, type")??V(e,1,"is","type")},Nt={name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>M(e,1,"async","expression")},kt={as:Ot,is:Ct,async:Nt};var jt=Object.freeze({__proto__:null,AsExpression:bt,asExpression:Ot,asyncExpression:Nt,conversionExpressions:kt,createAsExpression:function(){return new bt},defaultConversions:xt,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:At,getInputValue:St,isExpression:Ct,parseFixedPrecision:Tt});const Lt={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"},It=Y({collection:K().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Rt=Y({collection:K().describe("Collection to access"),index:Z().describe("Index position to access")}).strict(),$t=Y({collection:K().describe("Collection to select random item from")}).strict();class Mt extends te{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=It,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:Lt[this.inferResultTypeLocal(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"])}}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":S(e)?"String":T(e)?"Number":O(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}}class Vt extends te{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=It,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:Lt[this.inferResultTypeLocal(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"])}}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":S(e)?"String":T(e)?"Number":O(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}}function Dt(){return new Mt}function _t(){return new Vt}Dt(),_t(),new class extends te{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=Rt,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:Lt[this.inferResultTypeLocal(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}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":S(e)?"String":T(e)?"Number":O(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}},new class extends te{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=$t,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:Lt[this.inferResultTypeLocal(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)}inferResultTypeLocal(e){return void 0===e?"Undefined":null===e?"Null":S(e)?"String":T(e)?"Number":O(e)?"Boolean":Array.isArray(e)?"Array":e instanceof HTMLElement?"Element":"Object"}};const Bt={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:C(r)&&"length"in r&&T(r.length)&&r.length>0?r[0]:null},validate:e=>P(e,1,"first","collection")},Pt={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:C(r)&&"length"in r&&T(r.length)&&r.length>0?r[r.length-1]:null},validate:e=>P(e,1,"last","collection")},qt={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(C(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=>q(e,1,2,"at","index, optional collection")??function(e){return"number"!=typeof e[0]?"at index must be a number":null}(e)},Ft={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?Ht(o,r):o.nextElementSibling:null},validate:e=>P(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")},Ut={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?Wt(o,r):o.previousElementSibling:null},validate:e=>P(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 Ht(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?Ht(n,t):null}function Wt(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?Wt(n,t):null}const Jt={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?Zt(i,r,s):null},validate:e=>q(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")},zt={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?Gt(i,r,s):null},validate:e=>q(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 Zt(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=Yt(e);for(const e of n)if(Yt(e)>o)return e;return null}function Gt(e,t,r){const n=Array.from(r.querySelectorAll(t)),o=Yt(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(o>Yt(t))return t}return null}function Yt(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 Xt={first:Bt,last:Pt,at:qt,next:Ft,previous:Ut,nextWithin:Jt,previousWithin:zt};var Kt=Object.freeze({__proto__:null,FirstExpression:Mt,LastExpression:Vt,atExpression:qt,createFirstExpression:Dt,createLastExpression:_t,findNextElementInDOM:Ht,findNextElementWithinContainer:Zt,findPreviousElementInDOM:Wt,findPreviousElementWithinContainer:Gt,firstExpression:Bt,getElementPosition:Yt,lastExpression:Pt,nextExpression:Ft,nextWithinExpression:Jt,positionalExpressions:Xt,previousExpression:Ut,previousWithinExpression:zt});const Qt={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");return r instanceof Element?I(r,n):(C(r),r[n])}},validate:e=>M(e,2,"possessive","element, property")??V(e,1,"possessive","property name")},er={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");return e.me instanceof Element?I(e.me,r):(C(e.me),e.me[r])}},validate:e=>D(e,"my","property")},tr={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;return n instanceof Element?I(n,r):(C(n),n[r])},validate:e=>D(e,"its","property")},rr={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");return e.you instanceof Element?I(e.you,r):(C(e.you),e.you[r])}},validate:e=>D(e,"your","property")},nr={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");return n instanceof Element?I(n,r):(C(n),n[r])}},validate:e=>M(e,2,"of","property, object")??V(e,0,"of","property name")},or={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=>q(e,1,2,"attribute","attributeName, optional element")??V(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},ir={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=>q(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??V(e,0,"attributeWithValue","attribute name")??V(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},sr={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=>D(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=>D(e,"idReference","idValue")},cr={possessive:Qt,my:er,its:tr,your:rr,of:nr,attribute:or,attributeWithValue:ir,classReference:sr,idReference:ar};var lr=Object.freeze({__proto__:null,attributeExpression:or,attributeWithValueExpression:ir,classReferenceExpression:sr,getElementProperty:I,idReferenceExpression:ar,isAriaAttribute:function(e){return e.startsWith("aria-")||"aria"===e},isDataAttribute:function(e){return e.startsWith("data-")||"data"===e},itsExpression:tr,myExpression:er,ofExpression:nr,possessiveExpression:Qt,propertiesExpressions:cr,yourExpression:rr});const ur=Y({value:z().describe("String literal value")}).strict(),fr=Y({value:Z().describe("Number literal value")}).strict(),dr=Y({value:G().describe("Boolean literal value")}).strict(),mr=Y({left:K().describe("Left operand"),right:K().describe("Right operand")}).strict();class pr extends te{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=ur,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 yr extends te{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=fr,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?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?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 hr extends te{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=dr,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 vr extends te{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=mr,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=Re(t.left,"left operand")+Re(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 gr extends te{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=mr,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=mr.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(O(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}class br extends te{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=mr,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=Re(t.left,"left operand")*Re(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 wr(){return new pr}function Er(){return new yr}function xr(){return new hr}function Ar(){return new vr}function Sr(){return new gr}function Tr(){return new br}const Or={stringLiteral:wr(),numberLiteral:Er(),booleanLiteral:xr(),addition:Ar(),stringConcatenation:Sr(),multiplication:Tr()};var Cr=Object.freeze({__proto__:null,AdditionExpression:vr,BooleanLiteralExpression:hr,MultiplicationExpression:br,NumberLiteralExpression:yr,StringConcatenationExpression:gr,StringLiteralExpression:pr,createAdditionExpression:Ar,createBooleanLiteralExpression:xr,createMultiplicationExpression:Tr,createNumberLiteralExpression:Er,createStringConcatenationExpression:Sr,createStringLiteralExpression:wr,specialExpressions:Or});class Nr extends R{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Se),this.registerCategory(dt),this.registerCategory(kt),this.registerCategory(Xt),p("About to register properties expressions:",Object.keys(cr)),this.registerCategory(cr),p("Total expressions registered:",this.expressionRegistry.size),p('Registry has "possessive":',this.expressionRegistry.has("possessive")),p('Registry has "my":',this.expressionRegistry.has("my")),this.registerCategory(Or)}}class kr{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 Nr,this.hookRegistry=r??null}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(f(`CommandAdapterV2: Executing '${this.name}' with args:`,t),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void f(`CommandAdapterV2: '${this.name}' intercepted by hook`);e.locals||(e.locals=new Map),e.locals.set("__evaluator",this.expressionEvaluator);const o=kr.toTyped(e);let i,s;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(f(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers?.when||r.modifiers?.where;if(t&&!await this.expressionEvaluator.evaluate(t,e))return void f(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:r.modifiers||{},commandName:r.commandName},this.expressionEvaluator,e)}else i=t;else f(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=t;return f("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),f("CommandAdapterV2: Command result:",s),Object.assign(e,kr.fromTyped(o,e)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,s),s}catch(e){if(f(`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 Lr{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=e,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e,h("CommandRegistryV2: Hook registry set")}getHookRegistry(){return this.hookRegistry}register(e){const t=(e.name||e.metadata?.name).toLowerCase();h(`CommandRegistryV2: Registering command '${t}'`),this.implementations.set(t,e);const r=new jr(e,this.sharedEvaluator,this.hookRegistry);this.adapters.set(t,r);const n=e.metadata?.aliases;if(n&&Array.isArray(n))for(const t of n){const n=t.toLowerCase();this.implementations.set(n,e),this.adapters.set(n,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 Ir=null;function Rr(){return Ir||(Ir=function(e){const t=e?.commands??new Lr,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}()),Ir}class $r{constructor(e={}){this.contextCache=new WeakMap;const t=Rr();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,h(`[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),h(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),t}catch(t){return h("[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 h(`[RegistryIntegration] Found event source for '${e}'`),t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){const t=this.eventSourceRegistry.get(r);return h(`[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 h(`[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,h("[RegistryIntegration] Destroyed")}}class Mr{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 $r("object"==typeof e.registryIntegration?e.registryIntegration:{}),h("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=>{for(const t of e)for(const e of t.removedNodes)if(e instanceof Element){const t=this.cleanupRegistry.cleanupElementTree(e);t>0&&h(`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(),h("RuntimeBase: Destroyed")}async execute(e,t){h(`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(!o(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}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(!o(n)){const e=n.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}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(!o(r)){const e=r.error,t=Error(e.type.toUpperCase()+"_EXECUTION");throw t["is"+e.type.charAt(0).toUpperCase()+e.type.slice(1)]=!0,"returnValue"in e&&(t.returnValue=e.returnValue),t}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(f(`RUNTIME BASE: Processing command '${i}'`),console.log("[RUNTIME DEBUG] executeCommand called with:",i),this.registry.has(i)){console.log("[RUNTIME DEBUG] Found command:",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 e instanceof Error&&(!0===e.isHalt||!0===e.isExit||"HALT_EXECUTION"===e.message||"EXIT_COMMAND"===e.message)||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){if(e instanceof Error){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}return null}async processCommandWithResult(e,t){const{name:o,args:i,modifiers:s}=e,a=o.toLowerCase();if(f(`RUNTIME BASE (Result): Processing command '${a}'`),!this.registry.has(a)){const e=`Unknown command: ${o}. 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 r(await c.execute(t,{args:i||[],modifiers:s||{},commandName:a,runtime:this}))}catch(e){const t=this.toSignal(e);if(t)return n(t);throw console.error(`Error executing command '${a}':`,e),e}}async executeCommandSequenceWithResult(e,t){let n;for(const i of e)if("command"===i.type){const e=await this.processCommandWithResult(i,t);if(!o(e)){const n=e.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return e;case"return":return void 0!==n.returnValue&&Object.assign(t,{it:n.returnValue,result:n.returnValue}),r(n.returnValue)}}n=e.value}else{const e=await this.evaluateExpressionWithResult(i,t);if(!o(e))return e;n=e.value}return r(n)}async evaluateExpression(e,t){const r=await this.expressionEvaluator.evaluate(e,t);return r&&"object"==typeof r&&r.command&&r.selector?await this.executeCommandFromPattern(r.command,r.selector,t):r}async evaluateExpressionWithResult(e,t){const i=await this.expressionEvaluator.evaluateWithResult(e,t);if(!o(i))return i;const s=i.value;if(s&&"object"==typeof s&&s.command&&s.selector){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},t);try{return r(await this.executeCommandFromPattern(s.command,s.selector,t))}catch(e){const t=this.toSignal(e);if(t)return n(t);throw e}}return r(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(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}for(const e of o)try{r=await this.execute(e,t)}catch(e){if(e instanceof Error&&(e.isHalt||e.isExit))break;throw e}for(const e of i)try{r=await this.execute(e,t)}catch(e){if(e instanceof Error&&(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(e instanceof Error&&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){const r=e;if(r.isHalt||r.isExit)break;if(r.isReturn){if(void 0!==r.returnValue)return Object.assign(t,{it:r.returnValue,result:r.returnValue}),r.returnValue;break}if(r.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;this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:o,initBlock:i}),h(`RUNTIME BASE: Registered behavior '${r}'`)}async installBehaviorOnElement(e,t,r){h("BEHAVIOR: installBehaviorOnElement called: "+e);const n=this.behaviorRegistry.get(e);if(!n)throw Error(`Behavior "${e}" not found`);h("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){h("BEHAVIOR: Running init block for "+e);try{await this.execute(n.initBlock,i),h("BEHAVIOR: Init block completed for "+e)}catch(t){if(h(`BEHAVIOR: Init block error for ${e}:`,t),!(t instanceof Error&&t.isHalt))throw t}}if(h(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${e}`),n.eventHandlers)for(const e of n.eventHandlers)await this.executeEventHandler(e,i);h("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];h(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let d=[],m=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)m=window;else if("document"===e||"the document"===e||"body"===e)m=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);h(`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 h(`BEHAVIOR: Target resolution: querying for '${i}'`),d=this.queryElements(i,t)}else d=t.me?[t.me]:[];if(0===d.length&&!m)return void h(`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 p=e.customEventSource;if(p&&this.registryIntegration){h(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' 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);h(`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(p,{event:r,handler:e,target:i,selector:a},t);h(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${p}' subscription ${n.id}`)}catch(e){console.error(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,e)}return}const y=async e=>{const r=e.l||0;if(r>=100)return;if(e.l=r+1,a&&e.target instanceof Element&&!e.target.matches(a)&&!e.target.closest(a))return;const n=new Map(t.locals),i={...t,locals:n,it:e,event:e};n.has("target")||i.locals.set("target",e.target);const c=this.enhanceContext(i);if(s&&s.length>0)for(const t of s)c.locals.set(t,e[t]||e.detail?.[t]||null);for(const e of o)try{const t=await this.execute(e,c);if(void 0!==t){let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult){void 0!==e&&Object.assign(c,{it:e,result:e});continue}}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)continue;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}Array.isArray(e)&&e.length>0&&(e=e[0]),Object.assign(c,{it:e,result:e})}}catch(e){const t=e;if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(c,{it:t.returnValue,result:t.returnValue});break}throw console.error("COMMAND FAILED:",e),e}};let v;if(u){let e=y;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)}}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=y;const g=u?.once?{once:!0}:void 0;if(m)for(const e of f)m.addEventListener(e,v,g),d.length>0?this.cleanupRegistry.registerListener(d[0],m,e,v):this.cleanupRegistry.registerGlobal(()=>m.removeEventListener(e,v),"listener",`Global ${e} listener`);else for(const e of d)for(const t of f)e.addEventListener(t,v,g),this.cleanupRegistry.registerListener(e,e,t,v)}setupMutationObserver(e,t,r,n){h(`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){d(`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){console.error("❌ Error executing mutation handler command:",e)}}});e.observe(o,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(o,e),h("RUNTIME BASE: MutationObserver attached to",o,`for attribute '${t}'`)}}async setupChangeObserver(e,t,r){h("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))),h(`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){d("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){console.error("❌ Error executing change handler command:",e)}}});n.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,n),h("RUNTIME BASE: MutationObserver attached to",e,"for content changes")}}queryElements(e,t){const r=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)return[];let n=e;return n.startsWith("<")&&n.endsWith("/>")&&(n=n.slice(1,-2).trim()),Array.from(r.querySelectorAll(n))}isElement(e){return"undefined"!=typeof HTMLElement&&e instanceof HTMLElement||e&&"object"==typeof e&&e.style&&e.classList}}const Vr={core:["references","logical","special"],common:["properties","conversion"],optional:["positional"]};class Dr extends R{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=Vr[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.u(e);this.loadPromises.set(e,t);try{await t,this.loadedCategories.add(e),y("✅ Loaded expression category: "+e)}finally{this.loadPromises.delete(e)}}async u(e){try{let t;switch(y("📦 Loading expression category: "+e),e){case"references":t=await Promise.resolve().then(function(){return Te});break;case"logical":t=await Promise.resolve().then(function(){return mt});break;case"special":t=await Promise.resolve().then(function(){return Cr});break;case"properties":t=await Promise.resolve().then(function(){return lr});break;case"conversion":t=await Promise.resolve().then(function(){return jt});break;case"positional":t=await Promise.resolve().then(function(){return Kt});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),y(` ✓ 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 y("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)&&(y(`🔄 Auto-loading category for node type: ${e.type} → ${r}`),await this.loadCategory(r)),super.evaluate(e,t)}async warmupExpressions(e){y("🔥 Warming up expression categories: "+e.join(", ")),await Promise.all(e.map(e=>this.loadCategory(e)))}getLoadedCategories(){return Array.from(this.loadedCategories)}}function _r(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,m=r.length-1;m>=0;m--){var p={};for(var y in n)p[y]="access"===y?{}:n[y];for(var y in n.access)p.access[y]=n.access[y];p.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");i.push(s(e||null))};var h=(0,r[m])("accessor"===c?{get:f.get,set:f.set}:f[l],p);if("accessor"===c){if(void 0===h)continue;if(null===h||"object"!=typeof h)throw new TypeError("Object expected");(a=s(h.get))&&(f.get=a),(a=s(h.set))&&(f.set=a),(a=s(h.init))&&o.unshift(a)}else(a=s(h))&&("field"===c?o.unshift(a):f[l]=a)}u&&Object.defineProperty(u,n.name,f),d=!0}function Br(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 Pr(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 qr=Symbol("command:name"),Fr=Symbol("command:category"),Ur=Symbol("command:metadata");function Hr(e){return function(t,r){const n=t;n[qr]=e.name,n[Fr]=e.category,Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function Wr(e){return function(t,r){const n=t,o=n[Fr];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"};n[Ur]=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 Jr(e){return()=>new e}function zr(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function Zr(e,t){if(zr(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 Yr(e)}if("string"==typeof e){const r=e.trim();if("me"===r){if(!t.me)throw Error('Context reference "me" is not available');return Yr(t.me)}if("it"===r){if(!zr(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 Yr(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(!zr(o))throw Error("Element found but is not an HTMLElement: "+r);return o}throw Error("Invalid target type: "+typeof e)}function Gr(e,t){if(Array.isArray(e))return e.filter(zr);if(e instanceof NodeList)return Array.from(e).filter(zr);if(zr(e))return[e];if(!e){const e=t.me;return e&&zr(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&zr(t.me)?[t.me]:[];if("it"===r)return zr(t.it)?[t.it]:[];if("you"===r)return t.you&&zr(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(zr)}}return[]}function Yr(e){if(zr(e))return e;throw Error("Value is not an HTMLElement")}function Xr(e,t){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error('No "me" element in context');if(!zr(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(!zr(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(!zr(t.you))throw Error("context.you is not an HTMLElement");return t.you;default:throw Error("Unknown possessive: "+e)}}const Kr=["on","from","to","in","with","at"];async function Qr(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||!Kr.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(!zr(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(zr(o))a.push(o);else if(o instanceof NodeList){const e=Array.from(o).filter(zr);a.push(...e)}else if(Array.isArray(o)){const e=o.filter(zr);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(zr);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(!zr(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}class en{async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await Qr(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=>zr(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 tn=(()=>{let e,t,r=[Wr({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),Hr({name:"hide",category:"dom"})],n=[],o=en;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=>zr(e))}},Pr(t,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const rn=Jr(tn);let nn=(()=>{let e,t,r=[Wr({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),Hr({name:"show",category:"dom"})],n=[],o=en;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=>zr(e))&&"string"==typeof t.defaultDisplay}},Pr(t,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const on=Jr(nn);function sn(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function an(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 cn(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 un(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 fn(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 dn(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function mn(e){if(!e||0===e.trim().length)return!1;const t=e.trim();return!!dn(t)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function pn(e,t){return e.map(e=>{if(dn(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 yn(e){return"string"==typeof e&&e.trim().startsWith("*")}function hn(e,t,r){e.style.setProperty(t,r)}const vn=["dialog","details","summary","select"];function gn(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 bn(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=gn(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=gn(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:gn(e),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1}}class wn{async resolveTargets(e,t,r,n){return Qr(e,t,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(e,t,r){return bn(e,t,r)}parseClassNames(e){return fn(e)}isAttribute(e){return sn(e.trim())}isCSSProperty(e){return yn(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>zr(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 En=(()=>{let e,t,r=[Wr({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"]}),Hr({name:"add",category:"dom"})],n=[],o=wn;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=an(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=pn(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,cn(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}},Pr(t,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const xn=Jr(En);function An(e){return!!e.parentNode&&(e.remove(),!0)}let Sn=(()=>{let e,t,r=[Wr({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"]}),Hr({name:"remove",category:"dom"})],n=[],o=wn;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(zr(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&zr(n[0]))return{type:"element",targets:n.filter(e=>zr(e))};if("string"==typeof n){const o=n.trim();if(this.isAttribute(o))return{type:"attribute",name:an(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=pn(e.classes,t);r.length>0&&ln(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":r=e.name,cn(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)An(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}},Pr(t,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const Tn=Jr(Sn);function On(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 Cn(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=On(e);return r?r.milliseconds:t}return t}function Nn(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=On(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function kn(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 jn(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 Ln(e){return 0===e.length?[]:"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function In(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&un(e,r)}}function Rn(e,t,r,n){const o=In(e,t,r),i=setTimeout(o,n);return()=>{clearTimeout(i)}}function $n(e,t,r,n){const o=In(e,t,r),i=()=>{o(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function Mn(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]}function Vn(e,t,r){if(t.startsWith("@"))return void e.setAttribute(t.substring(1),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 Dn(e){return null==e||""===e}const _n=/^the\s+(.+?)\s+of\s+(.+)$/i,Bn=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 Pn(e){return"string"==typeof e&&_n.test(e)}function qn(e,t){const r=e.match(_n);if(!r)return null;try{return{element:Zr(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function Fn(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]),zr(o)?{element:o,property:n}:null}(e,t,r);if(function(e){return!(!e||"object"!=typeof e)&&"propertyAccess"===e.type&&"string"==typeof e.property}(e))return async function(e,t,r){const n=e.property;if(!n)return null;let o=await t.evaluate(e.object,r);return Array.isArray(o)&&(o=o[0]),zr(o)?{element:o,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type){const e=n.object,o=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!zr(i))return null;const s=o?.name||o?.value;return s?{element:i,property:s}:null}return null}function Un(e,t){const{element:r,property:n}=e;n.startsWith("*")?hn(r,n.substring(1),t+""):Vn(r,n,t)}async function Hn(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?Cn(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 Wn(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 vn.includes(t)}(t)}(t);if(zr(e)||Array.isArray(e)&&e.every(e=>zr(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 vn.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const Jn=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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 Hn(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 Qr(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 Fn(n,t,r);if(i)return{type:"property",target:i};const{duration:s,untilEvent:a}=await Hn(e.modifiers,t,r),{value:c}=await bn(n,t,r);if(Pn(c)){const e=qn(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=Wn(c,n),f={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:o}=an(u);return{type:"attribute",name:n,value:o,targets:await Qr(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 Qr(e.args.slice(1),t,r,"toggle",f,e.modifiers)}}case"element":{let o;if(zr(c))o=[c];else if(Array.isArray(c)&&c.every(e=>zr(e)))o=c;else if(u){const e=document.querySelectorAll(u);o=Array.from(e).filter(e=>zr(e))}else o=await Qr([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:Ln(o)}:"select"===i?{type:"select",targets:o}:{type:"classes",classes:fn(u),targets:o,duration:s,untilEvent:a}}default:{const n=fn(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Qr(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=pn(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&&Rn(t,"class",r[0],e.duration),e.untilEvent&&$n(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(r=e.name,n=e.value,cn(e.targets,e=>{un(e,r,n)}),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Rn(t,"attribute",e.name,e.duration),e.untilEvent&&$n(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return cn(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)):Mn(t,r)}(e),r=e.property;if("boolean"==typeof t||Bn.has(r)||Bn.has(r.toLowerCase())){const r=!t;return Un(e,r),r}if("number"==typeof t){const r=0===t?1:0;return Un(e,r),r}if("string"==typeof t){const n="__ht_"+r,o=e.element[n];return""===t&&void 0!==o?(Un(e,o),o):(e.element[n]=t,Un(e,""),"")}Un(e,!t)}(e.target),[e.target.element];case"dialog":return cn(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 cn(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return cn(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&&Rn(t,"class",e.classA,e.duration),e.untilEvent&&$n(t,"class",e.classA,e.untilEvent);return[...e.targets]}var r,n}},Pr(t,"ToggleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());const zn=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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,m=null;if(c){const e=n(c),o=await Fn(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?m=e.value:"identifier"===e?.type&&(m=e.name),m&&n?.name)f=n.name;else{const e=await t.evaluate(c,r);"string"==typeof e&&(m=e)}}else if("identifier"===e&&"me"===c.name)m=null;else if("selector"===e||"cssSelector"===e)m=c.value||c.selector;else if("literal"===e){const e=c.value;if("string"==typeof e&&Pn(e)){const t=qn(e,r);if(t)return{value:l,targets:[t.element],position:"replace",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?m=e:d=e+""}else if("identifier"===e){const e=c.name;this.looksLikeCss(e)?m=e:d=e}else{const e=await t.evaluate(c,r);"string"==typeof e&&(this.looksLikeCss(e)?m=e:d=e)}}return d?{value:l,targets:[],position:u,memberPath:f,variableName:d}:{value:l,targets:await this.resolveTargets(m,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,[];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||!zr(t.me))throw Error("put: no target and context.me is null");return[t.me]}const r=Array.from(document.querySelectorAll(e)).filter(e=>zr(e));if(!r.length)throw Error(`No elements: "${e}"`);return r}parseValue(e){return zr(e)?e:null==e?"":e+""}insertContent(e,t,r){if("replace"!==r)if(zr(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 zr(t)?(e.innerHTML="",e.appendChild(t)):t.includes("<")&&t.includes(">")?e.innerHTML=t:e.textContent=t}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}},Pr(t,"PutCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());function Zn(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 Gn(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 Yn(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 Xn(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Gn(e,t)}const Kn=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(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&&Yn(o,i,t),i}},Pr(t,"MakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());function Qn(e,t,r){return e?new Promise(r=>{const n=to(()=>{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 eo(e){return new Promise(t=>setTimeout(t,e))}function to(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}const ro=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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 eo(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,o=(await Qn(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:Nn(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:Nn(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?eo(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e})):Qn(e.target??t.me??document,e.eventName).then(t=>({result:t.event,winningCondition:e})));return Promise.race(r)}},Pr(t,"WaitCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());const no=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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};if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let l;i.timeout&&(l=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.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{l&&clearTimeout(l),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(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":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){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();default:return 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&&zr(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}},Pr(t,"FetchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),oo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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 Fn(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){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(zr(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(Pn(s)){const n=qn(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&&yn(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&&sn(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=Xr(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:o,property:n[2],value:i}}}if(zr(s))return{type:"property",element:s,property:"textContent",value:await this.extractValue(e,t,r)};if(Array.isArray(s)&&s.length>0&&zr(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 Vn(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return hn(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))Vn(t,r,n);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,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=Xr(e,n),s=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.name,value:s}}}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 Zr(e?await t.evaluate(e,r):void 0,r)}async resolveTargets(e,t,r){return Gr(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=Zr(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&&zr(t.element)&&"value"in t;case"property":return"string"==typeof t.property&&zr(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&zr(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}}},Pr(t,"SetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());let io=(()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(e)){const r=e;return t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?Zn(r.getAttribute(t)):Zn(r[t]):Zn(r.value||r.textContent)}return"string"==typeof e?"global"===r?Zn(Gn(e,n,"global")):e.includes(".")?function(e,t){const r=e.split("."),n=r[1],o=Xn(r[0],t);return o?Zn(o[n]):0}(e,n):Zn("me"===e&&n.me?n.me.value||0:"it"===e?n.it||0:"you"===e&&n.you?n.you.value||0:Gn(e,n)):Zn(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(zr(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 Yn(e,n,o,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),o=n[1],i=Xn(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);Yn(e,n,o)}}(r,n,o,c,t),Object.assign(t,{it:c}),c}},Pr(t,"NumericModifyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})();const so=Jr(io),ao=Jr(io),co=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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)}},Pr(t,"LogCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());function lo(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 uo=(()=>{let e,t,r=[Wr({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"]}),Hr({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))a=s.name,s.args?.length&&(c=await this.parseEventDetail(s.args,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(zr(e))o.push(e);else if(e instanceof NodeList)o.push(...Array.from(e).filter(zr));else if(Array.isArray(e))o.push(...e.filter(zr));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(zr));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)return await t.evaluate(e[0],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()]=lo(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}},Pr(t,"EventDispatchCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})();const fo=Jr(uo),mo=Jr(uo),po=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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&&zr(t.me))return t.me;if("it"===r&&zr(t.it))return t.it;if("you"===r&&zr(t.you))return t.you;const n=Gn(r,t);if(zr(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)}}},Pr(t,"GoCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());function yo(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=Gn(e,t);return void 0!==r?!!r:!!e}return!!e}const ho=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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=yo(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}},Pr(t,"ConditionalCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),vo=ho,go=ho;let bo=(()=>{let e,t,r=[Wr({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"]}),Hr({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,yo,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,yo,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}},Pr(t,"RepeatCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})();const wo=Jr(bo);class Eo{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 xo=(()=>{let e,t,r=[Wr({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"]}),Hr({name:"break",category:"control-flow"})],n=[],o=Eo;return t=class extends o{constructor(){super(...arguments),this.signalType="break",this.errorMessage="BREAK_LOOP",this.errorFlag="isBreak"}},Pr(t,"BreakCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const Ao=Jr(xo);let So=(()=>{let e,t,r=[Wr({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"]}),Hr({name:"continue",category:"control-flow"})],n=[],o=Eo;return t=class extends o{constructor(){super(...arguments),this.signalType="continue",this.errorMessage="CONTINUE_LOOP",this.errorFlag="isContinue"}},Pr(t,"ContinueCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const To=Jr(So),Oo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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}},Pr(t,"HaltCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Co=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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}},Pr(t,"ReturnCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());let No=(()=>{let e,t,r=[Wr({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"]}),Hr({name:"exit",category:"control-flow"})],n=[],o=Eo;return t=class extends o{constructor(){super(...arguments),this.signalType="exit",this.errorMessage="EXIT_COMMAND",this.errorFlag="isExit"}},Pr(t,"ExitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})(),t})();const ko=Jr(No),jo=new Map,Lo=Jr((()=>{let e,t,r=[Wr({description:"Create two-way data binding between variables and DOM elements",syntax:["bind :variable to <element>.<property>","bind :variable from <element>.<property>","bind :variable to <element>.<property> bidirectional"],examples:["bind :username to my.value","bind :count from #display.textContent","bind :message to #input.value bidirectional"],sideEffects:["data-binding","event-listeners","dom-observation"]}),Hr({name:"bind",category:"data"})],n=[];return t=class{async parseInput(e,t,r){if(!e.args||1>e.args.length)throw Error("bind command requires a variable name");const n=await t.evaluate(e.args[0],r),o="string"==typeof n&&n.startsWith(":")?n.substring(1):n+"";let i,s="to";e.modifiers?.bidirectional||e.bidirectional?s="bidirectional":e.modifiers?.to||"to"===e.direction?s="to":(e.modifiers?.from||"from"===e.direction)&&(s="from");let a="value";if(e.modifiers?.to||e.modifiers?.from){const n=e.modifiers.to||e.modifiers.from,o=await t.evaluate(n,r);if(zr(o))i=o;else if("string"==typeof o){const e=o.split(".");e.length>1?(i=e[0],a=e.slice(1).join(".")):i=o}else i=o}else{if(!e.target)throw Error("bind command requires a target element (to/from)");i=e.target,a=e.property||"value"}const c=await this.resolveElement(i,t,r);if(!c)throw Error("Cannot resolve target element: "+i);return{variable:o,target:c,property:a,direction:s}}async execute(e,t){const{variable:r,target:n,property:o,direction:i}=e,s=this.createBinding(r,n,o,i,t);return this.dispatchEvent(t,"bind:created",{variable:r,element:n,property:o,direction:i,bindingId:s}),{success:!0,variable:r,element:n,property:o,direction:i,bindingId:s}}createBinding(e,t,r,n,o){const i=`bind-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,s=[];if("to"===n||"bidirectional"===n){const i=()=>{const n=Mn(t,r);o.locals.set(e,n);const i=new CustomEvent(`variable:${e}:change`,{detail:{value:n,source:"variable",originElement:t},bubbles:!0});t.dispatchEvent(i)},a=this.getEventTypeForProperty(r);t.addEventListener(a,i),s.push(()=>t.removeEventListener(a,i)),"to"===n&&i()}if("from"===n||"bidirectional"===n){const n=n=>{const i=n,s=i.detail?.value??o.locals.get(e),a=i.detail?.originElement;a&&a===t||Vn(t,r,s)};if(t.addEventListener(`variable:${e}:change`,n),s.push(()=>t.removeEventListener(`variable:${e}:change`,n)),r.startsWith("@")||"textContent"===r||"innerHTML"===r){const n=new MutationObserver(()=>{const n=o.locals.get(e);Vn(t,r,n)});n.observe(t,{attributes:!0,childList:!0,characterData:!0}),s.push(()=>n.disconnect())}const i=o.locals.get(e);void 0!==i&&Vn(t,r,i)}return jo.set(i,{id:i,variable:e,element:t,property:r,direction:n,cleanup:()=>s.forEach(e=>e())}),i}async resolveElement(e,t,r){if(zr(e))return e;if(e&&"object"==typeof e&&e.type&&(e=await t.evaluate(e,r)),"string"==typeof e){if(["me","my","it","its","you","your"].includes(e.toLowerCase()))try{return Xr(e,r)}catch{return null}if("undefined"!=typeof document)try{return document.querySelector(e)}catch{return null}}return null}getEventTypeForProperty(e){return{value:"input",checked:"change",textContent:"input",innerHTML:"input"}[e]||"change"}dispatchEvent(e,t,r){if(zr(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Pr(t,"BindCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());let Io=(()=>{let e,t,r=[Wr({description:"Evaluate an expression and store the result in the it variable",syntax:["call <expression>","get <expression>"],examples:["call myFunction()","get user.name",'call fetch("/api/data")'],sideEffects:["function-execution","context-mutation"]}),Hr({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],alias:e.alias||"call"})}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}}},Pr(t,"CallCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})();(()=>{let e,t,r=[Wr({description:"Alias for call - evaluate an expression and store the result in the it variable",syntax:["get <expression>"],examples:["get user.profile","get document.title"],sideEffects:["function-execution","context-mutation"]}),Hr({name:"get",category:"execution"})],n=[],o=Io;t=class extends o{},Pr(t,"GetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;_r(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}),Br(t,n)})()})();const Ro=Jr(Io),$o=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(e))return e.innerHTML+=o,{result:e,targetType:"element",target:e}}const e=Gn(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 Yn(n,i,t),{result:i,targetType:"variable",target:n}}return Yn(n,o,t),{result:o,targetType:"variable",target:n}}if(Array.isArray(n))return n.push(r),{result:n,targetType:"array"};if(zr(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)}}},Pr(t,"AppendCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Mo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(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=Zr(n,t),c=Cn(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+"",m=!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),m=!0}a.style.setProperty(r,d);const p=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=to(()=>{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,m&&a.style.removeProperty(r),Object.assign(t,{it:a}),{element:a,property:r,fromValue:l,toValue:d,duration:c,completed:p.completed}}},Pr(t,"TransitionCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Vo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(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(zr(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=Zr(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"}}},Pr(t,"MeasureCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Do=Jr((()=>{let e,t,r=[Wr({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"]}),Hr({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);(zr(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=Zr(r,t),i=Cn(n,5e3),s=Date.now(),a=getComputedStyle(o),c=kn(a.transitionDuration),l=kn(a.transitionDelay),u=kn(a.animationDuration),f=kn(a.animationDelay),d=jn(c,l),m=jn(u,f),p=Math.max(d,m),y=await(h=o,v=p,g=i,v>0?new Promise(e=>{const t=e=>{e.target===h&&n({completed:!0,type:"transition"})},r=e=>{e.target===h&&n({completed:!0,type:"animation"})},n=to(()=>{h.removeEventListener("transitionend",t),h.removeEventListener("animationend",r),clearTimeout(o),clearTimeout(i)},e);h.addEventListener("transitionend",t),h.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 h,v,g;const b=Date.now()-s;return Object.assign(t,{it:o}),{element:o,settled:y.completed,timeout:i,duration:b}}},Pr(t,"SettleCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),_o=Jr((()=>{let e,t,r=[Wr({description:"Save and restore values from browser storage with TTL support",syntax:["persist <value> to <storage> as <key>","restore <key> from <storage>","remove <key> from <storage>"],examples:['persist myValue to local as "username"','persist formData to session as "draft"','restore "username" from local'],sideEffects:["storage","data-mutation"]}),Hr({name:"persist",category:"data"})],n=[];return t=class{async parseInput(e,t,r){let n,o,i,s,a="save";if(e.modifiers?.from)a="restore",n=await t.evaluate(e.args[0],r)+"",i=await t.evaluate(e.modifiers.from,r)+"";else{if(a="save",o=await t.evaluate(e.args[0],r),e.modifiers?.to&&(i=await t.evaluate(e.modifiers.to,r)+""),!e.modifiers?.as)throw Error('persist command requires "as <key>" modifier');n=await t.evaluate(e.modifiers.as,r)+"",e.modifiers?.ttl&&(s=Number(await t.evaluate(e.modifiers.ttl,r)))}return{key:n,value:o,storage:i||"local",ttl:s,operation:a}}async execute(e,t){const{key:r,value:n,storage:o="local",ttl:i,operation:s="save"}=e;if(!r||"string"!=typeof r||""===r.trim())throw Error("persist command requires a valid storage key");const a=this.getStorage(o);if(!a)throw Error(`Storage not available: ${o}Storage`);switch(s){case"save":return await this.saveValue(r,n,a,o,i,t);case"restore":return await this.restoreValue(r,a,o,t);case"remove":return await this.removeValue(r,a,o,t);default:throw Error("Unknown persist operation: "+s)}}getStorage(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch(t){return console.warn(`Storage not available: ${e}Storage`,t),null}}async saveValue(e,t,r,n,o,i){const s=Date.now(),a={value:t,timestamp:s,...void 0!==o&&{ttl:o}};try{const c=JSON.stringify(a);return r.setItem(e,c),this.dispatchEvent(i,"persist:save",{key:e,value:t,storage:n,timestamp:s,ttl:o}),{success:!0,operation:"save",key:e,value:t,storage:n,timestamp:s}}catch(t){throw this.dispatchEvent(i,"persist:error",{key:e,operation:"save",error:t instanceof Error?t.message:"Unknown error"}),Error("Failed to persist value: "+(t instanceof Error?t.message:"Unknown error"))}}async restoreValue(e,t,r,n){try{const o=t.getItem(e);if(null===o)return this.dispatchEvent(n,"persist:notfound",{key:e}),{success:!1,operation:"restore",key:e,value:null,storage:r};const i=JSON.parse(o),{value:s,timestamp:a,ttl:c}=i,l=Date.now();return void 0!==c&&l-a>c?(t.removeItem(e),this.dispatchEvent(n,"persist:expired",{key:e,timestamp:a,ttl:c}),{success:!1,operation:"restore",key:e,value:null,storage:r,expired:!0}):(this.dispatchEvent(n,"persist:restore",{key:e,value:s,storage:r}),Object.assign(n,{it:s}),{success:!0,operation:"restore",key:e,value:s,storage:r,timestamp:a})}catch(t){throw this.dispatchEvent(n,"persist:error",{key:e,operation:"restore",error:t instanceof Error?t.message:"Unknown error"}),Error("Failed to restore value: "+(t instanceof Error?t.message:"Unknown error"))}}async removeValue(e,t,r,n){try{return t.removeItem(e),this.dispatchEvent(n,"persist:remove",{key:e,storage:r}),{success:!0,operation:"remove",key:e,storage:r}}catch(t){throw this.dispatchEvent(n,"persist:error",{key:e,operation:"remove",error:t instanceof Error?t.message:"Unknown error"}),Error("Failed to remove value: "+(t instanceof Error?t.message:"Unknown error"))}}dispatchEvent(e,t,r){if(zr(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Pr(t,"PersistCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Bo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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},{})}}},Pr(t,"JsCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Po=Jr((()=>{let e,t,r=[Wr({description:"Execute commands asynchronously without blocking",syntax:["async <command> [<command> ...]"],examples:["async command1 command2","async fetchData processData","async animateIn showContent"],sideEffects:["async-execution"]}),Hr({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"}},Pr(t,"AsyncCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),qo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(r))return this.defaultElementValue(t,r,n);throw Error("Invalid target type: "+typeof r)}defaultVariable(e,t,r){const n=Gn(t,e);return void 0!==n?{target:t,value:r,wasSet:!1,existingValue:n,targetType:"variable"}:(Yn(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=Xr(t,e),i=Mn(o,r),s=`${t} ${r}`;return Dn(i)?(Vn(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 Dn(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"}}},Pr(t,"DefaultCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());class Fo{constructor(){this.name="pseudo-command"}get metadata(){return Fo.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 Uo(){return new Fo}Fo.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 Ho=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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=Gr(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")}},Pr(t,"TellCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());let Wo=(()=>{let e,t,r=[Wr({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"]}),Hr({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(zr(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&zr(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(zr(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}},Pr(t,"CopyCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})();const Jo=Jr(Wo),zo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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}}},Pr(t,"PickCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})()),Zo=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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}},Pr(t,"ThrowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());const Go=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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":zr(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(zr(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+""}},Pr(t,"BeepCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());class Yo{constructor(){this.name="install"}get metadata(){return Yo.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(zr(e))return[e];throw Error('No target specified and "me" is not available in context')}if(zr(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>zr(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(zr(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=>zr(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=>zr(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(zr(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 Xo(){return new Yo}Yo.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 Ko=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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=Zr(e.source,t),n=Zr(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+"")}},Pr(t,"TakeCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());class Qo{constructor(){this.name="render"}get metadata(){return Qo.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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}function ei(){return new Qo}Qo.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 ti extends Mr{constructor(e={}){const t=e.registry||new Lr;let r;e.registry||(t.register(rn()),t.register(on()),t.register(xn()),t.register(Tn()),t.register(Jn()),t.register(zn()),t.register(Kn()),t.register(ro()),t.register(no()),t.register(oo()),t.register(so()),t.register(ao()),t.register(co()),t.register(fo()),t.register(mo()),t.register(po()),t.register(vo()),t.register(wo()),t.register(Ao()),t.register(To()),t.register(Oo()),t.register(Co()),t.register(ko()),t.register(Lo()),t.register(Ro()),t.register($o()),t.register(Mo()),t.register(Vo()),t.register(Do()),t.register(_o()),t.register(Bo()),t.register(Po()),t.register(go()),t.register(qo()),t.register(Uo()),t.register(Ho()),t.register(Jo()),t.register(zo()),t.register(Zo()),t.register(Go()),t.register(Xo()),t.register(Ko()),t.register(ei()),console.log("RuntimeExperimental: Registered 43 V2 commands (Phase 6 COMPLETE - All commands migrated)")),r=e.expressionEvaluator?e.expressionEvaluator:e.lazyLoad?new Dr({preload:e.expressionPreload||"core"}):new Nr;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 ri=Jr((()=>{let e,t,r=[Wr({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"]}),Hr({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}},Pr(t,"GetCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;_r(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}),Br(t,n)})(),t})());function ni(){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="lokascript-multilingual.js"><\/script>')}const oi=["en","ja","ar","es","ko","zh","tr","pt","fr","de","id","qu","sw"],ii=function(e,t={}){const r=new Lr;for(const t of e)r.register(t);return new ti({...t,registry:r})}([rn(),on(),xn(),Tn(),Jn(),zn(),Kn(),ro(),no(),oo(),ri(),so(),ao(),Lo(),qo(),_o(),fo(),mo(),po(),vo(),wo(),Ao(),To(),Oo(),Co(),ko(),go(),Zo(),Ro(),Uo(),$o(),Mo(),Vo(),Do(),Ko(),Bo(),Po(),co(),Ho(),Jo(),zo(),Go(),Xo(),ei()],{expressionPreload:"all"}),si={async execute(e,t,r){const n=ni(),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 ii.execute(i.ast,s)},parse(e,t){const r=ni(),n=r.createSemanticAnalyzer().analyze(e,t);return.5>n.confidence||!n.node?null:r.buildAST(n.node).ast},translate:(e,t,r)=>ni().translate(e,t,r),getAllTranslations:(e,t)=>ni().getAllTranslations(e,t),createContext:b,runtime:ii,version:"1.0.0-multilingual",commands:["hide","show","add","remove","toggle","put","make","wait","fetch","set","get","increment","decrement","bind","default","persist","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:oi,bundleType:"multilingual",processNode:async e=>{e===document||e===document.documentElement?await ui():e instanceof HTMLElement&&await li(e)},process:async e=>si.processNode(e)},ai=new WeakSet;let ci=null;async function li(e){if(ai.has(e))return;const t=e.getAttribute("_");if(t)try{const r=function(e){const t=e.getAttribute("data-lang");if(t&&oi.includes(t))return t;let r=e;for(;r;){const e=r.getAttribute("lang");if(e){const t=e.split("-")[0].toLowerCase();if(oi.includes(t))return t}r=r.parentElement}return"en"}(e);m(`ATTR-ML: Processing element with lang="${r}":`,t.substring(0,60));const n=ni(),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 ii.execute(i.ast,s),ai.add(e),m("ATTR-ML: Successfully processed element")}catch(e){m("ATTR-ML: Error processing element:",e.message)}}async function ui(){const e=document.querySelectorAll("[_]");m(`ATTR-ML: Found ${e.length} elements with _ attributes`);const t=[];e.forEach(e=>{e instanceof HTMLElement&&t.push(li(e))}),await Promise.all(t),m("ATTR-ML: All elements processed"),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("lokascript:initialized",{detail:{elementsProcessed:e.length}}))}function fi(){"undefined"!=typeof MutationObserver&&(ci=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;t.getAttribute?.("_")&&li(t).catch(e=>{m("ATTR-ML: Error processing dynamic element:",e)});const r=t.querySelectorAll?.("[_]");r?.forEach(e=>{e instanceof HTMLElement&&li(e).catch(e=>{m("ATTR-ML: Error processing dynamic descendant:",e)})})})}),ci.observe(document.body,{childList:!0,subtree:!0}))}return"undefined"!=typeof window&&(window.lokascript=si,void 0===window.hyperfixi&&Object.defineProperty(window,"hyperfixi",{get:()=>(console.warn("[DEPRECATED] window.hyperfixi is deprecated and will be removed in v2.0.0. Please use window.lokascript instead."),window.lokascript),enumerable:!0,configurable:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ui().then(()=>fi())}):ui().then(()=>fi())),e.default=si,e.hyperfixi=si,Object.defineProperty(e,"m",{value:!0}),e}({});
2
2
  //# sourceMappingURL=lokascript-multilingual.js.map