zero-query 0.9.6 → 0.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/zquery.dist.zip +0 -0
- package/dist/zquery.js +40 -2
- package/dist/zquery.min.js +2 -2
- package/index.d.ts +1 -1
- package/index.js +1 -0
- package/package.json +1 -1
- package/src/http.js +37 -0
- package/tests/http.test.js +200 -0
- package/types/http.d.ts +15 -4
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
</p>
|
|
17
17
|
|
|
18
|
-
> **Lightweight, zero-dependency frontend library that combines jQuery-style DOM manipulation with a modern reactive component system, SPA router, global state management, HTTP client, and utility toolkit — all in a single ~
|
|
18
|
+
> **Lightweight, zero-dependency frontend library that combines jQuery-style DOM manipulation with a modern reactive component system, SPA router, global state management, HTTP client, and utility toolkit — all in a single ~100 KB minified browser bundle. Works out of the box with ES modules. An optional CLI bundler is available for single-file production builds.**
|
|
19
19
|
|
|
20
20
|
## Features
|
|
21
21
|
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
| **Reactive** | Deep proxy reactivity, Signals (`.value`, `.peek()`), computed values, effects (auto-tracked with dispose) |
|
|
28
28
|
| **Store** | Reactive global state, named actions, computed getters, middleware, subscriptions, action history, snapshots |
|
|
29
29
|
| **Selectors & DOM** | jQuery-like chainable selectors, traversal, DOM manipulation, events, animation |
|
|
30
|
-
| **HTTP** | Fetch wrapper with auto-JSON, interceptors, timeout/abort, base URL |
|
|
30
|
+
| **HTTP** | Fetch wrapper with auto-JSON, interceptors (with unsubscribe & clear), HEAD requests, parallel requests (`http.all`), config inspection (`getConfig`), timeout/abort, base URL |
|
|
31
31
|
| **Utils** | debounce, throttle, pipe, once, sleep, memoize, escapeHtml, stripHtml, uuid, capitalize, truncate, range, chunk, groupBy, unique, pick, omit, getPath/setPath, isEmpty, clamp, retry, timeout, deepClone, deepMerge, storage/session wrappers, event bus |
|
|
32
32
|
| **Dev Tools** | CLI dev server with live-reload, CSS hot-swap, full-screen error overlay, floating toolbar, dark-themed inspector panel (Router view, DOM tree, network log, component viewer, performance dashboard), fetch interceptor, render instrumentation, CLI bundler for single-file production builds |
|
|
33
33
|
|
|
@@ -75,7 +75,7 @@ If you prefer **zero tooling**, download `dist/zquery.min.js` from the [dist/ fo
|
|
|
75
75
|
git clone https://github.com/tonywied17/zero-query.git
|
|
76
76
|
cd zero-query
|
|
77
77
|
npx zquery build
|
|
78
|
-
# → dist/zquery.min.js (~
|
|
78
|
+
# → dist/zquery.min.js (~100 KB)
|
|
79
79
|
```
|
|
80
80
|
|
|
81
81
|
### Include in HTML
|
|
@@ -261,7 +261,7 @@ location / {
|
|
|
261
261
|
| `$.style` | Dynamically load global stylesheet file(s) at runtime |
|
|
262
262
|
| `$.router` `$.getRouter` | SPA router |
|
|
263
263
|
| `$.store` `$.getStore` | State management |
|
|
264
|
-
| `$.http` `$.get` `$.post` `$.put` `$.patch` `$.delete` | HTTP client |
|
|
264
|
+
| `$.http` `$.get` `$.post` `$.put` `$.patch` `$.delete` `$.head` | HTTP client |
|
|
265
265
|
| `$.reactive` `$.Signal` `$.signal` `$.computed` `$.effect` | Reactive primitives |
|
|
266
266
|
| `$.debounce` `$.throttle` `$.pipe` `$.once` `$.sleep` `$.memoize` | Function utils |
|
|
267
267
|
| `$.escapeHtml` `$.stripHtml` `$.html` `$.trust` `$.TrustedHTML` `$.uuid` `$.camelCase` `$.kebabCase` `$.capitalize` `$.truncate` | String utils |
|
|
@@ -271,7 +271,7 @@ location / {
|
|
|
271
271
|
| `$.retry` `$.timeout` | Async utils |
|
|
272
272
|
| `$.param` `$.parseQuery` | URL utils |
|
|
273
273
|
| `$.storage` `$.session` | Storage wrappers |
|
|
274
|
-
| `$.EventBus` `$.bus` | Event bus || `$.onError` `$.ZQueryError` `$.ErrorCode` `$.guardCallback` `$.validate` | Error handling || `$.version` | Library version |\n| `$.libSize` | Minified bundle size string (e.g. `\"~
|
|
274
|
+
| `$.EventBus` `$.bus` | Event bus || `$.onError` `$.ZQueryError` `$.ErrorCode` `$.guardCallback` `$.validate` | Error handling || `$.version` | Library version |\n| `$.libSize` | Minified bundle size string (e.g. `\"~100 KB\"`) |
|
|
275
275
|
| `$.meta` | Build metadata (populated by CLI bundler) |
|
|
276
276
|
| `$.noConflict` | Release `$` global |
|
|
277
277
|
|
package/dist/zquery.dist.zip
CHANGED
|
Binary file
|
package/dist/zquery.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* zQuery (zeroQuery) v0.9.
|
|
2
|
+
* zQuery (zeroQuery) v0.9.7
|
|
3
3
|
* Lightweight Frontend Library
|
|
4
4
|
* https://github.com/tonywied17/zero-query
|
|
5
5
|
* (c) 2026 Anthony Wiedman - MIT License
|
|
@@ -5127,6 +5127,7 @@ const http = {
|
|
|
5127
5127
|
put: (url, data, opts) => request('PUT', url, data, opts),
|
|
5128
5128
|
patch: (url, data, opts) => request('PATCH', url, data, opts),
|
|
5129
5129
|
delete: (url, data, opts) => request('DELETE', url, data, opts),
|
|
5130
|
+
head: (url, opts) => request('HEAD', url, undefined, opts),
|
|
5130
5131
|
|
|
5131
5132
|
/**
|
|
5132
5133
|
* Configure defaults
|
|
@@ -5137,20 +5138,56 @@ const http = {
|
|
|
5137
5138
|
if (opts.timeout !== undefined) _config.timeout = opts.timeout;
|
|
5138
5139
|
},
|
|
5139
5140
|
|
|
5141
|
+
/**
|
|
5142
|
+
* Read-only snapshot of current configuration
|
|
5143
|
+
*/
|
|
5144
|
+
getConfig() {
|
|
5145
|
+
return {
|
|
5146
|
+
baseURL: _config.baseURL,
|
|
5147
|
+
headers: { ..._config.headers },
|
|
5148
|
+
timeout: _config.timeout,
|
|
5149
|
+
};
|
|
5150
|
+
},
|
|
5151
|
+
|
|
5140
5152
|
/**
|
|
5141
5153
|
* Add request interceptor
|
|
5142
5154
|
* @param {Function} fn — (fetchOpts, url) → void | false | { url, options }
|
|
5155
|
+
* @returns {Function} unsubscribe function
|
|
5143
5156
|
*/
|
|
5144
5157
|
onRequest(fn) {
|
|
5145
5158
|
_interceptors.request.push(fn);
|
|
5159
|
+
return () => {
|
|
5160
|
+
const idx = _interceptors.request.indexOf(fn);
|
|
5161
|
+
if (idx !== -1) _interceptors.request.splice(idx, 1);
|
|
5162
|
+
};
|
|
5146
5163
|
},
|
|
5147
5164
|
|
|
5148
5165
|
/**
|
|
5149
5166
|
* Add response interceptor
|
|
5150
5167
|
* @param {Function} fn — (result) → void
|
|
5168
|
+
* @returns {Function} unsubscribe function
|
|
5151
5169
|
*/
|
|
5152
5170
|
onResponse(fn) {
|
|
5153
5171
|
_interceptors.response.push(fn);
|
|
5172
|
+
return () => {
|
|
5173
|
+
const idx = _interceptors.response.indexOf(fn);
|
|
5174
|
+
if (idx !== -1) _interceptors.response.splice(idx, 1);
|
|
5175
|
+
};
|
|
5176
|
+
},
|
|
5177
|
+
|
|
5178
|
+
/**
|
|
5179
|
+
* Clear interceptors — all, or just 'request' / 'response'
|
|
5180
|
+
*/
|
|
5181
|
+
clearInterceptors(type) {
|
|
5182
|
+
if (!type || type === 'request') _interceptors.request.length = 0;
|
|
5183
|
+
if (!type || type === 'response') _interceptors.response.length = 0;
|
|
5184
|
+
},
|
|
5185
|
+
|
|
5186
|
+
/**
|
|
5187
|
+
* Run multiple requests in parallel
|
|
5188
|
+
*/
|
|
5189
|
+
all(requests) {
|
|
5190
|
+
return Promise.all(requests);
|
|
5154
5191
|
},
|
|
5155
5192
|
|
|
5156
5193
|
/**
|
|
@@ -5750,6 +5787,7 @@ $.post = http.post;
|
|
|
5750
5787
|
$.put = http.put;
|
|
5751
5788
|
$.patch = http.patch;
|
|
5752
5789
|
$.delete = http.delete;
|
|
5790
|
+
$.head = http.head;
|
|
5753
5791
|
|
|
5754
5792
|
// --- Utilities -------------------------------------------------------------
|
|
5755
5793
|
$.debounce = debounce;
|
|
@@ -5798,7 +5836,7 @@ $.guardCallback = guardCallback;
|
|
|
5798
5836
|
$.validate = validate;
|
|
5799
5837
|
|
|
5800
5838
|
// --- Meta ------------------------------------------------------------------
|
|
5801
|
-
$.version = '0.9.
|
|
5839
|
+
$.version = '0.9.7';
|
|
5802
5840
|
$.libSize = '~100 KB';
|
|
5803
5841
|
$.meta = {}; // populated at build time by CLI bundler
|
|
5804
5842
|
|
package/dist/zquery.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* zQuery (zeroQuery) v0.9.
|
|
2
|
+
* zQuery (zeroQuery) v0.9.7
|
|
3
3
|
* Lightweight Frontend Library
|
|
4
4
|
* https://github.com/tonywied17/zero-query
|
|
5
5
|
* (c) 2026 Anthony Wiedman - MIT License
|
|
6
6
|
*/
|
|
7
|
-
(function(global){'use strict';const ErrorCode=Object.freeze({REACTIVE_CALLBACK:'ZQ_REACTIVE_CALLBACK',SIGNAL_CALLBACK:'ZQ_SIGNAL_CALLBACK',EFFECT_EXEC:'ZQ_EFFECT_EXEC',EXPR_PARSE:'ZQ_EXPR_PARSE',EXPR_EVAL:'ZQ_EXPR_EVAL',EXPR_UNSAFE_ACCESS:'ZQ_EXPR_UNSAFE_ACCESS',COMP_INVALID_NAME:'ZQ_COMP_INVALID_NAME',COMP_NOT_FOUND:'ZQ_COMP_NOT_FOUND',COMP_MOUNT_TARGET:'ZQ_COMP_MOUNT_TARGET',COMP_RENDER:'ZQ_COMP_RENDER',COMP_LIFECYCLE:'ZQ_COMP_LIFECYCLE',COMP_RESOURCE:'ZQ_COMP_RESOURCE',COMP_DIRECTIVE:'ZQ_COMP_DIRECTIVE',ROUTER_LOAD:'ZQ_ROUTER_LOAD',ROUTER_GUARD:'ZQ_ROUTER_GUARD',ROUTER_RESOLVE:'ZQ_ROUTER_RESOLVE',STORE_ACTION:'ZQ_STORE_ACTION',STORE_MIDDLEWARE:'ZQ_STORE_MIDDLEWARE',STORE_SUBSCRIBE:'ZQ_STORE_SUBSCRIBE',HTTP_REQUEST:'ZQ_HTTP_REQUEST',HTTP_TIMEOUT:'ZQ_HTTP_TIMEOUT',HTTP_INTERCEPTOR:'ZQ_HTTP_INTERCEPTOR',HTTP_PARSE:'ZQ_HTTP_PARSE',INVALID_ARGUMENT:'ZQ_INVALID_ARGUMENT',});class ZQueryError extends Error{constructor(code,message,context={},cause){super(message);this.name='ZQueryError';this.code=code;this.context=context;if(cause)this.cause=cause;}}let _errorHandler=null;function onError(handler){_errorHandler=typeof handler==='function'?handler:null;}function reportError(code,message,context={},cause){const err=cause instanceof ZQueryError?cause:new ZQueryError(code,message,context,cause);if(_errorHandler){try{_errorHandler(err);}catch{}}console.error(`[zQuery ${code}] ${message}`,context,cause||'');}function guardCallback(fn,code,context={}){return(...args)=>{try{return fn(...args);}catch(err){reportError(code,err.message||'Callback error',context,err);}};}function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}return true;}};return new Proxy(target,handler);}class Signal{constructor(value){this._value=value;this._subscribers=new Set();}get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}return this._value;}set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}peek(){return this._value;}_notify(){const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}toString(){return String(this._value);}}Signal._activeEffect=null;function signal(initial){return new Signal(initial);}function computed(fn){const s=new Signal(undefined);effect(()=>{const v=fn();if(v!==s._value){s._value=v;s._notify();}});return s;}function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=execute;try{fn();}catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:(elements?[elements]:[]);this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}first(){return this.elements[0]||null;}last(){return this.elements[this.length-1]||null;}eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}siblings(selector){const sibs=[];this.elements.forEach(el=>{if(!el.parentElement)return;const all=[...el.parentElement.children].filter(c=>c!==el);sibs.push(...(selector?all.filter(c=>c.matches(selector)):all));});return new ZQueryCollection(sibs);}next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}return this.elements.some(el=>el.matches(selector));}slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}index(selector){if(selector===undefined){const el=this.first();if(!el||!el.parentElement)return-1;return Array.from(el.parentElement.children).indexOf(el);}const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}return this;}const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}return this;}hasClass(name){return this.first()?.classList.contains(name)||false;}attr(name,value){if(typeof name==='object'&&name!==null){return this.each((_,el)=>{for(const[k,v]of Object.entries(name))el.setAttribute(k,v);});}if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}css(props,value){if(typeof props==='string'&&value!==undefined){return this.each((_,el)=>{el.style[props]=value;});}if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}return this.each((_,el)=>Object.assign(el.style,props));}width(){return this.first()?.getBoundingClientRect().width;}height(){return this.first()?.getBoundingClientRect().height;}offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}innerWidth(){const el=this.first();return el?.clientWidth;}innerHeight(){const el=this.first();return el?.clientHeight;}outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}return w;}outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}return h;}html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}morph(content){return this.each((_,el)=>{_morph(el,content);});}text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);if(!w||!el.parentNode)return;el.parentNode.insertBefore(w,el);w.appendChild(el);});}remove(){return this.each((_,el)=>el.remove());}empty(){return this.each((_,el)=>{el.textContent='';});}clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}detach(){return this.each((_,el)=>el.remove());}show(display=''){return this.each((_,el)=>{el.style.display=display;});}hide(){return this.each((_,el)=>{el.style.display='none';});}toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){const wrapper=(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);};wrapper._zqOriginal=handler;wrapper._zqSelector=selectorOrHandler;el.addEventListener(evt,wrapper);if(!el._zqDelegated)el._zqDelegated=[];el._zqDelegated.push({evt,wrapper});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{el.removeEventListener(evt,handler);if(el._zqDelegated){el._zqDelegated=el._zqDelegated.filter(d=>{if(d.evt===evt&&d.wrapper._zqOriginal===handler){el.removeEventListener(evt,d.wrapper);return false;}return true;});}});});}one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}click(fn){return fn?this.on('click',fn):this.trigger('click');}submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}focus(){this.first()?.focus();return this;}blur(){this.first()?.blur();return this;}hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}animate(props,duration=300,easing='ease'){if(this.length===0)return Promise.resolve(this);return new Promise(resolve=>{let resolved=false;const count={done:0};const listeners=[];this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(!resolved&&++count.done>=this.length){resolved=true;resolve(this);}};el.addEventListener('transitionend',onEnd);listeners.push({el,onEnd});});});setTimeout(()=>{if(!resolved){resolved=true;for(const{el,onEnd}of listeners){el.removeEventListener('transitionend',onEnd);el.style.transition='';}resolve(this);}},duration+50);});}fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const cs=getComputedStyle(el);const visible=cs.opacity!=='0'&&cs.display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.qs=(sel,ctx=document)=>ctx.querySelector(sel);query.qsa=(sel,ctx=document)=>Array.from(ctx.querySelectorAll(sel));query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2).toLowerCase(),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}tokens.push({t:T.NUM,v:Number(num)});continue;}if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}i++;}i++;tokens.push({t:T.STR,v:str});continue;}if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}inner+=expr[i++];}i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}else str+=expr[i];i++;}}i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}continue;}const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if(ch==='.'&&i+2<len&&expr[i+1]==='.'&&expr[i+2]==='.'){tokens.push({t:T.OP,v:'...'});i+=3;continue;}if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}i++;}tokens.push({t:T.EOF,v:null});return tokens;}class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}peek(){return this.tokens[this.pos];}next(){return this.tokens[this.pos++];}expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}return t;}match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}return null;}parse(){const result=this.parseExpression(0);return result;}parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(0);left={type:'ternary',cond:left,truthy,falsy};continue;}}if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}break;}return left;}parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}return this.parsePostfix();}parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}continue;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}break;}return left;}_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();args.push({type:'spread',arg:this.parseExpression(0)});}else{args.push(this.parseExpression(0));}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,')');return args;}parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();elements.push({type:'spread',arg:this.parseExpression(0)});}else{elements.push(this.parseExpression(0));}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,']');return{type:'array',elements};}if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();properties.push({spread:true,value:this.parseExpression(0)});if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();continue;}const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,'}');return{type:'object',properties};}if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){let classExpr=this.parsePrimary();while(this.peek().t===T.PUNC&&this.peek().v==='.'){this.next();const prop=this.next();classExpr={type:'member',obj:classExpr,prop:prop.v,computed:false};}let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}return{type:'new',callee:classExpr,args};}if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}return{type:'ident',name:tok.v};}this.next();return{type:'literal',value:undefined};}}const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__','call','apply','bind',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;if(name==='Map')return Map;if(name==='Set')return Set;if(name==='RegExp')return RegExp;if(name==='Error')return Error;if(name==='URL')return URL;if(name==='URLSearchParams')return URLSearchParams;return undefined;}case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}return result;}case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'call':{const result=_resolveCall(node,scope,false);return result;}case'optional_call':{const calleeNode=node.callee;const args=_evalArgs(node.args,scope);if(calleeNode.type==='member'||calleeNode.type==='optional_member'){const obj=evaluate(calleeNode.obj,scope);if(obj==null)return undefined;const prop=calleeNode.computed?evaluate(calleeNode.prop,scope):calleeNode.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const callee=evaluate(calleeNode,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;return callee(...args);}case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===RegExp||Ctor===Error||Ctor===URL||Ctor===URLSearchParams){const args=_evalArgs(node.args,scope);return new Ctor(...args);}return undefined;}case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}case'array':{const arr=[];for(const e of node.elements){if(e.type==='spread'){const iterable=evaluate(e.arg,scope);if(iterable!=null&&typeof iterable[Symbol.iterator]==='function'){for(const v of iterable)arr.push(v);}}else{arr.push(evaluate(e,scope));}}return arr;}case'object':{const obj={};for(const prop of node.properties){if(prop.spread){const source=evaluate(prop.value,scope);if(source!=null&&typeof source==='object'){Object.assign(obj,source);}}else{obj[prop.key]=evaluate(prop.value,scope);}}return obj;}case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}default:return undefined;}}function _evalArgs(argNodes,scope){const result=[];for(const a of argNodes){if(a.type==='spread'){const iterable=evaluate(a.arg,scope);if(iterable!=null&&typeof iterable[Symbol.iterator]==='function'){for(const v of iterable)result.push(v);}}else{result.push(evaluate(a,scope));}}return result;}function _resolveCall(node,scope){const callee=node.callee;const args=_evalArgs(node.args,scope);if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}let ast=_astCache.get(trimmed);if(ast){_astCache.delete(trimmed);_astCache.set(trimmed,ast);}else{const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}_astCache.set(trimmed,ast);}return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}return undefined;}}let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}const nextSib=oldNode.nextSibling;_morphNode(oldParent,oldNode,newNode);cursor=nextSib;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}return result;}function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}return;}parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}return;}if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}return;}_morphChildren(oldNode,newNode);}}function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}if(same)return;}const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}const oldNames=new Array(oldLen);for(let i=0;i<oldLen;i++)oldNames[i]=oldAttrs[i].name;for(let i=oldNames.length-1;i>=0;i--){if(!newNames.has(oldNames[i])){oldEl.removeAttribute(oldNames[i]);}}}function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{if(oldEl.value!==(newEl.getAttribute('value')||'')){oldEl.value=newEl.getAttribute('value')||'';}}if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}return null;}const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}return undefined;}function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot')||'default';if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}if(definition.init){try{definition.init.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}def._templateLoaded=true;}if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}def._styleLoaded=true;}}_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});}else{html='';}html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let noScopeDepth=0;let braceDepth=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(noScopeDepth>0&&braceDepth<=noScopeDepth)noScopeDepth=0;braceDepth--;return match;}braceDepth++;const trimmed=selector.trim();if(trimmed.startsWith('@')){if(/^@(keyframes|font-face)\b/.test(trimmed)){noScopeDepth=braceDepth;}return match;}if(noScopeDepth>0&&braceDepth>noScopeDepth){return match;}return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}document.head.appendChild(styleEl);this._styleEl=styleEl;}let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el&&el!==document.activeElement){el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}return;}this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}this._outsideListeners=this._outsideListeners||[];for(const[event,bindings]of eventMap){for(const binding of bindings){if(!binding.modifiers.includes('outside'))continue;const outsideHandler=(e)=>{if(binding.el.contains(e.target))return;const match=binding.methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const fn=this[match[1]];if(typeof fn==='function')fn.call(this,e);};document.addEventListener(event,outsideHandler,true);this._outsideListeners.push({event,handler:outsideHandler});}}}_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];const hits=[];for(const binding of currentBindings){const matched=e.target.closest(binding.selector);if(!matched)continue;hits.push({...binding,matched});}hits.sort((a,b)=>{if(a.matched===b.matched)return 0;return a.matched.contains(b.matched)?1:-1;});let stoppedAt=null;for(const{selector,methodExpr,modifiers,el,matched}of hits){if(stoppedAt){let blocked=false;for(const stopped of stoppedAt){if(matched.contains(stopped)&&matched!==stopped){blocked=true;break;}}if(blocked)continue;}if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('outside')){if(el.contains(e.target))continue;}const _keyMap={enter:'Enter',escape:'Escape',tab:'Tab',space:' ',delete:'Delete|Backspace',up:'ArrowUp',down:'ArrowDown',left:'ArrowLeft',right:'ArrowRight'};let keyFiltered=false;for(const mod of modifiers){if(_keyMap[mod]){const keys=_keyMap[mod].split('|');if(!e.key||!keys.includes(e.key)){keyFiltered=true;break;}}}if(keyFiltered)continue;if(modifiers.includes('ctrl')&&!e.ctrlKey)continue;if(modifiers.includes('shift')&&!e.shiftKey)continue;if(modifiers.includes('alt')&&!e.altKey)continue;if(modifiers.includes('meta')&&!e.metaKey)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop')){e.stopPropagation();if(!stoppedAt)stoppedAt=[];stoppedAt.push(matched);}const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const isUpper=el.hasAttribute('z-uppercase');const isLower=el.hasAttribute('z-lowercase');const hasDebounce=el.hasAttribute('z-debounce');const debounceMs=hasDebounce?(parseInt(el.getAttribute('z-debounce'),10)||250):0;const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isUpper&&typeof val==='string')val=val.toUpperCase();if(isLower&&typeof val==='string')val=val.toLowerCase();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};if(hasDebounce){let timer=null;el.addEventListener(event,()=>{clearTimeout(timer);timer=setTimeout(handler,debounceMs);});}else{el.addEventListener(event,handler);}});}_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}if(!Array.isArray(list)){el.remove();continue;}const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}parent.replaceChild(fragment,el);}if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];if(this._outsideListeners){this._outsideListeners.forEach(({event,handler})=>document.removeEventListener(event,handler,true));this._outsideListeners=[];}this._delegatedEvents=null;this._eventBindings=null;const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{const dTimers=_debounceTimers.get(child);if(dTimers){for(const key in dTimers)clearTimeout(dTimers[key]);_debounceTimers.delete(child);}const tTimers=_throttleTimers.get(child);if(tTimers){for(const key in tTimers)clearTimeout(tTimers[key]);_throttleTimers.delete(child);}});if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}_registry.set(name,definition);}function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}catch{props[propName]=attr.value;}}return;}try{props[attr.name]=JSON.parse(attr.value);}catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}function getRegistry(){return Object.fromEntries(_registry);}async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}const _ZQ_STATE_KEY='__zq';function _shallowEqual(a,b){if(a===b)return true;if(!a||!b)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;for(let i=0;i<keysA.length;i++){const k=keysA[i];if(a[k]!==b[k])return false;}return true;}class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}catch{rawBase=baseEl.getAttribute('href')||'';}if(rawBase==='/')rawBase='';}}}this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}if(config.routes){config.routes.forEach(r=>this.add(r));}if(this._mode==='hash'){this._onNavEvent=()=>this._resolve();window.addEventListener('hashchange',this._onNavEvent);}else{this._onNavEvent=(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}this._resolve();};window.addEventListener('popstate',this._onNavEvent);}this._onLinkClick=(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch{}}this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}};document.addEventListener('click',this._onLinkClick);if(this._el){queueMicrotask(()=>this._resolve());}}add(route){const keys=[];const pattern=route.path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const regex=new RegExp(`^${pattern}$`);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fbKeys=[];const fbPattern=route.fallback.replace(/:(\w+)/g,(_,key)=>{fbKeys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const fbRegex=new RegExp(`^${fbPattern}$`);this._routes.push({...route,path:route.fallback,_regex:fbRegex,_keys:fbKeys});}return this;}remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}return this;}replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}return this;}_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}return p;}resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}back(){window.history.back();return this;}forward(){window.history.forward();return this;}go(n){window.history.go(n);return this;}beforeEach(fn){this._guards.before.push(fn);return this;}afterEach(fn){this._guards.after.push(fn);return this;}onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}return this;}onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}return false;}get current(){return this._current;}get base(){return this._base;}get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}return raw;}let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}return pathname;}get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=_shallowEqual(params,from.params);const sameQuery=_shallowEqual(query,from.query);if(sameParams&&sameQuery){return;}}for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}if(matched.load){try{await matched.load();}catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}if(this._instance){this._instance.destroy();this._instance=null;}const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);try{this._instance=mount(container,matched.component,props);}catch(err){reportError(ErrorCode.COMP_NOT_FOUND,`Failed to mount component for route "${matched.path}"`,{component:matched.component,path:matched.path},err);return;}if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}for(const guard of this._guards.after){await guard(to,from);}this._listeners.forEach(fn=>fn(to,from));}destroy(){if(this._onNavEvent){window.removeEventListener(this._mode==='hash'?'hashchange':'popstate',this._onNavEvent);this._onNavEvent=null;}if(this._onLinkClick){document.removeEventListener('click',this._onLinkClick);this._onLinkClick=null;}if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}function getRouter(){return _activeRouter;}class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._maxHistory=config.maxHistory||1000;this._debug=config.debug||false;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this.state=reactive(initial,(key,value,old)=>{const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(value,old,key);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});if(this._history.length>this._maxHistory){this._history.splice(0,this._history.length-this._maxHistory);}return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}Object.assign(this.state,newState);}use(fn){this._middleware.push(fn);return this;}get history(){return[...this._history];}reset(initialState){this.replaceState(initialState);this._history=[];}}let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}const store=new Store(config);_stores.set(name,store);return store;}function getStore(name='default'){return _stores.get(name)||null;}const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}fetchOpts.body=body;}if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}const controller=new AbortController();const timeout=options.timeout??_config.timeout;let timer;if(options.signal){if(typeof AbortSignal.any==='function'){fetchOpts.signal=AbortSignal.any([options.signal,controller.signal]);}else{fetchOpts.signal=controller.signal;if(options.signal.aborted){controller.abort(options.signal.reason);}else{options.signal.addEventListener('abort',()=>controller.abort(options.signal.reason),{once:true});}}}else{fetchOpts.signal=controller.signal;}let _timedOut=false;if(timeout>0){timer=setTimeout(()=>{_timedOut=true;controller.abort();},timeout);}for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){if(_timedOut){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}throw new Error(`Request aborted: ${method} ${fullURL}`);}throw err;}}const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},onRequest(fn){_interceptors.request.push(fn);},onResponse(fn){_interceptors.response.push(fn);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}return result;};}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}function escapeHtml(str){const map={'&':'&','<':'<','>':'>','"':'"',"'":'''};return String(str).replace(/[&<>"']/g,c=>map[c]);}function stripHtml(str){return String(str).replace(/<[^>]*>/g,'');}function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}class TrustedHTML{constructor(html){this._html=html;}toString(){return this._html;}}function trust(htmlStr){return new TrustedHTML(htmlStr);}function uuid(){return crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}function kebabCase(str){return str.replace(/([A-Z]+)([A-Z][a-z])/g,'$1-$2').replace(/([a-z\d])([A-Z])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){const seen=new WeakSet();function merge(tgt,src){if(seen.has(src))return tgt;seen.add(src);for(const key of Object.keys(src)){if(src[key]&&typeof src[key]==='object'&&!Array.isArray(src[key])){if(!tgt[key]||typeof tgt[key]!=='object')tgt[key]={};merge(tgt[key],src[key]);}else{tgt[key]=src[key];}}return tgt;}for(const source of sources)merge(target,source);return target;}function isEqual(a,b,_seen){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;if(Array.isArray(a)!==Array.isArray(b))return false;if(!_seen)_seen=new Set();if(_seen.has(a))return true;_seen.add(a);const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k],_seen));}function param(obj){return new URLSearchParams(obj).toString();}function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}off(event,fn){this._handlers.get(event)?.delete(fn);}emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}clear(){this._handlers.clear();}}const bus=new EventBus();function range(startOrEnd,end,step){let s,e,st;if(end===undefined){s=0;e=startOrEnd;st=1;}else{s=startOrEnd;e=end;st=step!==undefined?step:1;}if(st===0)return[];const result=[];if(st>0){for(let i=s;i<e;i+=st)result.push(i);}else{for(let i=s;i>e;i+=st)result.push(i);}return result;}function unique(arr,keyFn){if(!keyFn)return[...new Set(arr)];const seen=new Set();return arr.filter(item=>{const k=keyFn(item);if(seen.has(k))return false;seen.add(k);return true;});}function chunk(arr,size){const result=[];for(let i=0;i<arr.length;i+=size)result.push(arr.slice(i,i+size));return result;}function groupBy(arr,keyFn){const result={};for(const item of arr){const k=keyFn(item);(result[k]??=[]).push(item);}return result;}function pick(obj,keys){const result={};for(const k of keys){if(k in obj)result[k]=obj[k];}return result;}function omit(obj,keys){const exclude=new Set(keys);const result={};for(const k of Object.keys(obj)){if(!exclude.has(k))result[k]=obj[k];}return result;}function getPath(obj,path,fallback){const keys=path.split('.');let cur=obj;for(const k of keys){if(cur==null||typeof cur!=='object')return fallback;cur=cur[k];}return cur===undefined?fallback:cur;}function setPath(obj,path,value){const keys=path.split('.');let cur=obj;for(let i=0;i<keys.length-1;i++){const k=keys[i];if(cur[k]==null||typeof cur[k]!=='object')cur[k]={};cur=cur[k];}cur[keys[keys.length-1]]=value;return obj;}function isEmpty(val){if(val==null)return true;if(typeof val==='string'||Array.isArray(val))return val.length===0;if(val instanceof Map||val instanceof Set)return val.size===0;if(typeof val==='object')return Object.keys(val).length===0;return false;}function capitalize(str){if(!str)return'';return str[0].toUpperCase()+str.slice(1).toLowerCase();}function truncate(str,maxLen,suffix='…'){if(str.length<=maxLen)return str;const end=Math.max(0,maxLen-suffix.length);return str.slice(0,end)+suffix;}function clamp(val,min,max){return val<min?min:val>max?max:val;}function memoize(fn,keyFnOrOpts){let keyFn,maxSize=0;if(typeof keyFnOrOpts==='function')keyFn=keyFnOrOpts;else if(keyFnOrOpts&&typeof keyFnOrOpts==='object')maxSize=keyFnOrOpts.maxSize||0;const cache=new Map();const memoized=(...args)=>{const key=keyFn?keyFn(...args):args[0];if(cache.has(key))return cache.get(key);const result=fn(...args);cache.set(key,result);if(maxSize>0&&cache.size>maxSize){cache.delete(cache.keys().next().value);}return result;};memoized.clear=()=>cache.clear();return memoized;}function retry(fn,opts={}){const{attempts=3,delay=1000,backoff=1}=opts;return new Promise((resolve,reject)=>{let attempt=0,currentDelay=delay;const tryOnce=()=>{attempt++;fn(attempt).then(resolve,(err)=>{if(attempt>=attempts)return reject(err);const d=currentDelay;currentDelay*=backoff;setTimeout(tryOnce,d);});};tryOnce();});}function timeout(promise,ms,message){let timer;const race=Promise.race([promise,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message||`Timed out after ${ms}ms`)),ms);})]);return race.finally(()=>clearTimeout(timer));}function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}return query(selector,context);}$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.qs=query.qs;$.qsa=query.qsa;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.stripHtml=stripHtml;$.html=html;$.trust=trust;$.TrustedHTML=TrustedHTML;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.EventBus=EventBus;$.bus=bus;$.range=range;$.unique=unique;$.chunk=chunk;$.groupBy=groupBy;$.pick=pick;$.omit=omit;$.getPath=getPath;$.setPath=setPath;$.isEmpty=isEmpty;$.capitalize=capitalize;$.truncate=truncate;$.clamp=clamp;$.memoize=memoize;$.retry=retry;$.timeout=timeout;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.9.6';$.libSize='~100 KB';$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}$;})(typeof window!=='undefined'?window:globalThis);
|
|
7
|
+
(function(global){'use strict';const ErrorCode=Object.freeze({REACTIVE_CALLBACK:'ZQ_REACTIVE_CALLBACK',SIGNAL_CALLBACK:'ZQ_SIGNAL_CALLBACK',EFFECT_EXEC:'ZQ_EFFECT_EXEC',EXPR_PARSE:'ZQ_EXPR_PARSE',EXPR_EVAL:'ZQ_EXPR_EVAL',EXPR_UNSAFE_ACCESS:'ZQ_EXPR_UNSAFE_ACCESS',COMP_INVALID_NAME:'ZQ_COMP_INVALID_NAME',COMP_NOT_FOUND:'ZQ_COMP_NOT_FOUND',COMP_MOUNT_TARGET:'ZQ_COMP_MOUNT_TARGET',COMP_RENDER:'ZQ_COMP_RENDER',COMP_LIFECYCLE:'ZQ_COMP_LIFECYCLE',COMP_RESOURCE:'ZQ_COMP_RESOURCE',COMP_DIRECTIVE:'ZQ_COMP_DIRECTIVE',ROUTER_LOAD:'ZQ_ROUTER_LOAD',ROUTER_GUARD:'ZQ_ROUTER_GUARD',ROUTER_RESOLVE:'ZQ_ROUTER_RESOLVE',STORE_ACTION:'ZQ_STORE_ACTION',STORE_MIDDLEWARE:'ZQ_STORE_MIDDLEWARE',STORE_SUBSCRIBE:'ZQ_STORE_SUBSCRIBE',HTTP_REQUEST:'ZQ_HTTP_REQUEST',HTTP_TIMEOUT:'ZQ_HTTP_TIMEOUT',HTTP_INTERCEPTOR:'ZQ_HTTP_INTERCEPTOR',HTTP_PARSE:'ZQ_HTTP_PARSE',INVALID_ARGUMENT:'ZQ_INVALID_ARGUMENT',});class ZQueryError extends Error{constructor(code,message,context={},cause){super(message);this.name='ZQueryError';this.code=code;this.context=context;if(cause)this.cause=cause;}}let _errorHandler=null;function onError(handler){_errorHandler=typeof handler==='function'?handler:null;}function reportError(code,message,context={},cause){const err=cause instanceof ZQueryError?cause:new ZQueryError(code,message,context,cause);if(_errorHandler){try{_errorHandler(err);}catch{}}console.error(`[zQuery ${code}] ${message}`,context,cause||'');}function guardCallback(fn,code,context={}){return(...args)=>{try{return fn(...args);}catch(err){reportError(code,err.message||'Callback error',context,err);}};}function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}return true;}};return new Proxy(target,handler);}class Signal{constructor(value){this._value=value;this._subscribers=new Set();}get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}return this._value;}set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}peek(){return this._value;}_notify(){const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}toString(){return String(this._value);}}Signal._activeEffect=null;function signal(initial){return new Signal(initial);}function computed(fn){const s=new Signal(undefined);effect(()=>{const v=fn();if(v!==s._value){s._value=v;s._notify();}});return s;}function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=execute;try{fn();}catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:(elements?[elements]:[]);this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}first(){return this.elements[0]||null;}last(){return this.elements[this.length-1]||null;}eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}siblings(selector){const sibs=[];this.elements.forEach(el=>{if(!el.parentElement)return;const all=[...el.parentElement.children].filter(c=>c!==el);sibs.push(...(selector?all.filter(c=>c.matches(selector)):all));});return new ZQueryCollection(sibs);}next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}return this.elements.some(el=>el.matches(selector));}slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}index(selector){if(selector===undefined){const el=this.first();if(!el||!el.parentElement)return-1;return Array.from(el.parentElement.children).indexOf(el);}const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}return this;}const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}return this;}hasClass(name){return this.first()?.classList.contains(name)||false;}attr(name,value){if(typeof name==='object'&&name!==null){return this.each((_,el)=>{for(const[k,v]of Object.entries(name))el.setAttribute(k,v);});}if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}css(props,value){if(typeof props==='string'&&value!==undefined){return this.each((_,el)=>{el.style[props]=value;});}if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}return this.each((_,el)=>Object.assign(el.style,props));}width(){return this.first()?.getBoundingClientRect().width;}height(){return this.first()?.getBoundingClientRect().height;}offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}innerWidth(){const el=this.first();return el?.clientWidth;}innerHeight(){const el=this.first();return el?.clientHeight;}outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}return w;}outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}return h;}html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}morph(content){return this.each((_,el)=>{_morph(el,content);});}text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);if(!w||!el.parentNode)return;el.parentNode.insertBefore(w,el);w.appendChild(el);});}remove(){return this.each((_,el)=>el.remove());}empty(){return this.each((_,el)=>{el.textContent='';});}clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}detach(){return this.each((_,el)=>el.remove());}show(display=''){return this.each((_,el)=>{el.style.display=display;});}hide(){return this.each((_,el)=>{el.style.display='none';});}toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){const wrapper=(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);};wrapper._zqOriginal=handler;wrapper._zqSelector=selectorOrHandler;el.addEventListener(evt,wrapper);if(!el._zqDelegated)el._zqDelegated=[];el._zqDelegated.push({evt,wrapper});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{el.removeEventListener(evt,handler);if(el._zqDelegated){el._zqDelegated=el._zqDelegated.filter(d=>{if(d.evt===evt&&d.wrapper._zqOriginal===handler){el.removeEventListener(evt,d.wrapper);return false;}return true;});}});});}one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}click(fn){return fn?this.on('click',fn):this.trigger('click');}submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}focus(){this.first()?.focus();return this;}blur(){this.first()?.blur();return this;}hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}animate(props,duration=300,easing='ease'){if(this.length===0)return Promise.resolve(this);return new Promise(resolve=>{let resolved=false;const count={done:0};const listeners=[];this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(!resolved&&++count.done>=this.length){resolved=true;resolve(this);}};el.addEventListener('transitionend',onEnd);listeners.push({el,onEnd});});});setTimeout(()=>{if(!resolved){resolved=true;for(const{el,onEnd}of listeners){el.removeEventListener('transitionend',onEnd);el.style.transition='';}resolve(this);}},duration+50);});}fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const cs=getComputedStyle(el);const visible=cs.opacity!=='0'&&cs.display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.qs=(sel,ctx=document)=>ctx.querySelector(sel);query.qsa=(sel,ctx=document)=>Array.from(ctx.querySelectorAll(sel));query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2).toLowerCase(),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}tokens.push({t:T.NUM,v:Number(num)});continue;}if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}i++;}i++;tokens.push({t:T.STR,v:str});continue;}if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}inner+=expr[i++];}i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}else str+=expr[i];i++;}}i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}continue;}const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if(ch==='.'&&i+2<len&&expr[i+1]==='.'&&expr[i+2]==='.'){tokens.push({t:T.OP,v:'...'});i+=3;continue;}if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}i++;}tokens.push({t:T.EOF,v:null});return tokens;}class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}peek(){return this.tokens[this.pos];}next(){return this.tokens[this.pos++];}expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}return t;}match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}return null;}parse(){const result=this.parseExpression(0);return result;}parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(0);left={type:'ternary',cond:left,truthy,falsy};continue;}}if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}break;}return left;}parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}return this.parsePostfix();}parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}continue;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}break;}return left;}_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();args.push({type:'spread',arg:this.parseExpression(0)});}else{args.push(this.parseExpression(0));}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,')');return args;}parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();elements.push({type:'spread',arg:this.parseExpression(0)});}else{elements.push(this.parseExpression(0));}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,']');return{type:'array',elements};}if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){if(this.peek().t===T.OP&&this.peek().v==='...'){this.next();properties.push({spread:true,value:this.parseExpression(0)});if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();continue;}const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,'}');return{type:'object',properties};}if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){let classExpr=this.parsePrimary();while(this.peek().t===T.PUNC&&this.peek().v==='.'){this.next();const prop=this.next();classExpr={type:'member',obj:classExpr,prop:prop.v,computed:false};}let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}return{type:'new',callee:classExpr,args};}if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}return{type:'ident',name:tok.v};}this.next();return{type:'literal',value:undefined};}}const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__','call','apply','bind',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;if(name==='Map')return Map;if(name==='Set')return Set;if(name==='RegExp')return RegExp;if(name==='Error')return Error;if(name==='URL')return URL;if(name==='URLSearchParams')return URLSearchParams;return undefined;}case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}return result;}case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'call':{const result=_resolveCall(node,scope,false);return result;}case'optional_call':{const calleeNode=node.callee;const args=_evalArgs(node.args,scope);if(calleeNode.type==='member'||calleeNode.type==='optional_member'){const obj=evaluate(calleeNode.obj,scope);if(obj==null)return undefined;const prop=calleeNode.computed?evaluate(calleeNode.prop,scope):calleeNode.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const callee=evaluate(calleeNode,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;return callee(...args);}case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===RegExp||Ctor===Error||Ctor===URL||Ctor===URLSearchParams){const args=_evalArgs(node.args,scope);return new Ctor(...args);}return undefined;}case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}case'array':{const arr=[];for(const e of node.elements){if(e.type==='spread'){const iterable=evaluate(e.arg,scope);if(iterable!=null&&typeof iterable[Symbol.iterator]==='function'){for(const v of iterable)arr.push(v);}}else{arr.push(evaluate(e,scope));}}return arr;}case'object':{const obj={};for(const prop of node.properties){if(prop.spread){const source=evaluate(prop.value,scope);if(source!=null&&typeof source==='object'){Object.assign(obj,source);}}else{obj[prop.key]=evaluate(prop.value,scope);}}return obj;}case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}default:return undefined;}}function _evalArgs(argNodes,scope){const result=[];for(const a of argNodes){if(a.type==='spread'){const iterable=evaluate(a.arg,scope);if(iterable!=null&&typeof iterable[Symbol.iterator]==='function'){for(const v of iterable)result.push(v);}}else{result.push(evaluate(a,scope));}}return result;}function _resolveCall(node,scope){const callee=node.callee;const args=_evalArgs(node.args,scope);if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}let ast=_astCache.get(trimmed);if(ast){_astCache.delete(trimmed);_astCache.set(trimmed,ast);}else{const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}_astCache.set(trimmed,ast);}return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}return undefined;}}let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}const nextSib=oldNode.nextSibling;_morphNode(oldParent,oldNode,newNode);cursor=nextSib;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}return result;}function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}return;}parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}return;}if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}return;}_morphChildren(oldNode,newNode);}}function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}if(same)return;}const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}const oldNames=new Array(oldLen);for(let i=0;i<oldLen;i++)oldNames[i]=oldAttrs[i].name;for(let i=oldNames.length-1;i>=0;i--){if(!newNames.has(oldNames[i])){oldEl.removeAttribute(oldNames[i]);}}}function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{if(oldEl.value!==(newEl.getAttribute('value')||'')){oldEl.value=newEl.getAttribute('value')||'';}}if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}return null;}const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}return undefined;}function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot')||'default';if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}if(definition.init){try{definition.init.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}def._templateLoaded=true;}if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}def._styleLoaded=true;}}_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});}else{html='';}html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let noScopeDepth=0;let braceDepth=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(noScopeDepth>0&&braceDepth<=noScopeDepth)noScopeDepth=0;braceDepth--;return match;}braceDepth++;const trimmed=selector.trim();if(trimmed.startsWith('@')){if(/^@(keyframes|font-face)\b/.test(trimmed)){noScopeDepth=braceDepth;}return match;}if(noScopeDepth>0&&braceDepth>noScopeDepth){return match;}return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}document.head.appendChild(styleEl);this._styleEl=styleEl;}let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el&&el!==document.activeElement){el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}return;}this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}this._outsideListeners=this._outsideListeners||[];for(const[event,bindings]of eventMap){for(const binding of bindings){if(!binding.modifiers.includes('outside'))continue;const outsideHandler=(e)=>{if(binding.el.contains(e.target))return;const match=binding.methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const fn=this[match[1]];if(typeof fn==='function')fn.call(this,e);};document.addEventListener(event,outsideHandler,true);this._outsideListeners.push({event,handler:outsideHandler});}}}_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];const hits=[];for(const binding of currentBindings){const matched=e.target.closest(binding.selector);if(!matched)continue;hits.push({...binding,matched});}hits.sort((a,b)=>{if(a.matched===b.matched)return 0;return a.matched.contains(b.matched)?1:-1;});let stoppedAt=null;for(const{selector,methodExpr,modifiers,el,matched}of hits){if(stoppedAt){let blocked=false;for(const stopped of stoppedAt){if(matched.contains(stopped)&&matched!==stopped){blocked=true;break;}}if(blocked)continue;}if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('outside')){if(el.contains(e.target))continue;}const _keyMap={enter:'Enter',escape:'Escape',tab:'Tab',space:' ',delete:'Delete|Backspace',up:'ArrowUp',down:'ArrowDown',left:'ArrowLeft',right:'ArrowRight'};let keyFiltered=false;for(const mod of modifiers){if(_keyMap[mod]){const keys=_keyMap[mod].split('|');if(!e.key||!keys.includes(e.key)){keyFiltered=true;break;}}}if(keyFiltered)continue;if(modifiers.includes('ctrl')&&!e.ctrlKey)continue;if(modifiers.includes('shift')&&!e.shiftKey)continue;if(modifiers.includes('alt')&&!e.altKey)continue;if(modifiers.includes('meta')&&!e.metaKey)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop')){e.stopPropagation();if(!stoppedAt)stoppedAt=[];stoppedAt.push(matched);}const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const isUpper=el.hasAttribute('z-uppercase');const isLower=el.hasAttribute('z-lowercase');const hasDebounce=el.hasAttribute('z-debounce');const debounceMs=hasDebounce?(parseInt(el.getAttribute('z-debounce'),10)||250):0;const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isUpper&&typeof val==='string')val=val.toUpperCase();if(isLower&&typeof val==='string')val=val.toLowerCase();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};if(hasDebounce){let timer=null;el.addEventListener(event,()=>{clearTimeout(timer);timer=setTimeout(handler,debounceMs);});}else{el.addEventListener(event,handler);}});}_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}if(!Array.isArray(list)){el.remove();continue;}const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}parent.replaceChild(fragment,el);}if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];if(this._outsideListeners){this._outsideListeners.forEach(({event,handler})=>document.removeEventListener(event,handler,true));this._outsideListeners=[];}this._delegatedEvents=null;this._eventBindings=null;const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{const dTimers=_debounceTimers.get(child);if(dTimers){for(const key in dTimers)clearTimeout(dTimers[key]);_debounceTimers.delete(child);}const tTimers=_throttleTimers.get(child);if(tTimers){for(const key in tTimers)clearTimeout(tTimers[key]);_throttleTimers.delete(child);}});if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}_registry.set(name,definition);}function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}catch{props[propName]=attr.value;}}return;}try{props[attr.name]=JSON.parse(attr.value);}catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}function getRegistry(){return Object.fromEntries(_registry);}async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}const _ZQ_STATE_KEY='__zq';function _shallowEqual(a,b){if(a===b)return true;if(!a||!b)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;for(let i=0;i<keysA.length;i++){const k=keysA[i];if(a[k]!==b[k])return false;}return true;}class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}catch{rawBase=baseEl.getAttribute('href')||'';}if(rawBase==='/')rawBase='';}}}this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}if(config.routes){config.routes.forEach(r=>this.add(r));}if(this._mode==='hash'){this._onNavEvent=()=>this._resolve();window.addEventListener('hashchange',this._onNavEvent);}else{this._onNavEvent=(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}this._resolve();};window.addEventListener('popstate',this._onNavEvent);}this._onLinkClick=(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch{}}this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}};document.addEventListener('click',this._onLinkClick);if(this._el){queueMicrotask(()=>this._resolve());}}add(route){const keys=[];const pattern=route.path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const regex=new RegExp(`^${pattern}$`);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fbKeys=[];const fbPattern=route.fallback.replace(/:(\w+)/g,(_,key)=>{fbKeys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const fbRegex=new RegExp(`^${fbPattern}$`);this._routes.push({...route,path:route.fallback,_regex:fbRegex,_keys:fbKeys});}return this;}remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}return this;}replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}return this;}_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}return p;}resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}back(){window.history.back();return this;}forward(){window.history.forward();return this;}go(n){window.history.go(n);return this;}beforeEach(fn){this._guards.before.push(fn);return this;}afterEach(fn){this._guards.after.push(fn);return this;}onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}return this;}onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}return false;}get current(){return this._current;}get base(){return this._base;}get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}return raw;}let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}return pathname;}get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=_shallowEqual(params,from.params);const sameQuery=_shallowEqual(query,from.query);if(sameParams&&sameQuery){return;}}for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}if(matched.load){try{await matched.load();}catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}if(this._instance){this._instance.destroy();this._instance=null;}const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);try{this._instance=mount(container,matched.component,props);}catch(err){reportError(ErrorCode.COMP_NOT_FOUND,`Failed to mount component for route "${matched.path}"`,{component:matched.component,path:matched.path},err);return;}if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}for(const guard of this._guards.after){await guard(to,from);}this._listeners.forEach(fn=>fn(to,from));}destroy(){if(this._onNavEvent){window.removeEventListener(this._mode==='hash'?'hashchange':'popstate',this._onNavEvent);this._onNavEvent=null;}if(this._onLinkClick){document.removeEventListener('click',this._onLinkClick);this._onLinkClick=null;}if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}function getRouter(){return _activeRouter;}class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._maxHistory=config.maxHistory||1000;this._debug=config.debug||false;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this.state=reactive(initial,(key,value,old)=>{const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(value,old,key);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});if(this._history.length>this._maxHistory){this._history.splice(0,this._history.length-this._maxHistory);}return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}Object.assign(this.state,newState);}use(fn){this._middleware.push(fn);return this;}get history(){return[...this._history];}reset(initialState){this.replaceState(initialState);this._history=[];}}let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}const store=new Store(config);_stores.set(name,store);return store;}function getStore(name='default'){return _stores.get(name)||null;}const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}fetchOpts.body=body;}if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}const controller=new AbortController();const timeout=options.timeout??_config.timeout;let timer;if(options.signal){if(typeof AbortSignal.any==='function'){fetchOpts.signal=AbortSignal.any([options.signal,controller.signal]);}else{fetchOpts.signal=controller.signal;if(options.signal.aborted){controller.abort(options.signal.reason);}else{options.signal.addEventListener('abort',()=>controller.abort(options.signal.reason),{once:true});}}}else{fetchOpts.signal=controller.signal;}let _timedOut=false;if(timeout>0){timer=setTimeout(()=>{_timedOut=true;controller.abort();},timeout);}for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){if(_timedOut){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}throw new Error(`Request aborted: ${method} ${fullURL}`);}throw err;}}const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),head:(url,opts)=>request('HEAD',url,undefined,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},getConfig(){return{baseURL:_config.baseURL,headers:{..._config.headers},timeout:_config.timeout,};},onRequest(fn){_interceptors.request.push(fn);return()=>{const idx=_interceptors.request.indexOf(fn);if(idx!==-1)_interceptors.request.splice(idx,1);};},onResponse(fn){_interceptors.response.push(fn);return()=>{const idx=_interceptors.response.indexOf(fn);if(idx!==-1)_interceptors.response.splice(idx,1);};},clearInterceptors(type){if(!type||type==='request')_interceptors.request.length=0;if(!type||type==='response')_interceptors.response.length=0;},all(requests){return Promise.all(requests);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}return result;};}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}function escapeHtml(str){const map={'&':'&','<':'<','>':'>','"':'"',"'":'''};return String(str).replace(/[&<>"']/g,c=>map[c]);}function stripHtml(str){return String(str).replace(/<[^>]*>/g,'');}function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}class TrustedHTML{constructor(html){this._html=html;}toString(){return this._html;}}function trust(htmlStr){return new TrustedHTML(htmlStr);}function uuid(){return crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}function kebabCase(str){return str.replace(/([A-Z]+)([A-Z][a-z])/g,'$1-$2').replace(/([a-z\d])([A-Z])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){const seen=new WeakSet();function merge(tgt,src){if(seen.has(src))return tgt;seen.add(src);for(const key of Object.keys(src)){if(src[key]&&typeof src[key]==='object'&&!Array.isArray(src[key])){if(!tgt[key]||typeof tgt[key]!=='object')tgt[key]={};merge(tgt[key],src[key]);}else{tgt[key]=src[key];}}return tgt;}for(const source of sources)merge(target,source);return target;}function isEqual(a,b,_seen){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;if(Array.isArray(a)!==Array.isArray(b))return false;if(!_seen)_seen=new Set();if(_seen.has(a))return true;_seen.add(a);const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k],_seen));}function param(obj){return new URLSearchParams(obj).toString();}function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}off(event,fn){this._handlers.get(event)?.delete(fn);}emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}clear(){this._handlers.clear();}}const bus=new EventBus();function range(startOrEnd,end,step){let s,e,st;if(end===undefined){s=0;e=startOrEnd;st=1;}else{s=startOrEnd;e=end;st=step!==undefined?step:1;}if(st===0)return[];const result=[];if(st>0){for(let i=s;i<e;i+=st)result.push(i);}else{for(let i=s;i>e;i+=st)result.push(i);}return result;}function unique(arr,keyFn){if(!keyFn)return[...new Set(arr)];const seen=new Set();return arr.filter(item=>{const k=keyFn(item);if(seen.has(k))return false;seen.add(k);return true;});}function chunk(arr,size){const result=[];for(let i=0;i<arr.length;i+=size)result.push(arr.slice(i,i+size));return result;}function groupBy(arr,keyFn){const result={};for(const item of arr){const k=keyFn(item);(result[k]??=[]).push(item);}return result;}function pick(obj,keys){const result={};for(const k of keys){if(k in obj)result[k]=obj[k];}return result;}function omit(obj,keys){const exclude=new Set(keys);const result={};for(const k of Object.keys(obj)){if(!exclude.has(k))result[k]=obj[k];}return result;}function getPath(obj,path,fallback){const keys=path.split('.');let cur=obj;for(const k of keys){if(cur==null||typeof cur!=='object')return fallback;cur=cur[k];}return cur===undefined?fallback:cur;}function setPath(obj,path,value){const keys=path.split('.');let cur=obj;for(let i=0;i<keys.length-1;i++){const k=keys[i];if(cur[k]==null||typeof cur[k]!=='object')cur[k]={};cur=cur[k];}cur[keys[keys.length-1]]=value;return obj;}function isEmpty(val){if(val==null)return true;if(typeof val==='string'||Array.isArray(val))return val.length===0;if(val instanceof Map||val instanceof Set)return val.size===0;if(typeof val==='object')return Object.keys(val).length===0;return false;}function capitalize(str){if(!str)return'';return str[0].toUpperCase()+str.slice(1).toLowerCase();}function truncate(str,maxLen,suffix='…'){if(str.length<=maxLen)return str;const end=Math.max(0,maxLen-suffix.length);return str.slice(0,end)+suffix;}function clamp(val,min,max){return val<min?min:val>max?max:val;}function memoize(fn,keyFnOrOpts){let keyFn,maxSize=0;if(typeof keyFnOrOpts==='function')keyFn=keyFnOrOpts;else if(keyFnOrOpts&&typeof keyFnOrOpts==='object')maxSize=keyFnOrOpts.maxSize||0;const cache=new Map();const memoized=(...args)=>{const key=keyFn?keyFn(...args):args[0];if(cache.has(key))return cache.get(key);const result=fn(...args);cache.set(key,result);if(maxSize>0&&cache.size>maxSize){cache.delete(cache.keys().next().value);}return result;};memoized.clear=()=>cache.clear();return memoized;}function retry(fn,opts={}){const{attempts=3,delay=1000,backoff=1}=opts;return new Promise((resolve,reject)=>{let attempt=0,currentDelay=delay;const tryOnce=()=>{attempt++;fn(attempt).then(resolve,(err)=>{if(attempt>=attempts)return reject(err);const d=currentDelay;currentDelay*=backoff;setTimeout(tryOnce,d);});};tryOnce();});}function timeout(promise,ms,message){let timer;const race=Promise.race([promise,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message||`Timed out after ${ms}ms`)),ms);})]);return race.finally(()=>clearTimeout(timer));}function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}return query(selector,context);}$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.qs=query.qs;$.qsa=query.qsa;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.head=http.head;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.stripHtml=stripHtml;$.html=html;$.trust=trust;$.TrustedHTML=TrustedHTML;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.EventBus=EventBus;$.bus=bus;$.range=range;$.unique=unique;$.chunk=chunk;$.groupBy=groupBy;$.pick=pick;$.omit=omit;$.getPath=getPath;$.setPath=setPath;$.isEmpty=isEmpty;$.capitalize=capitalize;$.truncate=truncate;$.clamp=clamp;$.memoize=memoize;$.retry=retry;$.timeout=timeout;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.9.7';$.libSize='~100 KB';$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}$;})(typeof window!=='undefined'?window:globalThis);
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zero-query",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.7",
|
|
4
4
|
"description": "Lightweight modern frontend library — jQuery-like selectors, reactive components, SPA router, and state management with zero dependencies.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
package/src/http.js
CHANGED
|
@@ -165,6 +165,7 @@ export const http = {
|
|
|
165
165
|
put: (url, data, opts) => request('PUT', url, data, opts),
|
|
166
166
|
patch: (url, data, opts) => request('PATCH', url, data, opts),
|
|
167
167
|
delete: (url, data, opts) => request('DELETE', url, data, opts),
|
|
168
|
+
head: (url, opts) => request('HEAD', url, undefined, opts),
|
|
168
169
|
|
|
169
170
|
/**
|
|
170
171
|
* Configure defaults
|
|
@@ -175,20 +176,56 @@ export const http = {
|
|
|
175
176
|
if (opts.timeout !== undefined) _config.timeout = opts.timeout;
|
|
176
177
|
},
|
|
177
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Read-only snapshot of current configuration
|
|
181
|
+
*/
|
|
182
|
+
getConfig() {
|
|
183
|
+
return {
|
|
184
|
+
baseURL: _config.baseURL,
|
|
185
|
+
headers: { ..._config.headers },
|
|
186
|
+
timeout: _config.timeout,
|
|
187
|
+
};
|
|
188
|
+
},
|
|
189
|
+
|
|
178
190
|
/**
|
|
179
191
|
* Add request interceptor
|
|
180
192
|
* @param {Function} fn — (fetchOpts, url) → void | false | { url, options }
|
|
193
|
+
* @returns {Function} unsubscribe function
|
|
181
194
|
*/
|
|
182
195
|
onRequest(fn) {
|
|
183
196
|
_interceptors.request.push(fn);
|
|
197
|
+
return () => {
|
|
198
|
+
const idx = _interceptors.request.indexOf(fn);
|
|
199
|
+
if (idx !== -1) _interceptors.request.splice(idx, 1);
|
|
200
|
+
};
|
|
184
201
|
},
|
|
185
202
|
|
|
186
203
|
/**
|
|
187
204
|
* Add response interceptor
|
|
188
205
|
* @param {Function} fn — (result) → void
|
|
206
|
+
* @returns {Function} unsubscribe function
|
|
189
207
|
*/
|
|
190
208
|
onResponse(fn) {
|
|
191
209
|
_interceptors.response.push(fn);
|
|
210
|
+
return () => {
|
|
211
|
+
const idx = _interceptors.response.indexOf(fn);
|
|
212
|
+
if (idx !== -1) _interceptors.response.splice(idx, 1);
|
|
213
|
+
};
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Clear interceptors — all, or just 'request' / 'response'
|
|
218
|
+
*/
|
|
219
|
+
clearInterceptors(type) {
|
|
220
|
+
if (!type || type === 'request') _interceptors.request.length = 0;
|
|
221
|
+
if (!type || type === 'response') _interceptors.response.length = 0;
|
|
222
|
+
},
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Run multiple requests in parallel
|
|
226
|
+
*/
|
|
227
|
+
all(requests) {
|
|
228
|
+
return Promise.all(requests);
|
|
192
229
|
},
|
|
193
230
|
|
|
194
231
|
/**
|
package/tests/http.test.js
CHANGED
|
@@ -446,3 +446,203 @@ describe('http — AbortController integration', () => {
|
|
|
446
446
|
expect(fetchSpy).toHaveBeenCalled();
|
|
447
447
|
});
|
|
448
448
|
});
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
// ===========================================================================
|
|
452
|
+
// HEAD requests
|
|
453
|
+
// ===========================================================================
|
|
454
|
+
|
|
455
|
+
describe('http.head', () => {
|
|
456
|
+
it('sends a HEAD request', async () => {
|
|
457
|
+
mockFetch({});
|
|
458
|
+
const result = await http.head('https://api.test.com/resource');
|
|
459
|
+
expect(fetchSpy.mock.calls[0][1].method).toBe('HEAD');
|
|
460
|
+
expect(result.ok).toBe(true);
|
|
461
|
+
expect(result.status).toBe(200);
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
it('does not send a body', async () => {
|
|
465
|
+
mockFetch({});
|
|
466
|
+
await http.head('https://api.test.com/resource');
|
|
467
|
+
const opts = fetchSpy.mock.calls[0][1];
|
|
468
|
+
expect(opts.body).toBeUndefined();
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
it('accepts per-request options', async () => {
|
|
472
|
+
mockFetch({});
|
|
473
|
+
await http.head('https://api.test.com/resource', {
|
|
474
|
+
headers: { 'X-Check': 'exists' },
|
|
475
|
+
});
|
|
476
|
+
const opts = fetchSpy.mock.calls[0][1];
|
|
477
|
+
expect(opts.headers['X-Check']).toBe('exists');
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it('returns response headers', async () => {
|
|
481
|
+
mockFetch({});
|
|
482
|
+
const result = await http.head('https://api.test.com/resource');
|
|
483
|
+
expect(result.headers).toBeDefined();
|
|
484
|
+
expect(typeof result.headers).toBe('object');
|
|
485
|
+
});
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
// ===========================================================================
|
|
490
|
+
// Interceptor unsubscribe
|
|
491
|
+
// ===========================================================================
|
|
492
|
+
|
|
493
|
+
describe('http — interceptor unsubscribe', () => {
|
|
494
|
+
it('onRequest returns an unsubscribe function', async () => {
|
|
495
|
+
http.clearInterceptors();
|
|
496
|
+
const spy = vi.fn();
|
|
497
|
+
const unsub = http.onRequest(spy);
|
|
498
|
+
expect(typeof unsub).toBe('function');
|
|
499
|
+
|
|
500
|
+
mockFetch({});
|
|
501
|
+
await http.get('https://api.test.com/a');
|
|
502
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
503
|
+
|
|
504
|
+
unsub();
|
|
505
|
+
await http.get('https://api.test.com/b');
|
|
506
|
+
expect(spy).toHaveBeenCalledTimes(1); // not called again
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
it('onResponse returns an unsubscribe function', async () => {
|
|
510
|
+
http.clearInterceptors();
|
|
511
|
+
const spy = vi.fn();
|
|
512
|
+
const unsub = http.onResponse(spy);
|
|
513
|
+
expect(typeof unsub).toBe('function');
|
|
514
|
+
|
|
515
|
+
mockFetch({});
|
|
516
|
+
await http.get('https://api.test.com/a');
|
|
517
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
518
|
+
|
|
519
|
+
unsub();
|
|
520
|
+
await http.get('https://api.test.com/b');
|
|
521
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
it('double-unsubscribe is safe', async () => {
|
|
525
|
+
http.clearInterceptors();
|
|
526
|
+
const spy = vi.fn();
|
|
527
|
+
const unsub = http.onRequest(spy);
|
|
528
|
+
unsub();
|
|
529
|
+
unsub(); // should not throw
|
|
530
|
+
mockFetch({});
|
|
531
|
+
await http.get('https://api.test.com/data');
|
|
532
|
+
expect(spy).not.toHaveBeenCalled();
|
|
533
|
+
});
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
// ===========================================================================
|
|
538
|
+
// clearInterceptors
|
|
539
|
+
// ===========================================================================
|
|
540
|
+
|
|
541
|
+
describe('http.clearInterceptors', () => {
|
|
542
|
+
it('clears all interceptors when called with no args', async () => {
|
|
543
|
+
http.clearInterceptors();
|
|
544
|
+
const reqSpy = vi.fn();
|
|
545
|
+
const resSpy = vi.fn();
|
|
546
|
+
http.onRequest(reqSpy);
|
|
547
|
+
http.onResponse(resSpy);
|
|
548
|
+
|
|
549
|
+
http.clearInterceptors();
|
|
550
|
+
mockFetch({});
|
|
551
|
+
await http.get('https://api.test.com/data');
|
|
552
|
+
expect(reqSpy).not.toHaveBeenCalled();
|
|
553
|
+
expect(resSpy).not.toHaveBeenCalled();
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
it('clears only request interceptors with "request"', async () => {
|
|
557
|
+
http.clearInterceptors();
|
|
558
|
+
const reqSpy = vi.fn();
|
|
559
|
+
const resSpy = vi.fn();
|
|
560
|
+
http.onRequest(reqSpy);
|
|
561
|
+
http.onResponse(resSpy);
|
|
562
|
+
|
|
563
|
+
http.clearInterceptors('request');
|
|
564
|
+
mockFetch({});
|
|
565
|
+
await http.get('https://api.test.com/data');
|
|
566
|
+
expect(reqSpy).not.toHaveBeenCalled();
|
|
567
|
+
expect(resSpy).toHaveBeenCalledTimes(1);
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
it('clears only response interceptors with "response"', async () => {
|
|
571
|
+
http.clearInterceptors();
|
|
572
|
+
const reqSpy = vi.fn();
|
|
573
|
+
const resSpy = vi.fn();
|
|
574
|
+
http.onRequest(reqSpy);
|
|
575
|
+
http.onResponse(resSpy);
|
|
576
|
+
|
|
577
|
+
http.clearInterceptors('response');
|
|
578
|
+
mockFetch({});
|
|
579
|
+
await http.get('https://api.test.com/data');
|
|
580
|
+
expect(reqSpy).toHaveBeenCalledTimes(1);
|
|
581
|
+
expect(resSpy).not.toHaveBeenCalled();
|
|
582
|
+
});
|
|
583
|
+
});
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
// ===========================================================================
|
|
587
|
+
// http.all — parallel requests
|
|
588
|
+
// ===========================================================================
|
|
589
|
+
|
|
590
|
+
describe('http.all', () => {
|
|
591
|
+
it('resolves all parallel requests', async () => {
|
|
592
|
+
mockFetch({ ok: true });
|
|
593
|
+
const results = await http.all([
|
|
594
|
+
http.get('https://api.test.com/a'),
|
|
595
|
+
http.get('https://api.test.com/b'),
|
|
596
|
+
http.get('https://api.test.com/c'),
|
|
597
|
+
]);
|
|
598
|
+
expect(results).toHaveLength(3);
|
|
599
|
+
expect(results.every(r => r.ok)).toBe(true);
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
it('rejects if any request fails', async () => {
|
|
603
|
+
http.clearInterceptors();
|
|
604
|
+
mockFetch({ error: 'fail' }, false, 500);
|
|
605
|
+
await expect(
|
|
606
|
+
http.all([
|
|
607
|
+
http.get('https://api.test.com/a'),
|
|
608
|
+
http.get('https://api.test.com/b'),
|
|
609
|
+
])
|
|
610
|
+
).rejects.toThrow();
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
it('handles empty array', async () => {
|
|
614
|
+
const results = await http.all([]);
|
|
615
|
+
expect(results).toEqual([]);
|
|
616
|
+
});
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
// ===========================================================================
|
|
621
|
+
// http.getConfig
|
|
622
|
+
// ===========================================================================
|
|
623
|
+
|
|
624
|
+
describe('http.getConfig', () => {
|
|
625
|
+
it('returns current config', () => {
|
|
626
|
+
http.configure({ baseURL: 'https://myapi.com', timeout: 5000 });
|
|
627
|
+
const config = http.getConfig();
|
|
628
|
+
expect(config.baseURL).toBe('https://myapi.com');
|
|
629
|
+
expect(config.timeout).toBe(5000);
|
|
630
|
+
expect(config.headers).toBeDefined();
|
|
631
|
+
});
|
|
632
|
+
|
|
633
|
+
it('returns a copy (not the internal reference)', () => {
|
|
634
|
+
const config = http.getConfig();
|
|
635
|
+
config.baseURL = 'https://mutated.com';
|
|
636
|
+
config.headers['X-Evil'] = 'injected';
|
|
637
|
+
const fresh = http.getConfig();
|
|
638
|
+
expect(fresh.baseURL).not.toBe('https://mutated.com');
|
|
639
|
+
expect(fresh.headers['X-Evil']).toBeUndefined();
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
it('reflects updates after configure', () => {
|
|
643
|
+
http.configure({ baseURL: '' });
|
|
644
|
+
expect(http.getConfig().baseURL).toBe('');
|
|
645
|
+
http.configure({ baseURL: 'https://updated.com' });
|
|
646
|
+
expect(http.getConfig().baseURL).toBe('https://updated.com');
|
|
647
|
+
});
|
|
648
|
+
});
|
package/types/http.d.ts
CHANGED
|
@@ -61,15 +61,26 @@ export interface HttpClient {
|
|
|
61
61
|
patch<T = any>(url: string, data?: any, opts?: HttpRequestOptions): Promise<HttpResponse<T>>;
|
|
62
62
|
/** DELETE request. */
|
|
63
63
|
delete<T = any>(url: string, data?: any, opts?: HttpRequestOptions): Promise<HttpResponse<T>>;
|
|
64
|
+
/** HEAD request — no body, useful for checking resource existence or headers. */
|
|
65
|
+
head<T = any>(url: string, opts?: HttpRequestOptions): Promise<HttpResponse<T>>;
|
|
64
66
|
|
|
65
67
|
/** Update default configuration for all subsequent requests. */
|
|
66
68
|
configure(options: HttpConfigureOptions): void;
|
|
67
69
|
|
|
68
|
-
/**
|
|
69
|
-
|
|
70
|
+
/** Read-only snapshot of the current configuration. Returns a shallow copy. */
|
|
71
|
+
getConfig(): { baseURL: string; headers: Record<string, string>; timeout: number };
|
|
70
72
|
|
|
71
|
-
/** Add a
|
|
72
|
-
|
|
73
|
+
/** Add a request interceptor (called before every request). Returns an unsubscribe function. */
|
|
74
|
+
onRequest(fn: HttpRequestInterceptor): () => void;
|
|
75
|
+
|
|
76
|
+
/** Add a response interceptor (called after every response, before error check). Returns an unsubscribe function. */
|
|
77
|
+
onResponse(fn: HttpResponseInterceptor): () => void;
|
|
78
|
+
|
|
79
|
+
/** Clear interceptors. No args = all; `'request'` or `'response'` for one type. */
|
|
80
|
+
clearInterceptors(type?: 'request' | 'response'): void;
|
|
81
|
+
|
|
82
|
+
/** Run multiple request promises in parallel via `Promise.all`. */
|
|
83
|
+
all<T extends readonly Promise<HttpResponse<any>>[]>(requests: T): Promise<{ -readonly [K in keyof T]: Awaited<T[K]> }>;
|
|
73
84
|
|
|
74
85
|
/** Create a new `AbortController` for manual request cancellation. */
|
|
75
86
|
createAbort(): AbortController;
|