zero-query 0.8.6 → 0.8.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 CHANGED
@@ -189,13 +189,12 @@ Output goes to `dist/` next to your `index.html`:
189
189
  dist/
190
190
  server/ ← deploy to your web server (<base href="/"> for SPA routes)
191
191
  index.html
192
- z-app.<hash>.js
193
192
  z-app.<hash>.min.js
194
193
  global.<hash>.min.css
195
194
  assets/
196
195
  local/ ← open from disk (file://) — no server needed
197
196
  index.html
198
- z-app.<hash>.js
197
+ z-app.<hash>.min.js
199
198
  ...
200
199
  ```
201
200
 
@@ -217,7 +216,7 @@ dist/
217
216
  4. **Convention fallbacks** — `app/app.js`, `scripts/app.js`, `src/app.js`, `js/app.js`, `app.js`, `main.js`.
218
217
  2. Resolves all `import` statements and topologically sorts dependencies
219
218
  3. Strips `import`/`export` syntax, wraps in an IIFE
220
- 4. Embeds zQuery library and inlines `templateUrl` / `styleUrl` / `pages` files
219
+ 4. Embeds zQuery library and inlines `templateUrl` / `styleUrl` files
221
220
  5. Rewrites HTML, copies assets, produces hashed filenames
222
221
 
223
222
  ---
@@ -353,7 +353,7 @@ function _collapseTemplateCSS(tpl) {
353
353
 
354
354
  /**
355
355
  * Scan bundled source files for external resource references
356
- * (pages config, templateUrl, styleUrl) and return a map of
356
+ * (templateUrl, styleUrl) and return a map of
357
357
  * { relativePath: fileContent } for inlining.
358
358
  */
359
359
  function collectInlineResources(files, projectRoot) {
@@ -363,33 +363,6 @@ function collectInlineResources(files, projectRoot) {
363
363
  const code = fs.readFileSync(file, 'utf-8');
364
364
  const fileDir = path.dirname(file);
365
365
 
366
- // pages: config
367
- const pagesMatch = code.match(/pages\s*:\s*\{[^}]*dir\s*:\s*['"]([^'"]+)['"]/s);
368
- if (pagesMatch) {
369
- const pagesDir = pagesMatch[1];
370
- const ext = (code.match(/pages\s*:\s*\{[^}]*ext\s*:\s*['"]([^'"]+)['"]/s) || [])[1] || '.html';
371
- const itemsMatch = code.match(/items\s*:\s*\[([\s\S]*?)\]/);
372
- if (itemsMatch) {
373
- const itemsBlock = itemsMatch[1];
374
- const ids = [];
375
- let m;
376
- const strRe = /['"]([^'"]+)['"]/g;
377
- while ((m = strRe.exec(itemsBlock)) !== null) {
378
- const before = itemsBlock.substring(Math.max(0, m.index - 20), m.index);
379
- if (/label\s*:\s*$/.test(before)) continue;
380
- ids.push(m[1]);
381
- }
382
- const absPagesDir = path.join(fileDir, pagesDir);
383
- for (const id of ids) {
384
- const pagePath = path.join(absPagesDir, id + ext);
385
- if (fs.existsSync(pagePath)) {
386
- const relKey = path.relative(projectRoot, pagePath).replace(/\\/g, '/');
387
- inlineMap[relKey] = fs.readFileSync(pagePath, 'utf-8');
388
- }
389
- }
390
- }
391
- }
392
-
393
366
  // styleUrl:
394
367
  const styleUrlRe = /styleUrl\s*:\s*['"]([^'"]+)['"]/g;
395
368
  const styleMatch = styleUrlRe.exec(code);
@@ -409,6 +382,25 @@ function collectInlineResources(files, projectRoot) {
409
382
  const relKey = path.relative(projectRoot, tmplPath).replace(/\\/g, '/');
410
383
  inlineMap[relKey] = fs.readFileSync(tmplPath, 'utf-8');
411
384
  }
385
+ } else if (/templateUrl\s*:/.test(code)) {
386
+ // Dynamic templateUrl (e.g. Object.fromEntries, computed map) —
387
+ // inline all .html files in the component's directory tree so
388
+ // the runtime __zqInline lookup can resolve them by suffix.
389
+ (function scanHtml(dir) {
390
+ try {
391
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
392
+ const full = path.join(dir, entry.name);
393
+ if (entry.isFile() && entry.name.endsWith('.html')) {
394
+ const relKey = path.relative(projectRoot, full).replace(/\\/g, '/');
395
+ if (!inlineMap[relKey]) {
396
+ inlineMap[relKey] = fs.readFileSync(full, 'utf-8');
397
+ }
398
+ } else if (entry.isDirectory()) {
399
+ scanHtml(full);
400
+ }
401
+ }
402
+ } catch { /* permission error — skip */ }
403
+ })(fileDir);
412
404
  }
413
405
  }
414
406
 
Binary file
package/dist/zquery.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * zQuery (zeroQuery) v0.8.6
2
+ * zQuery (zeroQuery) v0.8.7
3
3
  * Lightweight Frontend Library
4
4
  * https://github.com/tonywied17/zero-query
5
5
  * (c) 2026 Anthony Wiedman - MIT License
@@ -2553,7 +2553,7 @@ function _getKey(node) {
2553
2553
  * - Scoped styles (inline or via styleUrl)
2554
2554
  * - External templates via templateUrl (with {{expression}} interpolation)
2555
2555
  * - External styles via styleUrl (fetched & scoped automatically)
2556
- * - Relative path resolution — templateUrl, styleUrl, and pages.dir
2556
+ * - Relative path resolution — templateUrl and styleUrl
2557
2557
  * resolve relative to the component file automatically
2558
2558
  */
2559
2559
 
@@ -2623,16 +2623,6 @@ function _fetchResource(url) {
2623
2623
  return promise;
2624
2624
  }
2625
2625
 
2626
- /**
2627
- * Convert a kebab-case id to Title Case.
2628
- * 'getting-started' → 'Getting Started'
2629
- * @param {string} id
2630
- * @returns {string}
2631
- */
2632
- function _titleCase(id) {
2633
- return id.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
2634
- }
2635
-
2636
2626
  /**
2637
2627
  * Resolve a relative URL against a base.
2638
2628
  *
@@ -2851,47 +2841,10 @@ class Component {
2851
2841
  // - string → single stylesheet
2852
2842
  // - string[] → array of URLs → all fetched & concatenated
2853
2843
  //
2854
- // pages config (shorthand for multi-template + route-param page switching):
2855
- // pages: {
2856
- // dir: 'pages', // relative to component file (or base)
2857
- // param: 'section', // route param name → this.activePage
2858
- // default: 'getting-started', // fallback when param is absent
2859
- // ext: '.html', // file extension (default '.html')
2860
- // items: ['page-a', { id: 'page-b', label: 'Page B' }, ...]
2861
- // }
2862
- // Exposes this.pages (array of {id,label}), this.activePage (current id)
2863
- // Pages are lazy-loaded: only the active page is fetched on first render,
2864
- // remaining pages are prefetched in the background for instant navigation.
2865
- //
2866
2844
  async _loadExternals() {
2867
2845
  const def = this._def;
2868
2846
  const base = def._base; // auto-detected or explicit
2869
2847
 
2870
- // -- Pages config ---------------------------------------------
2871
- if (def.pages && !def._pagesNormalized) {
2872
- const p = def.pages;
2873
- const ext = p.ext || '.html';
2874
- const dir = _resolveUrl((p.dir || '').replace(/\/+$/, ''), base);
2875
-
2876
- // Normalize items → [{id, label}, …]
2877
- def._pages = (p.items || []).map(item => {
2878
- if (typeof item === 'string') return { id: item, label: _titleCase(item) };
2879
- return { ...item, label: item.label || _titleCase(item.id) };
2880
- });
2881
-
2882
- // Build URL map for lazy per-page loading.
2883
- // Pages are fetched on demand (active page first, rest prefetched in
2884
- // the background) so the component renders as soon as the visible
2885
- // page is ready instead of waiting for every page to download.
2886
- def._pageUrls = {};
2887
- for (const { id } of def._pages) {
2888
- def._pageUrls[id] = `${dir}/${id}${ext}`;
2889
- }
2890
- if (!def._externalTemplates) def._externalTemplates = {};
2891
-
2892
- def._pagesNormalized = true;
2893
- }
2894
-
2895
2848
  // -- External templates --------------------------------------
2896
2849
  if (def.templateUrl && !def._templateLoaded) {
2897
2850
  const tu = def.templateUrl;
@@ -2904,9 +2857,8 @@ class Component {
2904
2857
  results.forEach((html, i) => { def._externalTemplates[i] = html; });
2905
2858
  } else if (typeof tu === 'object') {
2906
2859
  const entries = Object.entries(tu);
2907
- // Pages config already resolved; plain objects still need resolving
2908
2860
  const results = await Promise.all(
2909
- entries.map(([, url]) => _fetchResource(def._pagesNormalized ? url : _resolveUrl(url, base)))
2861
+ entries.map(([, url]) => _fetchResource(_resolveUrl(url, base)))
2910
2862
  );
2911
2863
  def._externalTemplates = {};
2912
2864
  entries.forEach(([key], i) => { def._externalTemplates[key] = results[i]; });
@@ -2935,8 +2887,7 @@ class Component {
2935
2887
  _render() {
2936
2888
  // If externals haven't loaded yet, trigger async load then re-render
2937
2889
  if ((this._def.templateUrl && !this._def._templateLoaded) ||
2938
- (this._def.styleUrl && !this._def._styleLoaded) ||
2939
- (this._def.pages && !this._def._pagesNormalized)) {
2890
+ (this._def.styleUrl && !this._def._styleLoaded)) {
2940
2891
  this._loadExternals().then(() => {
2941
2892
  if (!this._destroyed) this._render();
2942
2893
  });
@@ -2948,43 +2899,6 @@ class Component {
2948
2899
  this.templates = this._def._externalTemplates;
2949
2900
  }
2950
2901
 
2951
- // Expose pages metadata and active page (derived from route param)
2952
- if (this._def._pages) {
2953
- this.pages = this._def._pages;
2954
- const pc = this._def.pages;
2955
- let active = (pc.param && this.props.$params?.[pc.param]) || pc.default || this._def._pages[0]?.id || '';
2956
-
2957
- // Fall back to default if the param doesn't match any known page
2958
- if (this._def._pageUrls && !(active in this._def._pageUrls)) {
2959
- active = pc.default || this._def._pages[0]?.id || '';
2960
- }
2961
- this.activePage = active;
2962
-
2963
- // Lazy-load: fetch only the active page's template on demand
2964
- if (this._def._pageUrls && !(active in this._def._externalTemplates)) {
2965
- const url = this._def._pageUrls[active];
2966
- if (url) {
2967
- _fetchResource(url).then(html => {
2968
- this._def._externalTemplates[active] = html;
2969
- if (!this._destroyed) this._render();
2970
- });
2971
- return; // Wait for active page before rendering
2972
- }
2973
- }
2974
-
2975
- // Prefetch remaining pages in background (once, after active page is ready)
2976
- if (this._def._pageUrls && !this._def._pagesPrefetched) {
2977
- this._def._pagesPrefetched = true;
2978
- for (const [id, url] of Object.entries(this._def._pageUrls)) {
2979
- if (!(id in this._def._externalTemplates)) {
2980
- _fetchResource(url).then(html => {
2981
- this._def._externalTemplates[id] = html;
2982
- });
2983
- }
2984
- }
2985
- }
2986
- }
2987
-
2988
2902
  // Determine HTML content
2989
2903
  let html;
2990
2904
  if (this._def.render) {
@@ -3687,7 +3601,7 @@ class Component {
3687
3601
  // Reserved definition keys (not user methods)
3688
3602
  const _reservedKeys = new Set([
3689
3603
  'state', 'render', 'styles', 'init', 'mounted', 'updated', 'destroyed', 'props',
3690
- 'templateUrl', 'styleUrl', 'templates', 'pages', 'activePage', 'base',
3604
+ 'templateUrl', 'styleUrl', 'templates', 'base',
3691
3605
  'computed', 'watch'
3692
3606
  ]);
3693
3607
 
@@ -3710,8 +3624,8 @@ function component(name, definition) {
3710
3624
  }
3711
3625
  definition._name = name;
3712
3626
 
3713
- // Auto-detect the calling module's URL so that relative templateUrl,
3714
- // styleUrl, and pages.dir paths resolve relative to the component file.
3627
+ // Auto-detect the calling module's URL so that relative templateUrl
3628
+ // and styleUrl paths resolve relative to the component file.
3715
3629
  // An explicit `base` string on the definition overrides auto-detection.
3716
3630
  if (definition.base !== undefined) {
3717
3631
  definition._base = definition.base; // explicit override
@@ -3838,23 +3752,11 @@ async function prefetch(name) {
3838
3752
  const def = _registry.get(name);
3839
3753
  if (!def) return;
3840
3754
 
3841
- // Load templateUrl, styleUrl, and normalize pages config
3755
+ // Load templateUrl and styleUrl if not already loaded.
3842
3756
  if ((def.templateUrl && !def._templateLoaded) ||
3843
- (def.styleUrl && !def._styleLoaded) ||
3844
- (def.pages && !def._pagesNormalized)) {
3757
+ (def.styleUrl && !def._styleLoaded)) {
3845
3758
  await Component.prototype._loadExternals.call({ _def: def });
3846
3759
  }
3847
-
3848
- // For pages-based components, prefetch ALL page templates so any
3849
- // active page renders instantly on mount.
3850
- if (def._pageUrls && def._externalTemplates) {
3851
- const missing = Object.entries(def._pageUrls)
3852
- .filter(([id]) => !(id in def._externalTemplates));
3853
- if (missing.length) {
3854
- const results = await Promise.all(missing.map(([, url]) => _fetchResource(url)));
3855
- missing.forEach(([id], i) => { def._externalTemplates[id] = results[i]; });
3856
- }
3857
- }
3858
3760
  }
3859
3761
 
3860
3762
 
@@ -4098,7 +4000,7 @@ class Router {
4098
4000
 
4099
4001
  // Per-route fallback: register an alias path for the same component.
4100
4002
  // e.g. { path: '/docs/:section', fallback: '/docs', component: 'docs-page' }
4101
- // When matched via fallback, missing params are undefined → pages `default` kicks in.
4003
+ // When matched via fallback, missing params are undefined.
4102
4004
  if (route.fallback) {
4103
4005
  const fbKeys = [];
4104
4006
  const fbPattern = route.fallback
@@ -5362,8 +5264,8 @@ $.guardCallback = guardCallback;
5362
5264
  $.validate = validate;
5363
5265
 
5364
5266
  // --- Meta ------------------------------------------------------------------
5365
- $.version = '0.8.6';
5366
- $.libSize = '~91 KB';
5267
+ $.version = '0.8.7';
5268
+ $.libSize = '~89 KB';
5367
5269
  $.meta = {}; // populated at build time by CLI bundler
5368
5270
 
5369
5271
  $.noConflict = () => {
@@ -1,7 +1,7 @@
1
1
  /**
2
- * zQuery (zeroQuery) v0.8.6
2
+ * zQuery (zeroQuery) v0.8.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(()=>{s._value=fn();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();}Signal._activeEffect=null;};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(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(){const sibs=[];this.elements.forEach(el=>{sibs.push(...[...el.parentElement.children].filter(c=>c!==el));});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();return el?Array.from(el.parentElement.children).indexOf(el):-1;}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(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){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);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'){el.addEventListener(evt,(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);});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>el.removeEventListener(evt,handler));});}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'){return new Promise(resolve=>{const count={done:0};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(++count.done>=this.length)resolve(this);};el.addEventListener('transitionend',onEnd);});});setTimeout(()=>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 visible=getComputedStyle(el).opacity!=='0'&&getComputedStyle(el).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.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),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('()[]{},.?:'.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(1);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){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){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){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'){const classExpr=this.parsePostfix();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__',]);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;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 callee=evaluate(node.callee,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;const args=node.args.map(a=>evaluate(a,scope));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=node.args.map(a=>evaluate(a,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':return node.elements.map(e=>evaluate(e,scope));case'object':{const obj={};for(const{key,value}of node.properties){obj[key]=evaluate(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 _resolveCall(node,scope){const callee=node.callee;const args=node.args.map(a=>evaluate(a,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){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);}_morphNode(oldParent,oldNode,newNode);cursor=oldNode.nextSibling;}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);}}for(let i=oldLen-1;i>=0;i--){if(!newNames.has(oldAttrs[i].name)){oldEl.removeAttribute(oldAttrs[i].name);}}}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 _titleCase(id){return id.replace(/-/g,' ').replace(/\b\w/g,c=>c.toUpperCase());}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');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+'.')||changedKey===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.pages&&!def._pagesNormalized){const p=def.pages;const ext=p.ext||'.html';const dir=_resolveUrl((p.dir||'').replace(/\/+$/,''),base);def._pages=(p.items||[]).map(item=>{if(typeof item==='string')return{id:item,label:_titleCase(item)};return{...item,label:item.label||_titleCase(item.id)};});def._pageUrls={};for(const{id}of def._pages){def._pageUrls[id]=`${dir}/${id}${ext}`;}if(!def._externalTemplates)def._externalTemplates={};def._pagesNormalized=true;}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(def._pagesNormalized?url:_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._def.pages&&!this._def._pagesNormalized)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}if(this._def._pages){this.pages=this._def._pages;const pc=this._def.pages;let active=(pc.param&&this.props.$params?.[pc.param])||pc.default||this._def._pages[0]?.id||'';if(this._def._pageUrls&&!(active in this._def._pageUrls)){active=pc.default||this._def._pages[0]?.id||'';}this.activePage=active;if(this._def._pageUrls&&!(active in this._def._externalTemplates)){const url=this._def._pageUrls[active];if(url){_fetchResource(url).then(html=>{this._def._externalTemplates[active]=html;if(!this._destroyed)this._render();});return;}}if(this._def._pageUrls&&!this._def._pagesPrefetched){this._def._pagesPrefetched=true;for(const[id,url]of Object.entries(this._def._pageUrls)){if(!(id in this._def._externalTemplates)){_fetchResource(url).then(html=>{this._def._externalTemplates[id]=html;});}}}}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 inAtBlock=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(inAtBlock>0)inAtBlock--;return match;}const trimmed=selector.trim();if(trimmed.startsWith('@')){inAtBlock++;return match;}if(inAtBlock>0&&/^[\d%\s,fromto]+$/.test(trimmed.replace(/\s/g,''))){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);}}_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)||[];for(const{selector,methodExpr,modifiers,el}of currentBindings){if(!e.target.closest(selector))continue;if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop'))e.stopPropagation();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 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(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};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=[];this._delegatedEvents=null;this._eventBindings=null;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','pages','activePage','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)||(def.pages&&!def._pagesNormalized)){await Component.prototype._loadExternals.call({_def:def});}if(def._pageUrls&&def._externalTemplates){const missing=Object.entries(def._pageUrls).filter(([id])=>!(id in def._externalTemplates));if(missing.length){const results=await Promise.all(missing.map(([,url])=>_fetchResource(url)));missing.forEach(([id],i)=>{def._externalTemplates[id]=results[i];});}}}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';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'){window.addEventListener('hashchange',()=>this._resolve());}else{window.addEventListener('popstate',(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();});}document.addEventListener('click',(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});}});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=JSON.stringify(params)===JSON.stringify(from.params);const sameQuery=JSON.stringify(query)===JSON.stringify(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);this._instance=mount(container,matched.component,props);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._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._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()});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();fetchOpts.signal=options.signal||controller.signal;const timeout=options.timeout??_config.timeout;let timer;if(timeout>0){timer=setTimeout(()=>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'){throw new Error(`Request timeout after ${timeout}ms: ${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={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};return String(str).replace(/[&<>"']/g,c=>map[c]);}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])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){for(const source of sources){for(const key of Object.keys(source)){if(source[key]&&typeof source[key]==='object'&&!Array.isArray(source[key])){if(!target[key]||typeof target[key]!=='object')target[key]={};deepMerge(target[key],source[key]);}else{target[key]=source[key];}}}return target;}function isEqual(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;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]));}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 $(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;$.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;$.html=html;$.trust=trust;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.bus=bus;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.8.6';$.libSize='~91 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(()=>{s._value=fn();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();}Signal._activeEffect=null;};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(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(){const sibs=[];this.elements.forEach(el=>{sibs.push(...[...el.parentElement.children].filter(c=>c!==el));});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();return el?Array.from(el.parentElement.children).indexOf(el):-1;}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(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){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);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'){el.addEventListener(evt,(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);});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>el.removeEventListener(evt,handler));});}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'){return new Promise(resolve=>{const count={done:0};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(++count.done>=this.length)resolve(this);};el.addEventListener('transitionend',onEnd);});});setTimeout(()=>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 visible=getComputedStyle(el).opacity!=='0'&&getComputedStyle(el).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.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),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('()[]{},.?:'.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(1);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){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){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){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'){const classExpr=this.parsePostfix();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__',]);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;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 callee=evaluate(node.callee,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;const args=node.args.map(a=>evaluate(a,scope));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=node.args.map(a=>evaluate(a,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':return node.elements.map(e=>evaluate(e,scope));case'object':{const obj={};for(const{key,value}of node.properties){obj[key]=evaluate(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 _resolveCall(node,scope){const callee=node.callee;const args=node.args.map(a=>evaluate(a,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){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);}_morphNode(oldParent,oldNode,newNode);cursor=oldNode.nextSibling;}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);}}for(let i=oldLen-1;i>=0;i--){if(!newNames.has(oldAttrs[i].name)){oldEl.removeAttribute(oldAttrs[i].name);}}}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');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+'.')||changedKey===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 inAtBlock=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(inAtBlock>0)inAtBlock--;return match;}const trimmed=selector.trim();if(trimmed.startsWith('@')){inAtBlock++;return match;}if(inAtBlock>0&&/^[\d%\s,fromto]+$/.test(trimmed.replace(/\s/g,''))){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);}}_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)||[];for(const{selector,methodExpr,modifiers,el}of currentBindings){if(!e.target.closest(selector))continue;if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop'))e.stopPropagation();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 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(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};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=[];this._delegatedEvents=null;this._eventBindings=null;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';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'){window.addEventListener('hashchange',()=>this._resolve());}else{window.addEventListener('popstate',(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();});}document.addEventListener('click',(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});}});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=JSON.stringify(params)===JSON.stringify(from.params);const sameQuery=JSON.stringify(query)===JSON.stringify(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);this._instance=mount(container,matched.component,props);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._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._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()});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();fetchOpts.signal=options.signal||controller.signal;const timeout=options.timeout??_config.timeout;let timer;if(timeout>0){timer=setTimeout(()=>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'){throw new Error(`Request timeout after ${timeout}ms: ${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={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};return String(str).replace(/[&<>"']/g,c=>map[c]);}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])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){for(const source of sources){for(const key of Object.keys(source)){if(source[key]&&typeof source[key]==='object'&&!Array.isArray(source[key])){if(!target[key]||typeof target[key]!=='object')target[key]={};deepMerge(target[key],source[key]);}else{target[key]=source[key];}}}return target;}function isEqual(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;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]));}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 $(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;$.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;$.html=html;$.trust=trust;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.bus=bus;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.8.7';$.libSize='~89 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
@@ -4,7 +4,7 @@
4
4
  * Lightweight modern frontend library — jQuery-like selectors, reactive
5
5
  * components, SPA router, state management, HTTP client & utilities.
6
6
  *
7
- * @version 0.8.6
7
+ * @version 0.8.7
8
8
  * @license MIT
9
9
  * @see https://z-query.com/docs
10
10
  */
@@ -25,8 +25,6 @@ export {
25
25
  } from './types/reactive';
26
26
 
27
27
  export {
28
- PageItem,
29
- PagesConfig,
30
28
  ComponentDefinition,
31
29
  ComponentInstance,
32
30
  component,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zero-query",
3
- "version": "0.8.6",
3
+ "version": "0.8.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/component.js CHANGED
@@ -15,7 +15,7 @@
15
15
  * - Scoped styles (inline or via styleUrl)
16
16
  * - External templates via templateUrl (with {{expression}} interpolation)
17
17
  * - External styles via styleUrl (fetched & scoped automatically)
18
- * - Relative path resolution — templateUrl, styleUrl, and pages.dir
18
+ * - Relative path resolution — templateUrl and styleUrl
19
19
  * resolve relative to the component file automatically
20
20
  */
21
21
 
@@ -86,16 +86,6 @@ function _fetchResource(url) {
86
86
  return promise;
87
87
  }
88
88
 
89
- /**
90
- * Convert a kebab-case id to Title Case.
91
- * 'getting-started' → 'Getting Started'
92
- * @param {string} id
93
- * @returns {string}
94
- */
95
- function _titleCase(id) {
96
- return id.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
97
- }
98
-
99
89
  /**
100
90
  * Resolve a relative URL against a base.
101
91
  *
@@ -314,47 +304,10 @@ class Component {
314
304
  // - string → single stylesheet
315
305
  // - string[] → array of URLs → all fetched & concatenated
316
306
  //
317
- // pages config (shorthand for multi-template + route-param page switching):
318
- // pages: {
319
- // dir: 'pages', // relative to component file (or base)
320
- // param: 'section', // route param name → this.activePage
321
- // default: 'getting-started', // fallback when param is absent
322
- // ext: '.html', // file extension (default '.html')
323
- // items: ['page-a', { id: 'page-b', label: 'Page B' }, ...]
324
- // }
325
- // Exposes this.pages (array of {id,label}), this.activePage (current id)
326
- // Pages are lazy-loaded: only the active page is fetched on first render,
327
- // remaining pages are prefetched in the background for instant navigation.
328
- //
329
307
  async _loadExternals() {
330
308
  const def = this._def;
331
309
  const base = def._base; // auto-detected or explicit
332
310
 
333
- // -- Pages config ---------------------------------------------
334
- if (def.pages && !def._pagesNormalized) {
335
- const p = def.pages;
336
- const ext = p.ext || '.html';
337
- const dir = _resolveUrl((p.dir || '').replace(/\/+$/, ''), base);
338
-
339
- // Normalize items → [{id, label}, …]
340
- def._pages = (p.items || []).map(item => {
341
- if (typeof item === 'string') return { id: item, label: _titleCase(item) };
342
- return { ...item, label: item.label || _titleCase(item.id) };
343
- });
344
-
345
- // Build URL map for lazy per-page loading.
346
- // Pages are fetched on demand (active page first, rest prefetched in
347
- // the background) so the component renders as soon as the visible
348
- // page is ready instead of waiting for every page to download.
349
- def._pageUrls = {};
350
- for (const { id } of def._pages) {
351
- def._pageUrls[id] = `${dir}/${id}${ext}`;
352
- }
353
- if (!def._externalTemplates) def._externalTemplates = {};
354
-
355
- def._pagesNormalized = true;
356
- }
357
-
358
311
  // -- External templates --------------------------------------
359
312
  if (def.templateUrl && !def._templateLoaded) {
360
313
  const tu = def.templateUrl;
@@ -367,9 +320,8 @@ class Component {
367
320
  results.forEach((html, i) => { def._externalTemplates[i] = html; });
368
321
  } else if (typeof tu === 'object') {
369
322
  const entries = Object.entries(tu);
370
- // Pages config already resolved; plain objects still need resolving
371
323
  const results = await Promise.all(
372
- entries.map(([, url]) => _fetchResource(def._pagesNormalized ? url : _resolveUrl(url, base)))
324
+ entries.map(([, url]) => _fetchResource(_resolveUrl(url, base)))
373
325
  );
374
326
  def._externalTemplates = {};
375
327
  entries.forEach(([key], i) => { def._externalTemplates[key] = results[i]; });
@@ -398,8 +350,7 @@ class Component {
398
350
  _render() {
399
351
  // If externals haven't loaded yet, trigger async load then re-render
400
352
  if ((this._def.templateUrl && !this._def._templateLoaded) ||
401
- (this._def.styleUrl && !this._def._styleLoaded) ||
402
- (this._def.pages && !this._def._pagesNormalized)) {
353
+ (this._def.styleUrl && !this._def._styleLoaded)) {
403
354
  this._loadExternals().then(() => {
404
355
  if (!this._destroyed) this._render();
405
356
  });
@@ -411,43 +362,6 @@ class Component {
411
362
  this.templates = this._def._externalTemplates;
412
363
  }
413
364
 
414
- // Expose pages metadata and active page (derived from route param)
415
- if (this._def._pages) {
416
- this.pages = this._def._pages;
417
- const pc = this._def.pages;
418
- let active = (pc.param && this.props.$params?.[pc.param]) || pc.default || this._def._pages[0]?.id || '';
419
-
420
- // Fall back to default if the param doesn't match any known page
421
- if (this._def._pageUrls && !(active in this._def._pageUrls)) {
422
- active = pc.default || this._def._pages[0]?.id || '';
423
- }
424
- this.activePage = active;
425
-
426
- // Lazy-load: fetch only the active page's template on demand
427
- if (this._def._pageUrls && !(active in this._def._externalTemplates)) {
428
- const url = this._def._pageUrls[active];
429
- if (url) {
430
- _fetchResource(url).then(html => {
431
- this._def._externalTemplates[active] = html;
432
- if (!this._destroyed) this._render();
433
- });
434
- return; // Wait for active page before rendering
435
- }
436
- }
437
-
438
- // Prefetch remaining pages in background (once, after active page is ready)
439
- if (this._def._pageUrls && !this._def._pagesPrefetched) {
440
- this._def._pagesPrefetched = true;
441
- for (const [id, url] of Object.entries(this._def._pageUrls)) {
442
- if (!(id in this._def._externalTemplates)) {
443
- _fetchResource(url).then(html => {
444
- this._def._externalTemplates[id] = html;
445
- });
446
- }
447
- }
448
- }
449
- }
450
-
451
365
  // Determine HTML content
452
366
  let html;
453
367
  if (this._def.render) {
@@ -1150,7 +1064,7 @@ class Component {
1150
1064
  // Reserved definition keys (not user methods)
1151
1065
  const _reservedKeys = new Set([
1152
1066
  'state', 'render', 'styles', 'init', 'mounted', 'updated', 'destroyed', 'props',
1153
- 'templateUrl', 'styleUrl', 'templates', 'pages', 'activePage', 'base',
1067
+ 'templateUrl', 'styleUrl', 'templates', 'base',
1154
1068
  'computed', 'watch'
1155
1069
  ]);
1156
1070
 
@@ -1173,8 +1087,8 @@ export function component(name, definition) {
1173
1087
  }
1174
1088
  definition._name = name;
1175
1089
 
1176
- // Auto-detect the calling module's URL so that relative templateUrl,
1177
- // styleUrl, and pages.dir paths resolve relative to the component file.
1090
+ // Auto-detect the calling module's URL so that relative templateUrl
1091
+ // and styleUrl paths resolve relative to the component file.
1178
1092
  // An explicit `base` string on the definition overrides auto-detection.
1179
1093
  if (definition.base !== undefined) {
1180
1094
  definition._base = definition.base; // explicit override
@@ -1301,23 +1215,11 @@ export async function prefetch(name) {
1301
1215
  const def = _registry.get(name);
1302
1216
  if (!def) return;
1303
1217
 
1304
- // Load templateUrl, styleUrl, and normalize pages config
1218
+ // Load templateUrl and styleUrl if not already loaded.
1305
1219
  if ((def.templateUrl && !def._templateLoaded) ||
1306
- (def.styleUrl && !def._styleLoaded) ||
1307
- (def.pages && !def._pagesNormalized)) {
1220
+ (def.styleUrl && !def._styleLoaded)) {
1308
1221
  await Component.prototype._loadExternals.call({ _def: def });
1309
1222
  }
1310
-
1311
- // For pages-based components, prefetch ALL page templates so any
1312
- // active page renders instantly on mount.
1313
- if (def._pageUrls && def._externalTemplates) {
1314
- const missing = Object.entries(def._pageUrls)
1315
- .filter(([id]) => !(id in def._externalTemplates));
1316
- if (missing.length) {
1317
- const results = await Promise.all(missing.map(([, url]) => _fetchResource(url)));
1318
- missing.forEach(([id], i) => { def._externalTemplates[id] = results[i]; });
1319
- }
1320
- }
1321
1223
  }
1322
1224
 
1323
1225
 
package/src/router.js CHANGED
@@ -138,7 +138,7 @@ class Router {
138
138
 
139
139
  // Per-route fallback: register an alias path for the same component.
140
140
  // e.g. { path: '/docs/:section', fallback: '/docs', component: 'docs-page' }
141
- // When matched via fallback, missing params are undefined → pages `default` kicks in.
141
+ // When matched via fallback, missing params are undefined.
142
142
  if (route.fallback) {
143
143
  const fbKeys = [];
144
144
  const fbPattern = route.fallback
package/src/ssr.js CHANGED
@@ -94,7 +94,7 @@ class SSRComponent {
94
94
 
95
95
  const SSR_RESERVED = new Set([
96
96
  'state', 'render', 'styles', 'init', 'mounted', 'updated', 'destroyed',
97
- 'props', 'templateUrl', 'styleUrl', 'templates', 'pages', 'activePage',
97
+ 'props', 'templateUrl', 'styleUrl', 'templates',
98
98
  'base', 'computed', 'watch'
99
99
  ]);
100
100
 
@@ -7,28 +7,6 @@
7
7
  import type { ReactiveProxy } from './reactive';
8
8
  import type { NavigationContext } from './router';
9
9
 
10
- /** Item in a `pages` config — either a string id or an `{ id, label }` object. */
11
- export type PageItem = string | { id: string; label?: string };
12
-
13
- /**
14
- * Declarative multi-page configuration for a component.
15
- *
16
- * Pages are **lazy-loaded**: only the active page is fetched on first render.
17
- * Remaining pages are prefetched in the background for instant navigation.
18
- */
19
- export interface PagesConfig {
20
- /** Directory containing the page HTML files (resolved relative to `base`). */
21
- dir?: string;
22
- /** Route parameter name to read (e.g. `'section'` for `/docs/:section`). */
23
- param?: string;
24
- /** Default page id when the param is absent. */
25
- default?: string;
26
- /** File extension appended to each page id (default `'.html'`). */
27
- ext?: string;
28
- /** List of page ids and/or `{ id, label }` objects. */
29
- items?: PageItem[];
30
- }
31
-
32
10
  /** The object passed to `$.component()` to define a component. */
33
11
  export interface ComponentDefinition {
34
12
  /**
@@ -58,12 +36,9 @@ export interface ComponentDefinition {
58
36
  */
59
37
  styleUrl?: string | string[];
60
38
 
61
- /** High-level multi-page configuration shorthand. */
62
- pages?: PagesConfig;
63
-
64
39
  /**
65
- * Override the base path for resolving relative `templateUrl`, `styleUrl`,
66
- * and `pages.dir` paths. Normally auto-detected from the calling file.
40
+ * Override the base path for resolving relative `templateUrl` and `styleUrl`
41
+ * paths. Normally auto-detected from the calling file.
67
42
  */
68
43
  base?: string;
69
44
 
@@ -121,15 +96,9 @@ export interface ComponentInstance {
121
96
  /** Map of `z-ref` name → DOM element. Populated after each render. */
122
97
  refs: Record<string, Element>;
123
98
 
124
- /** Keyed template map (when using multi-`templateUrl` or `pages`). */
99
+ /** Keyed template map (when using multi-`templateUrl`). */
125
100
  templates: Record<string, string>;
126
101
 
127
- /** Normalized page metadata (when using `pages` config). */
128
- pages: Array<{ id: string; label: string }>;
129
-
130
- /** Active page id derived from route param (when using `pages` config). */
131
- activePage: string;
132
-
133
102
  /**
134
103
  * Computed properties — lazy getters derived from state.
135
104
  * Defined via `computed` in the component definition.