@jasonshimmy/custom-elements-runtime 2.6.3 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/custom-elements-runtime.cjs.js +1 -1
  2. package/dist/custom-elements-runtime.es.js +5 -5
  3. package/dist/custom-elements-runtime.router.cjs.js +1 -1
  4. package/dist/custom-elements-runtime.router.es.js +2 -2
  5. package/dist/custom-elements-runtime.ssr.cjs.js +1 -1
  6. package/dist/custom-elements-runtime.ssr.es.js +2 -2
  7. package/dist/custom-elements-runtime.transitions.cjs.js +1 -1
  8. package/dist/custom-elements-runtime.transitions.es.js +1 -1
  9. package/dist/namespace-helpers-Ctd_h7j2.cjs +5 -0
  10. package/dist/namespace-helpers-Ctd_h7j2.cjs.map +1 -0
  11. package/dist/{namespace-helpers-DcD_6_K1.js → namespace-helpers-DhLBqt-7.js} +52 -32
  12. package/dist/namespace-helpers-DhLBqt-7.js.map +1 -0
  13. package/dist/runtime/reactive.d.ts +10 -0
  14. package/dist/{template-compiler-Bypo0Cn6.cjs → template-compiler-C-jyYSkk.cjs} +2 -2
  15. package/dist/{template-compiler-Bypo0Cn6.cjs.map → template-compiler-C-jyYSkk.cjs.map} +1 -1
  16. package/dist/{template-compiler-taX5Zg4G.js → template-compiler-D0LrTkNv.js} +3 -3
  17. package/dist/{template-compiler-taX5Zg4G.js.map → template-compiler-D0LrTkNv.js.map} +1 -1
  18. package/dist/{transitions-Bo0DVkSp.js → transitions-DMJXs_tY.js} +8 -5
  19. package/dist/{transitions-Bo0DVkSp.js.map → transitions-DMJXs_tY.js.map} +1 -1
  20. package/dist/{transitions-Cm2TlhoN.cjs → transitions-f4KfN29T.cjs} +2 -2
  21. package/dist/{transitions-Cm2TlhoN.cjs.map → transitions-f4KfN29T.cjs.map} +1 -1
  22. package/dist/transitions.d.ts +5 -1
  23. package/package.json +1 -1
  24. package/dist/namespace-helpers-4qeKVqQw.cjs +0 -5
  25. package/dist/namespace-helpers-4qeKVqQw.cjs.map +0 -1
  26. package/dist/namespace-helpers-DcD_6_K1.js.map +0 -1
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./template-compiler-Bypo0Cn6.cjs"),c=require("./namespace-helpers-4qeKVqQw.cjs"),O=require("./transitions-Cm2TlhoN.cjs"),d=require("./logger-CSALKaYm.cjs"),x=100,k=3e4;function A(e,t,o){return o==="jitCacheHitRate"?e<t*.5?"critical":e<t?"warning":"healthy":e>t*2?"critical":e>t?"warning":"healthy"}function D(e){const t=[];return e.memoryUsage?.status!=="healthy"&&t.push("Consider reducing component complexity or implementing better memory cleanup"),e.averageRenderTime?.status!=="healthy"&&t.push("Optimize component render functions - consider lazy loading or virtualization"),e.jitCacheHitRate?.status!=="healthy"&&t.push("JIT CSS cache performance is poor - review CSS patterns for optimization"),e.componentErrorRate?.status!=="healthy"&&t.push("High component error rate detected - review error handling and component logic"),e.activeReactiveStates?.status!=="healthy"&&t.push("High number of reactive states - consider state consolidation or cleanup"),e.memoryLeakIndicator?.status!=="healthy"&&t.push("Potential memory leak detected - review component cleanup and event listener management"),t}function v(){const e=new Map,t=new Set;let o=null;function r(s,i,a){e.set(s,{name:s,value:i,threshold:a,status:"healthy",lastUpdated:Date.now(),history:[]})}function l(){r("activeComponents",0,1e3),r("componentCreateRate",0,50),r("componentErrorRate",0,.1),r("memoryUsage",0,50*1024*1024),r("memoryGrowthRate",0,1024*1024),r("averageRenderTime",0,16),r("slowRenderCount",0,10),r("jitCacheHitRate",100,80),r("activeReactiveStates",0,5e3),r("dependencyUpdates",0,100),r("memoryLeakIndicator",0,.1)}function m(s,i){const a=e.get(s);a&&(a.value=i,a.lastUpdated=Date.now(),a.history.push(i),a.history.length>x&&a.history.shift(),a.status=A(i,a.threshold,s))}function u(){const s={};let i="healthy";for(const[a,h]of e)s[a]={...h},h.status==="critical"?i="critical":h.status==="warning"&&i==="healthy"&&(i="warning");return{overall:i,metrics:s,timestamp:Date.now(),recommendations:D(s)}}function f(){if("memory"in performance&&performance.memory){const s=performance.memory;m("memoryUsage",s.usedJSHeapSize);const i=e.get("memoryUsage");if(i&&i.history.length>1){const a=i.history[i.history.length-2],h=i.history[i.history.length-1];m("memoryGrowthRate",Math.max(0,h-a))}}}function w(s){for(const i of t)try{i(s)}catch(a){d.devError("Error in health monitor listener:",a)}}function _(){f();const s=u();w(s),s.overall==="critical"?d.devError("🚨 Runtime Health: Critical issues detected",s.recommendations):s.overall==="warning"&&d.devWarn("⚠️ Runtime Health: Performance warnings",s.recommendations)}function M(){typeof window>"u"||(o=setInterval(_,k))}function R(){o!==null&&(clearInterval(o),o=null)}function H(s){t.add(s)}function L(s){t.delete(s)}function b(s){const i=e.get(s);return i?[...i.history]:[]}function T(){for(const s of e.values())s.history=[]}return l(),M(),{updateMetric:m,getHealthReport:u,addListener:H,removeListener:L,stop:R,getMetricHistory:b,clearHistory:T}}let p=null;function g(){return p||(p=v()),p}function I(e,t){g().updateMetric(e,t)}function U(){return g().getHealthReport()}function C(){typeof window>"u"||typeof customElements>"u"||customElements.get("cer-keep-alive")||customElements.define("cer-keep-alive",K())}function K(){return class extends HTMLElement{_cache=new Map;_slot=null;_slotListener=null;connectedCallback(){this.shadowRoot||this.attachShadow({mode:"open"}),this.shadowRoot.querySelector("slot")||(this.shadowRoot.innerHTML="<slot></slot>"),this._slot=this.shadowRoot.querySelector("slot"),this._slot&&(this._slotListener=()=>this._handleSlotChange(),this._slot.addEventListener("slotchange",this._slotListener),this._handleSlotChange())}disconnectedCallback(){this._slot&&this._slotListener&&this._slot.removeEventListener("slotchange",this._slotListener),this._slotListener=null}clearCache(t){t?this._cache.delete(t):this._cache.clear()}_handleSlotChange(){if(!this._slot)return;const t=this._slot.assignedElements({flatten:!0});for(const o of t){const r=this._buildCacheKey(o);if(!this._cache.has(r))this._cache.set(r,o);else{const l=this._cache.get(r);if(l!==o)try{o.parentNode?.replaceChild(l,o)}catch{this._cache.set(r,o)}}}}_buildCacheKey(t){const o=t.tagName.toLowerCase(),r=t.getAttribute("id");return r?`${o}:${r}`:o}}}function S(){customElements.get("cer-suspense")||n.component("cer-suspense",()=>{const{pending:e}=n.useProps({pending:!1});return e?n.html`<slot name="fallback"><span>Loading…</span></slot>`:n.html`<slot></slot>`})}function E(){customElements.get("cer-error-boundary")||n.component("cer-error-boundary",()=>{const e=c.ref(!1),t=c.ref("");return n.useOnError(o=>{e.value=!0,t.value=o.message}),n.useExpose({_cerHandleChildError:o=>{e.peek()||(e.value=!0,t.value=o instanceof Error?o.message:String(o))},reset:()=>{e.value=!1,t.value=""}}),e.value?n.html`<slot name="fallback"
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./template-compiler-C-jyYSkk.cjs"),c=require("./namespace-helpers-Ctd_h7j2.cjs"),O=require("./transitions-f4KfN29T.cjs"),d=require("./logger-CSALKaYm.cjs"),x=100,k=3e4;function A(e,t,o){return o==="jitCacheHitRate"?e<t*.5?"critical":e<t?"warning":"healthy":e>t*2?"critical":e>t?"warning":"healthy"}function D(e){const t=[];return e.memoryUsage?.status!=="healthy"&&t.push("Consider reducing component complexity or implementing better memory cleanup"),e.averageRenderTime?.status!=="healthy"&&t.push("Optimize component render functions - consider lazy loading or virtualization"),e.jitCacheHitRate?.status!=="healthy"&&t.push("JIT CSS cache performance is poor - review CSS patterns for optimization"),e.componentErrorRate?.status!=="healthy"&&t.push("High component error rate detected - review error handling and component logic"),e.activeReactiveStates?.status!=="healthy"&&t.push("High number of reactive states - consider state consolidation or cleanup"),e.memoryLeakIndicator?.status!=="healthy"&&t.push("Potential memory leak detected - review component cleanup and event listener management"),t}function v(){const e=new Map,t=new Set;let o=null;function r(s,i,a){e.set(s,{name:s,value:i,threshold:a,status:"healthy",lastUpdated:Date.now(),history:[]})}function l(){r("activeComponents",0,1e3),r("componentCreateRate",0,50),r("componentErrorRate",0,.1),r("memoryUsage",0,50*1024*1024),r("memoryGrowthRate",0,1024*1024),r("averageRenderTime",0,16),r("slowRenderCount",0,10),r("jitCacheHitRate",100,80),r("activeReactiveStates",0,5e3),r("dependencyUpdates",0,100),r("memoryLeakIndicator",0,.1)}function m(s,i){const a=e.get(s);a&&(a.value=i,a.lastUpdated=Date.now(),a.history.push(i),a.history.length>x&&a.history.shift(),a.status=A(i,a.threshold,s))}function u(){const s={};let i="healthy";for(const[a,h]of e)s[a]={...h},h.status==="critical"?i="critical":h.status==="warning"&&i==="healthy"&&(i="warning");return{overall:i,metrics:s,timestamp:Date.now(),recommendations:D(s)}}function f(){if("memory"in performance&&performance.memory){const s=performance.memory;m("memoryUsage",s.usedJSHeapSize);const i=e.get("memoryUsage");if(i&&i.history.length>1){const a=i.history[i.history.length-2],h=i.history[i.history.length-1];m("memoryGrowthRate",Math.max(0,h-a))}}}function w(s){for(const i of t)try{i(s)}catch(a){d.devError("Error in health monitor listener:",a)}}function _(){f();const s=u();w(s),s.overall==="critical"?d.devError("🚨 Runtime Health: Critical issues detected",s.recommendations):s.overall==="warning"&&d.devWarn("⚠️ Runtime Health: Performance warnings",s.recommendations)}function M(){typeof window>"u"||(o=setInterval(_,k))}function R(){o!==null&&(clearInterval(o),o=null)}function H(s){t.add(s)}function L(s){t.delete(s)}function b(s){const i=e.get(s);return i?[...i.history]:[]}function T(){for(const s of e.values())s.history=[]}return l(),M(),{updateMetric:m,getHealthReport:u,addListener:H,removeListener:L,stop:R,getMetricHistory:b,clearHistory:T}}let p=null;function g(){return p||(p=v()),p}function I(e,t){g().updateMetric(e,t)}function U(){return g().getHealthReport()}function C(){typeof window>"u"||typeof customElements>"u"||customElements.get("cer-keep-alive")||customElements.define("cer-keep-alive",K())}function K(){return class extends HTMLElement{_cache=new Map;_slot=null;_slotListener=null;connectedCallback(){this.shadowRoot||this.attachShadow({mode:"open"}),this.shadowRoot.querySelector("slot")||(this.shadowRoot.innerHTML="<slot></slot>"),this._slot=this.shadowRoot.querySelector("slot"),this._slot&&(this._slotListener=()=>this._handleSlotChange(),this._slot.addEventListener("slotchange",this._slotListener),this._handleSlotChange())}disconnectedCallback(){this._slot&&this._slotListener&&this._slot.removeEventListener("slotchange",this._slotListener),this._slotListener=null}clearCache(t){t?this._cache.delete(t):this._cache.clear()}_handleSlotChange(){if(!this._slot)return;const t=this._slot.assignedElements({flatten:!0});for(const o of t){const r=this._buildCacheKey(o);if(!this._cache.has(r))this._cache.set(r,o);else{const l=this._cache.get(r);if(l!==o)try{o.parentNode?.replaceChild(l,o)}catch{this._cache.set(r,o)}}}}_buildCacheKey(t){const o=t.tagName.toLowerCase(),r=t.getAttribute("id");return r?`${o}:${r}`:o}}}function S(){customElements.get("cer-suspense")||n.component("cer-suspense",()=>{const{pending:e}=n.useProps({pending:!1});return e?n.html`<slot name="fallback"><span>Loading…</span></slot>`:n.html`<slot></slot>`})}function E(){customElements.get("cer-error-boundary")||n.component("cer-error-boundary",()=>{const e=c.ref(!1),t=c.ref("");return n.useOnError(o=>{e.value=!0,t.value=o.message}),n.useExpose({_cerHandleChildError:o=>{e.peek()||(e.value=!0,t.value=o instanceof Error?o.message:String(o))},reset:()=>{e.value=!1,t.value=""}}),e.value?n.html`<slot name="fallback"
2
2
  ><div role="alert">
3
3
  <strong>Something went wrong.</strong>
4
4
  ${t.value?n.html`<p>${t.value}</p>`:n.html``}
@@ -1,8 +1,8 @@
1
- import { c as v, u as b, a as T, h as l, b as x, g as k, v as m, i as A } from "./template-compiler-taX5Zg4G.js";
2
- import { d as ee, e as te, f as ne, p as oe, j as re, k as se, l as ie, m as ae, n as ce, o as le } from "./template-compiler-taX5Zg4G.js";
3
- import { r as p, a as I } from "./namespace-helpers-DcD_6_K1.js";
4
- import { R as he, c as de, d as fe, f as me, i as pe, n as ye, s as ge, u as ve, w as Ce, b as we } from "./namespace-helpers-DcD_6_K1.js";
5
- import { c as _e } from "./transitions-Bo0DVkSp.js";
1
+ import { c as v, u as b, a as T, h as l, b as x, g as k, v as m, i as A } from "./template-compiler-D0LrTkNv.js";
2
+ import { d as ee, e as te, f as ne, p as oe, j as re, k as se, l as ie, m as ae, n as ce, o as le } from "./template-compiler-D0LrTkNv.js";
3
+ import { r as p, a as I } from "./namespace-helpers-DhLBqt-7.js";
4
+ import { R as he, c as de, d as fe, f as me, i as pe, n as ye, s as ge, u as ve, w as Ce, b as we } from "./namespace-helpers-DhLBqt-7.js";
5
+ import { c as _e } from "./transitions-DMJXs_tY.js";
6
6
  import { d as y, a as O } from "./logger-BvkEbVM4.js";
7
7
  import { b as Ee, s as He } from "./logger-BvkEbVM4.js";
8
8
  const U = 100, D = 3e4;
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./logger-CSALKaYm.cjs"),$=require("./namespace-helpers-4qeKVqQw.cjs"),x=require("./template-compiler-Bypo0Cn6.cjs"),ot=require("./custom-elements-runtime.store.cjs.js"),bt=require("./custom-elements-runtime.directives.cjs.js"),rt={enabled:!0,offset:0,timeoutMs:2e3},tt=t=>t?typeof URLSearchParams>"u"?{}:Object.fromEntries(new URLSearchParams(t)):{},ft=t=>{if(!t||Object.keys(t).length===0)return"";try{return"?"+new URLSearchParams(t).toString()}catch{return""}},nt=t=>t?/^\s*javascript\s*:/i.test(t):!1,U=t=>/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)||t.startsWith("//"),dt=t=>{try{return decodeURIComponent(t)}catch{return t}};function A(t){if(!t)return"/";let r=t.replace(/\/+/g,"/");return r.startsWith("/")||(r="/"+r),r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1)),r}const ht=t=>{if(!t)return"";const r=A(t);return r==="/"?"":r},st=new WeakMap;function wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function St(t){const r=t.path||"/",v=A(r),a=v==="/"?[]:v.split("/").filter(Boolean),l=[],o=[];for(let u=0;u<a.length;u++){const f=a[u];if(f==="*"){if(u!==a.length-1)return c.devWarn(`Route '${t.path}' contains a '*' splat in a non-terminal position; splats must be the last segment. This route will be ignored.`),{invalid:!0};const W=`splat${l.length}`;l.push(W),o.push("__SPLAT__");continue}const y=f.match(/^:([A-Za-z0-9_-]+)(\*)?$/);if(y){const W=y[1],k=!!y[2];if(k&&u!==a.length-1)return c.devWarn(`Route '${t.path}' contains a splat param ':${W}*' in a non-terminal position; splats must be the last segment. This route will be ignored.`),{invalid:!0};l.push(W),o.push(k?"__SPLAT__":"([^/]+)");continue}o.push(wt(f))}let b;if(o.length===0)b="^/$";else if(o[o.length-1]==="__SPLAT__"){const f=o.slice(0,-1).join("/");f?b=`^/${f}(?:/(.*))?(?:/)?$`:b="^(?:/(.*))?(?:/)?$"}else b=`^/${o.join("/")}(?:/)?$`;try{return{regex:new RegExp(b),paramNames:l}}catch(u){return c.devWarn(`Failed to compile route regex for '${t.path}': ${String(u)}`),{invalid:!0}}}const F=(t,r)=>{const v=A(r);for(const a of t){let l=st.get(a);if(l||(l=St(a),st.set(a,l)),l.invalid)continue;const{regex:o,paramNames:b}=l,u=o.exec(v);if(u){const f={};for(let y=0;y<b.length;y++){const W=u[y+1]||"";f[b[y]]=W?dt(W):""}return{route:a,params:f}}}return{route:null,params:{}}};function Z(t,r){for(const v of t)if(F([v],r).route!==null)return v;return null}function Rt(t,r){return F(t,r)}const ct=50;let G={},L={};function pt(){G={},L={}}function Et(){const t=Object.entries(G);if(t.length<=ct)return;const v=t.sort(([,a],[,l])=>a.lastAccessed-l.lastAccessed).slice(0,t.length-ct);for(const[a]of v)delete G[a]}async function yt(t){if(t.component)return t.component;if(t.load){const r=G[t.path];if(r)return r.lastAccessed=Date.now(),r.component;if(L[t.path]!==void 0)return L[t.path];const v=typeof window>"u";try{const a=t.load().then(l=>{Et();const o=l.default;return G[t.path]={component:o,lastAccessed:Date.now()},delete L[t.path],o}).catch(l=>{delete L[t.path];const o=l instanceof Error?l.message:String(l);throw v&&c.devError(`SSR component load failed for route: ${t.path}. ${o}`),new Error(`Failed to load component for route: ${t.path}. ${o}`)});return L[t.path]=a,await a}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(`Failed to load component for route: ${t.path}. ${l}`,{cause:a})}}throw new Error(`No component or loader defined for route: ${t.path}`)}let g=null;function $t(t){g=t}function it(){return g}const j=new Set;let N=null;function mt(){if(N){try{N()}catch{}N=null}if(g)try{let t=!1;N=g.subscribe(r=>{t=!0;for(const v of j)try{v(r)}catch{}});try{C.base=g.base}catch{}if(t){const r=g.getCurrent();for(const v of j)try{v(r)}catch{}}else{const r=g.getCurrent();for(const v of j)try{v(r)}catch{}}try{typeof window<"u"&&$.flushDOMUpdates()}catch{}}catch{N=null}}function Ct(){mt()}const C={store:{subscribe(t){if(g)return g.store.subscribe(t);try{t({path:"/",params:{},query:{}})}catch{}return()=>{}},getState(){return g?g.getCurrent():{path:"/",params:{},query:{}}},setState(t){if(g)try{g.store.setState(t)}catch{}}},subscribe(t){if(typeof t!="function")return c.devWarn("activeRouterProxy.subscribe: listener must be a function"),()=>{};if(j.add(t),g)if(!N)mt();else try{const r=g.getCurrent();r&&t(r)}catch(r){c.devWarn("activeRouterProxy subscription failed",r)}else try{t({path:"/",params:{},query:{}})}catch(r){c.devWarn("activeRouterProxy fallback state delivery failed",r)}return()=>{try{if(j.delete(t),j.size===0&&N){try{N()}catch(r){c.devWarn("activeRouterProxy inner unsubscribe failed",r)}N=null}}catch(r){c.devWarn("activeRouterProxy unsubscribe failed",r)}}},getCurrent(){return g?g.getCurrent():{path:"/",params:{},query:{}}},async push(t){return g?g.push(t):Promise.resolve()},async replace(t){return g?g.replace(t):Promise.resolve()},back(){if(g)return g.back()},matchRoute(t){return g?g.matchRoute(t):{route:null,params:{}}},resolveRouteComponent(t){return g?g.resolveRouteComponent(t):Promise.reject(new Error("No active router"))},base:"",scrollToFragment(t){return g?g.scrollToFragment(t):Promise.resolve(!1)}};function vt(t){const{routes:r,base:v="",initialUrl:a,scrollToFragment:l=!0}=t,o=ht(v),b=typeof l=="boolean"?{...rt,enabled:l}:{...rt,...l};let u,f,y,W,k,z,B;const _=new Set,K=10;let q=0;const J=async(s,i)=>{const e=Z(r,s.path);if(!e||!e.beforeEnter)return!0;try{const n=await e.beforeEnter(s,i);if(typeof n=="string"){const p=`${s.path}->${n}`;return _.has(p)||q>=K?(c.devError(`Redirect loop detected: ${p}`),!1):n}return n!==!1}catch(n){c.devError("beforeEnter error",n);try{y.setState(i)}catch{}throw n}},X=async(s,i)=>{const e=Z(r,s.path);if(!e||!e.onEnter)return!0;try{const n=await e.onEnter(s,i);if(typeof n=="string"){const p=`${s.path}->${n}`;return _.has(p)||q>=K?(c.devError(`Redirect loop detected: ${p}`),!1):n}return n!==!1}catch(n){c.devError("onEnter error",n);try{y.setState(i)}catch{}throw n}},et=(s,i)=>{const e=Z(r,s.path);if(!(!e||!e.afterEnter))try{e.afterEnter(s,i)}catch(n){c.devError("afterEnter error",n)}},I=new Map,M=100,T=s=>{if(I.has(s))return I.get(s);const i=F(r,s);if(I.size>=M){const e=Math.floor(M*.25),n=Array.from(I.keys());for(let p=0;p<e&&p<n.length;p++)I.delete(n[p])}return I.set(s,i),i},Y=()=>{};async function V(s,i=0){try{const e=document.getElementById(s);if(!e)return!1;if(i>0)try{const n=e.getBoundingClientRect(),p=Math.max(0,window.scrollY+n.top-i);typeof window.scrollTo=="function"&&window.scrollTo({top:p,behavior:"auto"})}catch{try{e.scrollIntoView()}catch{return!1}}else if(typeof e.scrollIntoView=="function")try{e.scrollIntoView({behavior:"auto",block:"start",inline:"nearest"})}catch{try{e.scrollIntoView()}catch{return!1}}return!0}catch{return!1}}function h(s,i=0,e=2e3){return new Promise(n=>{let p=!1,m=null;const w=Date.now(),S=P=>{p||(p=!0,m&&clearTimeout(m),n(P))},E=async()=>{if(!p)try{if(await V(s,i))return S(!0);const P=async()=>{if(p)return;if(Date.now()-w>=e)return S(!1);try{if(await V(s,i))return S(!0);requestAnimationFrame(P)}catch(gt){c.devWarn("Scroll retry attempt failed:",gt),requestAnimationFrame(P)}};requestAnimationFrame(P)}catch(P){c.devWarn("Initial scroll attempt failed:",P),S(!1)}};m=setTimeout(()=>{S(!1)},e),E().catch(P=>{c.devWarn("Scroll attempt failed:",P),S(!1)})})}let R=!1;const d=async(s,i=!1)=>{if(R){c.devWarn(`Navigation to ${s} blocked - navigation already in progress`);return}R=!0,q=0,_.clear();try{await D(s,i)}finally{R=!1,q=0,_.clear()}},O=s=>{const i=s.indexOf("#"),e=i>=0?s.slice(i+1):"",n=i>=0?s.slice(0,i):s,p=n.indexOf("?"),m=p>=0?n.slice(0,p):n,w=p>=0?tt(n.slice(p)):{},S=m.startsWith(o)?m.slice(o.length):m;return{path:A(S||"/"),query:w,fragment:e}},D=async(s,i=!1)=>{try{const e=O(s),n=T(e.path);if(!n.route)throw new Error(`No route found for ${e.path}`);const p=y.getState(),m={path:e.path,params:n.params,query:e.query,fragment:e.fragment},w=await J(m,p);if(w===!1)return;if(typeof w=="string"){q++;const E=`${m.path}->${w}`;_.add(E),await D(w,!0);return}const S=await X(m,p);if(S===!1)return;if(typeof S=="string"){q++;const E=`${m.path}->${S}`;_.add(E),await D(S,!0);return}if(typeof window<"u"&&typeof document<"u"){const E=ft(e.query),P=o+e.path+(E||"")+(e.fragment?"#"+e.fragment:"");i?window.history.replaceState({},"",P):window.history.pushState({},"",P)}if(y.setState(m),et(m,p),typeof window<"u"&&typeof document<"u")try{const E=m.fragment;b.enabled&&E&&h(String(E),b.offset,b.timeoutMs).catch(()=>{})}catch{}}catch(e){if(c.devError("Navigation error:",e),e instanceof Error&&(e.stack?.includes("runBeforeEnter")||e.stack?.includes("runOnEnter")))throw e;try{const n=y.getState();if(!F(r,n.path).route){let m=r.find(w=>w.path==="/");if(m||(m=r.find(w=>!w.path.includes(":")&&!w.path.includes("*"))),!m&&r.length>0&&(m=r[0]),m){const w=F(r,m.path);y.setState({path:m.path,params:w.params,query:{}})}else c.devError("No fallback route available for error recovery")}}catch(n){c.devWarn("State recovery failed during navigation error:",n)}}};if((s=>{if(!s||s.length===0)return c.devError("Router configuration error: No routes provided"),!1;const i=new Set;for(const e of s){if(!e.path)return c.devError("Router configuration error: Route missing path",e),!1;i.has(e.path)&&c.devWarn(`Duplicate route path detected: ${e.path}`),i.add(e.path),!e.component&&!e.load&&c.devWarn(`Route '${e.path}' has no component or load function`)}return!0})(r),typeof window>"u"||typeof a<"u"){for(const s of r)T(s.path);c.devWarn(`Pre-compiled ${r.length} routes for SSR`)}if(typeof window<"u"&&typeof document<"u"&&typeof a>"u"){u=()=>{try{const e=new URL(window.location.href),n=e.pathname,p=n.startsWith(o)?n.slice(o.length):n,m=A(p||"/"),w=tt(e.search),S=e.hash&&e.hash.length?e.hash.slice(1):"";return{path:m,query:w,fragment:S}}catch(e){return c.devWarn("Invalid URL detected, falling back to safe defaults",e),{path:"/",query:{},fragment:""}}},f=u();const s=T(f.path);y=ot.createStore({path:f.path,params:s.params,query:f.query,fragment:f.fragment}),W=async(e=!1)=>{const n=u();await d(n.path,e)};const i=()=>W(!0);window.addEventListener("popstate",i),k=e=>d(e,!1),z=e=>d(e,!0),B=()=>window.history.back()}else{u=()=>{try{const e=new URL(a||"/","http://localhost"),n=e.pathname,p=n.startsWith(o)?n.slice(o.length):n,m=A(p||"/"),w=tt(e.search),S=e.hash&&e.hash.length?e.hash.slice(1):"";return{path:m,query:w,fragment:S}}catch(e){return c.devWarn("Invalid SSR URL detected, falling back to safe defaults",e),{path:"/",query:{},fragment:""}}},f=u();const s=T(f.path);y=ot.createStore({path:f.path,params:s.params,query:f.query,fragment:f.fragment}),W=async()=>{const e=u();await i(e.path)};const i=async e=>{if(q++,q>K){c.devError(`SSR redirect depth exceeded for path: ${e}`);return}try{const n=O(e),p=T(n.path);if(!p.route)throw new Error(`No route found for ${n.path}`);const m=y.getState(),w={path:n.path,params:p.params,query:n.query,fragment:n.fragment},S=Z(r,w.path);if(S?.beforeEnter){const E=await S.beforeEnter(w,m);if(typeof E=="string"){const P=`${w.path}->${E}`;_.add(P),await i(E);return}if(E===!1)return}if(S?.onEnter){const E=await S.onEnter(w,m);if(typeof E=="string"){const P=`${w.path}->${E}`;_.add(P),await i(E);return}if(E===!1)return}y.setState(w),S?.afterEnter&&S.afterEnter(w,m)}catch(n){throw c.devError("SSR navigation error:",n),n}};k=async e=>(q=0,_.clear(),i(e)),z=async e=>(q=0,_.clear(),i(e)),B=()=>{}}return{_cleanupScrollState:Y,store:y,push:k,replace:z,back:B,subscribe:y.subscribe,matchRoute:s=>T(s),getCurrent:()=>y.getState(),resolveRouteComponent:yt,base:o,scrollToFragment:s=>{const i=s||y.getState().fragment;return!i||typeof window>"u"||typeof document>"u"?Promise.resolve(!1):h(i,b.offset,b.timeoutMs)}}}function At(t){pt();const r=vt(t),v=it();if(v)try{v._cleanupScrollState?.()}catch{}$t(r);try{Ct();try{typeof window<"u"&&$.flushDOMUpdates()}catch{}try{typeof window<"u"&&queueMicrotask(()=>{try{$.flushDOMUpdates()}catch{}})}catch{}}catch{}return x.component("router-view",async()=>{if(!it())return x.html`<div>Router not initialized.</div>`;const a=$.ref(C.getCurrent()),l=typeof window>"u";let o;l||(x.useOnConnected(()=>{try{typeof C.subscribe=="function"&&(o=C.subscribe(u=>{try{u&&typeof u=="object"&&typeof u.path=="string"?a.value=u:(c.devWarn("router-view received invalid state",u),a.value={path:"/",params:{},query:{}})}catch(f){c.devWarn("router-view subscription update failed",f);try{a.value={path:"/",params:{},query:{}}}catch{}}}))}catch(u){c.devWarn("router-view subscribe failed",u)}}),x.useOnDisconnected(()=>{if(typeof o=="function"){try{o()}catch(u){c.devWarn("router-view unsubscribe failed",u)}o=void 0}}));const b=C.matchRoute(a.value.path);if(!b||!b.route)return x.html`<div>Not found</div>`;try{const f=await C.resolveRouteComponent(b.route);if(typeof f=="string")return{tag:f,props:{},children:[]};if(typeof f=="function"){const y=f();return(y instanceof Promise?y:Promise.resolve(y)).then(k=>typeof k=="string"?{tag:k,props:{},children:[]}:k)}return x.html`<div>Invalid route component</div>`}catch{return x.html`<div>Invalid route component</div>`}}),x.component("router-link",()=>{const a=x.useProps({to:"",tag:"a",replace:!1,exact:!1,activeClass:"active",exactActiveClass:"exact-active",ariaCurrentValue:"page",disabled:!1,external:!1,class:"",style:""}),l=typeof window>"u",o=$.ref(C.getCurrent()),b=o.value?.path||"/",u=String(a.to||""),f=l?{isExactActive:lt(b,u,C.base),isActive:ut(b,u,C.base),isExternal:U(u)||!!a.external}:null;let y;x.useStyle(()=>"a,button{display:inline-block;}");const W=$.ref(a.class||""),k=$.ref(a.style||"");if(!l){let h=null;x.useOnConnected(R=>{try{if(typeof C.subscribe=="function"){y=C.subscribe(d=>{try{d&&typeof d=="object"&&typeof d.path=="string"?o.value=d:(c.devWarn("router-link received invalid state",d),o.value={path:"/",params:{},query:{}})}catch(O){c.devWarn("router-link subscription update failed",O);try{o.value={path:"/",params:{},query:{}}}catch{}}});try{const d=C.getCurrent();d&&typeof d.path=="string"&&(o.value=d)}catch(d){c.devWarn("router-link initial state sync failed",d)}h=setInterval(()=>{try{const d=C.getCurrent();d&&typeof d.path=="string"&&JSON.stringify(o.value)!==JSON.stringify(d)&&(o.value=d)}catch{}},100)}}catch(d){c.devWarn("router-link subscribe failed",d)}try{const d=R?._host;if(d instanceof HTMLElement){const O=d.getAttribute("class"),D=d.getAttribute("style");O&&(W.value=O),D&&(k.value=D),O!==null&&d.removeAttribute("class"),D!==null&&d.removeAttribute("style");try{R?._requestRender?.();try{$.flushDOMUpdates()}catch{}}catch{}}}catch(d){c.devWarn("router-link host migration failed",d)}}),x.useOnDisconnected(()=>{if(typeof y=="function")try{y()}catch(R){c.devWarn("router-link unsubscribe failed",R)}finally{y=void 0}if(h)try{clearInterval(h)}catch(R){c.devWarn("router-link sync interval cleanup failed",R)}finally{h=null}})}const z=$.computed(()=>{if(l&&f)return f.isExactActive;try{const h=C.base??"",R=a.to||"";return!o.value||typeof o.value.path!="string"?!1:lt(o.value.path,R,h)}catch(h){return c.devWarn("isExactActive computation error",h),!1}}),B=$.computed(()=>{if(l&&f)return f.isActive;try{const h=C.base??"",R=a.to||"";return!o.value||typeof o.value.path!="string"?!1:a.exact?z.value:ut(o.value.path,R,h)}catch(h){return c.devWarn("isActive computation error",h),!1}}),_=$.computed(()=>{const h=String(a.to||"");if(nt(h))return null;if(U(h))return h;const[R,d]=h.split("#"),[O,D]=(R||"").split("?"),H=C.base??"";let Q=O||"/";if(H&&H!=="/"){const s=A(H),i=A(Q);i.startsWith(s)?Q=i.slice(s.length)||"/":Q=i}const at=A(Q||"/");return H+at+(D?"?"+D:"")+(d?"#"+d:"")}),K=$.computed(()=>{const R=(W&&W.value||a.class||"").split(/\s+/).filter(Boolean),d={};for(const O of R)d[O]=!0;return d}),q=$.computed(()=>({...K.value,[a.activeClass||"active"]:B.value,[a.exactActiveClass||"exact-active"]:z.value})),J=$.computed(()=>Object.keys(q.value).filter(h=>q.value[h]).join(" ")),X=$.computed(()=>a.tag||"a"),et=$.computed(()=>X.value==="button"),I=$.computed(()=>z.value?a.ariaCurrentValue:null),M=$.computed(()=>!!a.disabled),T=$.computed(()=>{const h=String(a.to||"");return(U(h)||!!a.external)&&X.value==="a"}),Y=$.computed(()=>k&&k.value||a.style||""),V=h=>{if(h.defaultPrevented||h.button!==0||h.metaKey||h.altKey||h.ctrlKey||h.shiftKey)return;if(M.value){h.preventDefault();return}const R=String(a.to||"");if(nt(R)){try{h.preventDefault()}catch{}c.devWarn("Blocked unsafe javascript: URI in router-link.to");return}T.value||(h.preventDefault(),a.replace?C.replace(a.to):C.push(a.to))};return x.html`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./logger-CSALKaYm.cjs"),$=require("./namespace-helpers-Ctd_h7j2.cjs"),x=require("./template-compiler-C-jyYSkk.cjs"),ot=require("./custom-elements-runtime.store.cjs.js"),bt=require("./custom-elements-runtime.directives.cjs.js"),rt={enabled:!0,offset:0,timeoutMs:2e3},tt=t=>t?typeof URLSearchParams>"u"?{}:Object.fromEntries(new URLSearchParams(t)):{},ft=t=>{if(!t||Object.keys(t).length===0)return"";try{return"?"+new URLSearchParams(t).toString()}catch{return""}},nt=t=>t?/^\s*javascript\s*:/i.test(t):!1,U=t=>/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)||t.startsWith("//"),dt=t=>{try{return decodeURIComponent(t)}catch{return t}};function A(t){if(!t)return"/";let r=t.replace(/\/+/g,"/");return r.startsWith("/")||(r="/"+r),r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1)),r}const ht=t=>{if(!t)return"";const r=A(t);return r==="/"?"":r},st=new WeakMap;function wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function St(t){const r=t.path||"/",v=A(r),a=v==="/"?[]:v.split("/").filter(Boolean),l=[],o=[];for(let u=0;u<a.length;u++){const f=a[u];if(f==="*"){if(u!==a.length-1)return c.devWarn(`Route '${t.path}' contains a '*' splat in a non-terminal position; splats must be the last segment. This route will be ignored.`),{invalid:!0};const W=`splat${l.length}`;l.push(W),o.push("__SPLAT__");continue}const y=f.match(/^:([A-Za-z0-9_-]+)(\*)?$/);if(y){const W=y[1],k=!!y[2];if(k&&u!==a.length-1)return c.devWarn(`Route '${t.path}' contains a splat param ':${W}*' in a non-terminal position; splats must be the last segment. This route will be ignored.`),{invalid:!0};l.push(W),o.push(k?"__SPLAT__":"([^/]+)");continue}o.push(wt(f))}let b;if(o.length===0)b="^/$";else if(o[o.length-1]==="__SPLAT__"){const f=o.slice(0,-1).join("/");f?b=`^/${f}(?:/(.*))?(?:/)?$`:b="^(?:/(.*))?(?:/)?$"}else b=`^/${o.join("/")}(?:/)?$`;try{return{regex:new RegExp(b),paramNames:l}}catch(u){return c.devWarn(`Failed to compile route regex for '${t.path}': ${String(u)}`),{invalid:!0}}}const F=(t,r)=>{const v=A(r);for(const a of t){let l=st.get(a);if(l||(l=St(a),st.set(a,l)),l.invalid)continue;const{regex:o,paramNames:b}=l,u=o.exec(v);if(u){const f={};for(let y=0;y<b.length;y++){const W=u[y+1]||"";f[b[y]]=W?dt(W):""}return{route:a,params:f}}}return{route:null,params:{}}};function Z(t,r){for(const v of t)if(F([v],r).route!==null)return v;return null}function Rt(t,r){return F(t,r)}const ct=50;let G={},L={};function pt(){G={},L={}}function Et(){const t=Object.entries(G);if(t.length<=ct)return;const v=t.sort(([,a],[,l])=>a.lastAccessed-l.lastAccessed).slice(0,t.length-ct);for(const[a]of v)delete G[a]}async function yt(t){if(t.component)return t.component;if(t.load){const r=G[t.path];if(r)return r.lastAccessed=Date.now(),r.component;if(L[t.path]!==void 0)return L[t.path];const v=typeof window>"u";try{const a=t.load().then(l=>{Et();const o=l.default;return G[t.path]={component:o,lastAccessed:Date.now()},delete L[t.path],o}).catch(l=>{delete L[t.path];const o=l instanceof Error?l.message:String(l);throw v&&c.devError(`SSR component load failed for route: ${t.path}. ${o}`),new Error(`Failed to load component for route: ${t.path}. ${o}`)});return L[t.path]=a,await a}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(`Failed to load component for route: ${t.path}. ${l}`,{cause:a})}}throw new Error(`No component or loader defined for route: ${t.path}`)}let g=null;function $t(t){g=t}function it(){return g}const j=new Set;let N=null;function mt(){if(N){try{N()}catch{}N=null}if(g)try{let t=!1;N=g.subscribe(r=>{t=!0;for(const v of j)try{v(r)}catch{}});try{C.base=g.base}catch{}if(t){const r=g.getCurrent();for(const v of j)try{v(r)}catch{}}else{const r=g.getCurrent();for(const v of j)try{v(r)}catch{}}try{typeof window<"u"&&$.flushDOMUpdates()}catch{}}catch{N=null}}function Ct(){mt()}const C={store:{subscribe(t){if(g)return g.store.subscribe(t);try{t({path:"/",params:{},query:{}})}catch{}return()=>{}},getState(){return g?g.getCurrent():{path:"/",params:{},query:{}}},setState(t){if(g)try{g.store.setState(t)}catch{}}},subscribe(t){if(typeof t!="function")return c.devWarn("activeRouterProxy.subscribe: listener must be a function"),()=>{};if(j.add(t),g)if(!N)mt();else try{const r=g.getCurrent();r&&t(r)}catch(r){c.devWarn("activeRouterProxy subscription failed",r)}else try{t({path:"/",params:{},query:{}})}catch(r){c.devWarn("activeRouterProxy fallback state delivery failed",r)}return()=>{try{if(j.delete(t),j.size===0&&N){try{N()}catch(r){c.devWarn("activeRouterProxy inner unsubscribe failed",r)}N=null}}catch(r){c.devWarn("activeRouterProxy unsubscribe failed",r)}}},getCurrent(){return g?g.getCurrent():{path:"/",params:{},query:{}}},async push(t){return g?g.push(t):Promise.resolve()},async replace(t){return g?g.replace(t):Promise.resolve()},back(){if(g)return g.back()},matchRoute(t){return g?g.matchRoute(t):{route:null,params:{}}},resolveRouteComponent(t){return g?g.resolveRouteComponent(t):Promise.reject(new Error("No active router"))},base:"",scrollToFragment(t){return g?g.scrollToFragment(t):Promise.resolve(!1)}};function vt(t){const{routes:r,base:v="",initialUrl:a,scrollToFragment:l=!0}=t,o=ht(v),b=typeof l=="boolean"?{...rt,enabled:l}:{...rt,...l};let u,f,y,W,k,z,B;const _=new Set,K=10;let q=0;const J=async(s,i)=>{const e=Z(r,s.path);if(!e||!e.beforeEnter)return!0;try{const n=await e.beforeEnter(s,i);if(typeof n=="string"){const p=`${s.path}->${n}`;return _.has(p)||q>=K?(c.devError(`Redirect loop detected: ${p}`),!1):n}return n!==!1}catch(n){c.devError("beforeEnter error",n);try{y.setState(i)}catch{}throw n}},X=async(s,i)=>{const e=Z(r,s.path);if(!e||!e.onEnter)return!0;try{const n=await e.onEnter(s,i);if(typeof n=="string"){const p=`${s.path}->${n}`;return _.has(p)||q>=K?(c.devError(`Redirect loop detected: ${p}`),!1):n}return n!==!1}catch(n){c.devError("onEnter error",n);try{y.setState(i)}catch{}throw n}},et=(s,i)=>{const e=Z(r,s.path);if(!(!e||!e.afterEnter))try{e.afterEnter(s,i)}catch(n){c.devError("afterEnter error",n)}},I=new Map,M=100,T=s=>{if(I.has(s))return I.get(s);const i=F(r,s);if(I.size>=M){const e=Math.floor(M*.25),n=Array.from(I.keys());for(let p=0;p<e&&p<n.length;p++)I.delete(n[p])}return I.set(s,i),i},Y=()=>{};async function V(s,i=0){try{const e=document.getElementById(s);if(!e)return!1;if(i>0)try{const n=e.getBoundingClientRect(),p=Math.max(0,window.scrollY+n.top-i);typeof window.scrollTo=="function"&&window.scrollTo({top:p,behavior:"auto"})}catch{try{e.scrollIntoView()}catch{return!1}}else if(typeof e.scrollIntoView=="function")try{e.scrollIntoView({behavior:"auto",block:"start",inline:"nearest"})}catch{try{e.scrollIntoView()}catch{return!1}}return!0}catch{return!1}}function h(s,i=0,e=2e3){return new Promise(n=>{let p=!1,m=null;const w=Date.now(),S=P=>{p||(p=!0,m&&clearTimeout(m),n(P))},E=async()=>{if(!p)try{if(await V(s,i))return S(!0);const P=async()=>{if(p)return;if(Date.now()-w>=e)return S(!1);try{if(await V(s,i))return S(!0);requestAnimationFrame(P)}catch(gt){c.devWarn("Scroll retry attempt failed:",gt),requestAnimationFrame(P)}};requestAnimationFrame(P)}catch(P){c.devWarn("Initial scroll attempt failed:",P),S(!1)}};m=setTimeout(()=>{S(!1)},e),E().catch(P=>{c.devWarn("Scroll attempt failed:",P),S(!1)})})}let R=!1;const d=async(s,i=!1)=>{if(R){c.devWarn(`Navigation to ${s} blocked - navigation already in progress`);return}R=!0,q=0,_.clear();try{await D(s,i)}finally{R=!1,q=0,_.clear()}},O=s=>{const i=s.indexOf("#"),e=i>=0?s.slice(i+1):"",n=i>=0?s.slice(0,i):s,p=n.indexOf("?"),m=p>=0?n.slice(0,p):n,w=p>=0?tt(n.slice(p)):{},S=m.startsWith(o)?m.slice(o.length):m;return{path:A(S||"/"),query:w,fragment:e}},D=async(s,i=!1)=>{try{const e=O(s),n=T(e.path);if(!n.route)throw new Error(`No route found for ${e.path}`);const p=y.getState(),m={path:e.path,params:n.params,query:e.query,fragment:e.fragment},w=await J(m,p);if(w===!1)return;if(typeof w=="string"){q++;const E=`${m.path}->${w}`;_.add(E),await D(w,!0);return}const S=await X(m,p);if(S===!1)return;if(typeof S=="string"){q++;const E=`${m.path}->${S}`;_.add(E),await D(S,!0);return}if(typeof window<"u"&&typeof document<"u"){const E=ft(e.query),P=o+e.path+(E||"")+(e.fragment?"#"+e.fragment:"");i?window.history.replaceState({},"",P):window.history.pushState({},"",P)}if(y.setState(m),et(m,p),typeof window<"u"&&typeof document<"u")try{const E=m.fragment;b.enabled&&E&&h(String(E),b.offset,b.timeoutMs).catch(()=>{})}catch{}}catch(e){if(c.devError("Navigation error:",e),e instanceof Error&&(e.stack?.includes("runBeforeEnter")||e.stack?.includes("runOnEnter")))throw e;try{const n=y.getState();if(!F(r,n.path).route){let m=r.find(w=>w.path==="/");if(m||(m=r.find(w=>!w.path.includes(":")&&!w.path.includes("*"))),!m&&r.length>0&&(m=r[0]),m){const w=F(r,m.path);y.setState({path:m.path,params:w.params,query:{}})}else c.devError("No fallback route available for error recovery")}}catch(n){c.devWarn("State recovery failed during navigation error:",n)}}};if((s=>{if(!s||s.length===0)return c.devError("Router configuration error: No routes provided"),!1;const i=new Set;for(const e of s){if(!e.path)return c.devError("Router configuration error: Route missing path",e),!1;i.has(e.path)&&c.devWarn(`Duplicate route path detected: ${e.path}`),i.add(e.path),!e.component&&!e.load&&c.devWarn(`Route '${e.path}' has no component or load function`)}return!0})(r),typeof window>"u"||typeof a<"u"){for(const s of r)T(s.path);c.devWarn(`Pre-compiled ${r.length} routes for SSR`)}if(typeof window<"u"&&typeof document<"u"&&typeof a>"u"){u=()=>{try{const e=new URL(window.location.href),n=e.pathname,p=n.startsWith(o)?n.slice(o.length):n,m=A(p||"/"),w=tt(e.search),S=e.hash&&e.hash.length?e.hash.slice(1):"";return{path:m,query:w,fragment:S}}catch(e){return c.devWarn("Invalid URL detected, falling back to safe defaults",e),{path:"/",query:{},fragment:""}}},f=u();const s=T(f.path);y=ot.createStore({path:f.path,params:s.params,query:f.query,fragment:f.fragment}),W=async(e=!1)=>{const n=u();await d(n.path,e)};const i=()=>W(!0);window.addEventListener("popstate",i),k=e=>d(e,!1),z=e=>d(e,!0),B=()=>window.history.back()}else{u=()=>{try{const e=new URL(a||"/","http://localhost"),n=e.pathname,p=n.startsWith(o)?n.slice(o.length):n,m=A(p||"/"),w=tt(e.search),S=e.hash&&e.hash.length?e.hash.slice(1):"";return{path:m,query:w,fragment:S}}catch(e){return c.devWarn("Invalid SSR URL detected, falling back to safe defaults",e),{path:"/",query:{},fragment:""}}},f=u();const s=T(f.path);y=ot.createStore({path:f.path,params:s.params,query:f.query,fragment:f.fragment}),W=async()=>{const e=u();await i(e.path)};const i=async e=>{if(q++,q>K){c.devError(`SSR redirect depth exceeded for path: ${e}`);return}try{const n=O(e),p=T(n.path);if(!p.route)throw new Error(`No route found for ${n.path}`);const m=y.getState(),w={path:n.path,params:p.params,query:n.query,fragment:n.fragment},S=Z(r,w.path);if(S?.beforeEnter){const E=await S.beforeEnter(w,m);if(typeof E=="string"){const P=`${w.path}->${E}`;_.add(P),await i(E);return}if(E===!1)return}if(S?.onEnter){const E=await S.onEnter(w,m);if(typeof E=="string"){const P=`${w.path}->${E}`;_.add(P),await i(E);return}if(E===!1)return}y.setState(w),S?.afterEnter&&S.afterEnter(w,m)}catch(n){throw c.devError("SSR navigation error:",n),n}};k=async e=>(q=0,_.clear(),i(e)),z=async e=>(q=0,_.clear(),i(e)),B=()=>{}}return{_cleanupScrollState:Y,store:y,push:k,replace:z,back:B,subscribe:y.subscribe,matchRoute:s=>T(s),getCurrent:()=>y.getState(),resolveRouteComponent:yt,base:o,scrollToFragment:s=>{const i=s||y.getState().fragment;return!i||typeof window>"u"||typeof document>"u"?Promise.resolve(!1):h(i,b.offset,b.timeoutMs)}}}function At(t){pt();const r=vt(t),v=it();if(v)try{v._cleanupScrollState?.()}catch{}$t(r);try{Ct();try{typeof window<"u"&&$.flushDOMUpdates()}catch{}try{typeof window<"u"&&queueMicrotask(()=>{try{$.flushDOMUpdates()}catch{}})}catch{}}catch{}return x.component("router-view",async()=>{if(!it())return x.html`<div>Router not initialized.</div>`;const a=$.ref(C.getCurrent()),l=typeof window>"u";let o;l||(x.useOnConnected(()=>{try{typeof C.subscribe=="function"&&(o=C.subscribe(u=>{try{u&&typeof u=="object"&&typeof u.path=="string"?a.value=u:(c.devWarn("router-view received invalid state",u),a.value={path:"/",params:{},query:{}})}catch(f){c.devWarn("router-view subscription update failed",f);try{a.value={path:"/",params:{},query:{}}}catch{}}}))}catch(u){c.devWarn("router-view subscribe failed",u)}}),x.useOnDisconnected(()=>{if(typeof o=="function"){try{o()}catch(u){c.devWarn("router-view unsubscribe failed",u)}o=void 0}}));const b=C.matchRoute(a.value.path);if(!b||!b.route)return x.html`<div>Not found</div>`;try{const f=await C.resolveRouteComponent(b.route);if(typeof f=="string")return{tag:f,props:{},children:[]};if(typeof f=="function"){const y=f();return(y instanceof Promise?y:Promise.resolve(y)).then(k=>typeof k=="string"?{tag:k,props:{},children:[]}:k)}return x.html`<div>Invalid route component</div>`}catch{return x.html`<div>Invalid route component</div>`}}),x.component("router-link",()=>{const a=x.useProps({to:"",tag:"a",replace:!1,exact:!1,activeClass:"active",exactActiveClass:"exact-active",ariaCurrentValue:"page",disabled:!1,external:!1,class:"",style:""}),l=typeof window>"u",o=$.ref(C.getCurrent()),b=o.value?.path||"/",u=String(a.to||""),f=l?{isExactActive:lt(b,u,C.base),isActive:ut(b,u,C.base),isExternal:U(u)||!!a.external}:null;let y;x.useStyle(()=>"a,button{display:inline-block;}");const W=$.ref(a.class||""),k=$.ref(a.style||"");if(!l){let h=null;x.useOnConnected(R=>{try{if(typeof C.subscribe=="function"){y=C.subscribe(d=>{try{d&&typeof d=="object"&&typeof d.path=="string"?o.value=d:(c.devWarn("router-link received invalid state",d),o.value={path:"/",params:{},query:{}})}catch(O){c.devWarn("router-link subscription update failed",O);try{o.value={path:"/",params:{},query:{}}}catch{}}});try{const d=C.getCurrent();d&&typeof d.path=="string"&&(o.value=d)}catch(d){c.devWarn("router-link initial state sync failed",d)}h=setInterval(()=>{try{const d=C.getCurrent();d&&typeof d.path=="string"&&JSON.stringify(o.value)!==JSON.stringify(d)&&(o.value=d)}catch{}},100)}}catch(d){c.devWarn("router-link subscribe failed",d)}try{const d=R?._host;if(d instanceof HTMLElement){const O=d.getAttribute("class"),D=d.getAttribute("style");O&&(W.value=O),D&&(k.value=D),O!==null&&d.removeAttribute("class"),D!==null&&d.removeAttribute("style");try{R?._requestRender?.();try{$.flushDOMUpdates()}catch{}}catch{}}}catch(d){c.devWarn("router-link host migration failed",d)}}),x.useOnDisconnected(()=>{if(typeof y=="function")try{y()}catch(R){c.devWarn("router-link unsubscribe failed",R)}finally{y=void 0}if(h)try{clearInterval(h)}catch(R){c.devWarn("router-link sync interval cleanup failed",R)}finally{h=null}})}const z=$.computed(()=>{if(l&&f)return f.isExactActive;try{const h=C.base??"",R=a.to||"";return!o.value||typeof o.value.path!="string"?!1:lt(o.value.path,R,h)}catch(h){return c.devWarn("isExactActive computation error",h),!1}}),B=$.computed(()=>{if(l&&f)return f.isActive;try{const h=C.base??"",R=a.to||"";return!o.value||typeof o.value.path!="string"?!1:a.exact?z.value:ut(o.value.path,R,h)}catch(h){return c.devWarn("isActive computation error",h),!1}}),_=$.computed(()=>{const h=String(a.to||"");if(nt(h))return null;if(U(h))return h;const[R,d]=h.split("#"),[O,D]=(R||"").split("?"),H=C.base??"";let Q=O||"/";if(H&&H!=="/"){const s=A(H),i=A(Q);i.startsWith(s)?Q=i.slice(s.length)||"/":Q=i}const at=A(Q||"/");return H+at+(D?"?"+D:"")+(d?"#"+d:"")}),K=$.computed(()=>{const R=(W&&W.value||a.class||"").split(/\s+/).filter(Boolean),d={};for(const O of R)d[O]=!0;return d}),q=$.computed(()=>({...K.value,[a.activeClass||"active"]:B.value,[a.exactActiveClass||"exact-active"]:z.value})),J=$.computed(()=>Object.keys(q.value).filter(h=>q.value[h]).join(" ")),X=$.computed(()=>a.tag||"a"),et=$.computed(()=>X.value==="button"),I=$.computed(()=>z.value?a.ariaCurrentValue:null),M=$.computed(()=>!!a.disabled),T=$.computed(()=>{const h=String(a.to||"");return(U(h)||!!a.external)&&X.value==="a"}),Y=$.computed(()=>k&&k.value||a.style||""),V=h=>{if(h.defaultPrevented||h.button!==0||h.metaKey||h.altKey||h.ctrlKey||h.shiftKey)return;if(M.value){h.preventDefault();return}const R=String(a.to||"");if(nt(R)){try{h.preventDefault()}catch{}c.devWarn("Blocked unsafe javascript: URI in router-link.to");return}T.value||(h.preventDefault(),a.replace?C.replace(a.to):C.push(a.to))};return x.html`
2
2
  ${bt.match().when(et.value,x.html`
3
3
  <button
4
4
  part="button"
@@ -1,6 +1,6 @@
1
1
  import { a as y, d as I } from "./logger-BvkEbVM4.js";
2
- import { f as rt, r as tt, c as T } from "./namespace-helpers-DcD_6_K1.js";
3
- import { c as st, h as F, l as ct, m as it, b as bt, o as wt } from "./template-compiler-taX5Zg4G.js";
2
+ import { f as rt, r as tt, c as T } from "./namespace-helpers-DhLBqt-7.js";
3
+ import { c as st, h as F, l as ct, m as it, b as bt, o as wt } from "./template-compiler-D0LrTkNv.js";
4
4
  import { createStore as lt } from "./custom-elements-runtime.store.es.js";
5
5
  import { match as St } from "./custom-elements-runtime.directives.es.js";
6
6
  const ut = {
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./namespace-helpers-4qeKVqQw.cjs"),h=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function c(r,n){if(typeof r=="string")return t.escapeHTML(r);if(r.tag==="#text")return typeof r.children=="string"?t.escapeHTML(r.children):"";if(r.tag==="#anchor")return(Array.isArray(r.children)?r.children.filter(a=>a!=null):[]).map(a=>c(a,n)).join("");if(r.tag==="#raw")return typeof r.children=="string"?r.children:"";let e={};r.props&&r.props.attrs&&(e={...r.props.attrs});const s=n?.injectSvgNamespace??!0,g=n?.injectKnownNamespaces??s;s&&r.tag==="svg"&&!("xmlns"in e)?e.xmlns=t.SVG_NS:g&&r.tag in t.TAG_NAMESPACE_MAP&&!("xmlns"in e)&&(e.xmlns=t.TAG_NAMESPACE_MAP[r.tag]);const l=Object.entries(e).map(([i,a])=>` ${i}="${t.escapeHTML(String(a))}"`).join("");if(h.has(r.tag))return`<${r.tag}${l}>`;const p=Array.isArray(r.children)?r.children.filter(i=>i!=null).map(i=>c(i,n)).join(""):typeof r.children=="string"?t.escapeHTML(r.children):r.children?c(r.children,n):"";return`<${r.tag}${l}>${p}</${r.tag}>`}exports.clearRegisteredEntityMap=t.clearRegisteredEntityMap;exports.loadEntityMap=t.loadEntityMap;exports.registerEntityMap=t.registerEntityMap;exports.renderToString=c;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./namespace-helpers-Ctd_h7j2.cjs"),h=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function c(r,n){if(typeof r=="string")return t.escapeHTML(r);if(r.tag==="#text")return typeof r.children=="string"?t.escapeHTML(r.children):"";if(r.tag==="#anchor")return(Array.isArray(r.children)?r.children.filter(a=>a!=null):[]).map(a=>c(a,n)).join("");if(r.tag==="#raw")return typeof r.children=="string"?r.children:"";let e={};r.props&&r.props.attrs&&(e={...r.props.attrs});const s=n?.injectSvgNamespace??!0,g=n?.injectKnownNamespaces??s;s&&r.tag==="svg"&&!("xmlns"in e)?e.xmlns=t.SVG_NS:g&&r.tag in t.TAG_NAMESPACE_MAP&&!("xmlns"in e)&&(e.xmlns=t.TAG_NAMESPACE_MAP[r.tag]);const l=Object.entries(e).map(([i,a])=>` ${i}="${t.escapeHTML(String(a))}"`).join("");if(h.has(r.tag))return`<${r.tag}${l}>`;const p=Array.isArray(r.children)?r.children.filter(i=>i!=null).map(i=>c(i,n)).join(""):typeof r.children=="string"?t.escapeHTML(r.children):r.children?c(r.children,n):"";return`<${r.tag}${l}>${p}</${r.tag}>`}exports.clearRegisteredEntityMap=t.clearRegisteredEntityMap;exports.loadEntityMap=t.loadEntityMap;exports.registerEntityMap=t.registerEntityMap;exports.renderToString=c;
2
2
  //# sourceMappingURL=custom-elements-runtime.ssr.cjs.js.map
@@ -1,5 +1,5 @@
1
- import { e, S as f, T as g } from "./namespace-helpers-DcD_6_K1.js";
2
- import { g as j, l as A, h as E } from "./namespace-helpers-DcD_6_K1.js";
1
+ import { e, S as f, T as g } from "./namespace-helpers-DhLBqt-7.js";
2
+ import { g as j, l as A, h as E } from "./namespace-helpers-DhLBqt-7.js";
3
3
  const m = /* @__PURE__ */ new Set([
4
4
  "area",
5
5
  "base",
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./custom-elements-runtime.directives.cjs.js");const t=require("./transitions-Cm2TlhoN.cjs");exports.Transition=t.Transition;exports.TransitionGroup=t.TransitionGroup;exports.createTransitionPreset=t.createTransitionPreset;exports.getTransitionStyleSheet=t.getTransitionStyleSheet;exports.transitionPresets=t.transitionPresets;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./custom-elements-runtime.directives.cjs.js");const t=require("./transitions-f4KfN29T.cjs");exports.Transition=t.Transition;exports.TransitionGroup=t.TransitionGroup;exports.createTransitionPreset=t.createTransitionPreset;exports.getTransitionStyleSheet=t.getTransitionStyleSheet;exports.transitionPresets=t.transitionPresets;
2
2
  //# sourceMappingURL=custom-elements-runtime.transitions.cjs.js.map
@@ -1,5 +1,5 @@
1
1
  import "./custom-elements-runtime.directives.es.js";
2
- import { T as r, e as a, f as i, b as n, t as o } from "./transitions-Bo0DVkSp.js";
2
+ import { T as r, e as a, f as i, b as n, t as o } from "./transitions-DMJXs_tY.js";
3
3
  export {
4
4
  r as Transition,
5
5
  a as TransitionGroup,
@@ -0,0 +1,5 @@
1
+ "use strict";const d=require("./logger-CSALKaYm.cjs");function I(){const r=(()=>{try{return globalThis.process?.env?.NODE_ENV}catch{return}})(),e=(()=>{try{if(typeof window>"u")return{vitest:!1,cypress:!1};const n=window;return{vitest:!!n.__vitest__,cypress:!!n.Cypress}}catch{return{vitest:!1,cypress:!1}}})();return{isTest:r==="test"||e.vitest||e.cypress,isVitest:e.vitest,isCypress:e.cypress}}class L{pendingUpdates=new Map;isFlushScheduled=!1;isFlushing=!1;testEnv;lastCleanup=0;CLEANUP_INTERVAL=300*1e3;MAX_PENDING_SIZE=1e4;pendingIdleUpdates=new Map;idleCallbackHandle=null;constructor(){this.testEnv=I(),this.schedulePeriodicCleanup()}schedule(e,t){const n=t||e;this.pendingUpdates.size>=this.MAX_PENDING_SIZE&&this.performEmergencyCleanup(),this.pendingUpdates.set(n,e),this.isFlushScheduled||this.scheduleFlush()}scheduleFlush(){this.isFlushScheduled=!0,this.testEnv.isTest&&!this.isFlushing?this.flush():queueMicrotask(()=>this.flush())}flush(){if(this.isFlushing)return;this.isFlushing=!0;const e=this.pendingUpdates;this.pendingUpdates=new Map,this.isFlushScheduled=!1;try{for(const t of e.values())try{t()}catch(n){d.devError("Error in batched update:",n)}}finally{this.isFlushing=!1}}flushImmediately(){this.pendingUpdates.size!==0&&(this.isFlushScheduled=!1,this.flush())}get pendingCount(){return this.pendingUpdates.size}get hasPendingUpdates(){return this.pendingUpdates.size>0}get isFlushingUpdates(){return this.isFlushing}schedulePeriodicCleanup(){if(this.testEnv.isTest)return;const e=()=>{this.performPeriodicCleanup(),this.testEnv.isTest||setTimeout(e,this.CLEANUP_INTERVAL)};setTimeout(e,this.CLEANUP_INTERVAL)}performPeriodicCleanup(){const e=Date.now();e-this.lastCleanup<this.CLEANUP_INTERVAL||(this.pendingUpdates.size>100&&d.devWarn(`Scheduler has ${this.pendingUpdates.size} pending updates. Consider investigating.`),this.lastCleanup=e)}performEmergencyCleanup(){d.devWarn("Scheduler emergency cleanup: too many pending updates, clearing oldest entries");const e=Array.from(this.pendingUpdates.entries()),t=Math.floor(e.length/2);for(let n=0;n<t;n++)this.pendingUpdates.delete(e[n][0])}scheduleWithPriority(e,t="normal",n){if(t==="immediate"){try{e()}catch(i){d.devError("Error in immediate update:",i)}return}if(t==="idle"){const i=n??e;this.pendingIdleUpdates.size>=this.MAX_PENDING_SIZE&&this.performEmergencyCleanup(),this.pendingIdleUpdates.set(i,e),this.scheduleIdleFlush();return}const s=n??e;this.pendingUpdates.size>=this.MAX_PENDING_SIZE&&this.performEmergencyCleanup(),this.pendingUpdates.set(s,e),this.isFlushScheduled||(this.isFlushScheduled=!0,queueMicrotask(()=>this.flush()))}scheduleIdleFlush(){if(this.idleCallbackHandle===null){if(this.testEnv.isTest){this.idleCallbackHandle=setTimeout(()=>{this.idleCallbackHandle=null,this.flushIdleUpdates(null)},0);return}if(typeof requestIdleCallback<"u"){const e=requestIdleCallback(t=>{this.idleCallbackHandle=null,this.flushIdleUpdates(t)},{timeout:2e3});this.idleCallbackHandle=e}else this.idleCallbackHandle=setTimeout(()=>{this.idleCallbackHandle=null;const e=Date.now();this.flushIdleUpdates({timeRemaining:()=>Math.max(0,50-(Date.now()-e)),didTimeout:!1})},5)}}flushIdleUpdates(e){const t=Array.from(this.pendingIdleUpdates.entries());this.pendingIdleUpdates=new Map;for(let n=0;n<t.length;n++){if(e&&!e.didTimeout&&e.timeRemaining()<=0){for(let s=n;s<t.length;s++)this.pendingIdleUpdates.set(t[s][0],t[s][1]);this.scheduleIdleFlush();return}try{t[n][1]()}catch(s){d.devError("Error in idle update:",s)}}}}const p=new L;function D(r,e){p.schedule(r,e)}function P(r,e="normal",t){p.scheduleWithPriority(r,e,t)}function x(){p.flushImmediately()}function W(){return new Promise(r=>{p.hasPendingUpdates&&p.flushImmediately(),queueMicrotask(r)})}const _=new WeakSet;class F{static cache=new WeakMap;static arrayHandlerCache=new WeakMap;static objectHandlerCache=new WeakMap;static getOrCreateProxy(e,t,n=!1){const s=this.cache.get(e);if(s)return s;const i=n?this.getOrCreateArrayHandler(t):this.getOrCreateObjectHandler(t),a=new Proxy(e,i);try{U.markAsProxy(a)}catch{}return this.cache.set(e,a),a}static getOrCreateArrayHandler(e){if(!this.arrayHandlerCache.has(e)){const t={get:(n,s,i)=>{const a=Reflect.get(n,s,i);return typeof a=="function"&&typeof s=="string"&&["push","pop","shift","unshift","splice","sort","reverse","fill","copyWithin"].includes(s)?function(...u){const h=a.apply(n,u);return e.triggerUpdate(),h}:a!==null&&typeof a=="object"&&typeof s=="string"?e.makeReactiveValue(a):a},set:(n,s,i)=>(n[s]=e.makeReactiveValue(i),e.triggerUpdate(),!0),deleteProperty:(n,s)=>(delete n[s],e.triggerUpdate(),!0)};this.arrayHandlerCache.set(e,t)}return this.arrayHandlerCache.get(e)}static getOrCreateObjectHandler(e){if(!this.objectHandlerCache.has(e)){const t={get:(n,s,i)=>{const a=Reflect.get(n,s,i);return a!==null&&typeof a=="object"&&typeof s=="string"?e.makeReactiveValue(a):a},set:(n,s,i)=>(n[s]=e.makeReactiveValue(i),e.triggerUpdate(),!0),deleteProperty:(n,s)=>(delete n[s],e.triggerUpdate(),!0)};this.objectHandlerCache.set(e,t)}return this.objectHandlerCache.get(e)}static hasProxy(e){return this.cache.has(e)}static clear(){this.cache=new WeakMap,this.arrayHandlerCache=new WeakMap,this.objectHandlerCache=new WeakMap}static getStats(){return{hasCachedProxies:this.cache instanceof WeakMap}}}class U{static contextCache=new WeakMap;static createReactiveProxy(e,t,n){try{if(_.has(e))return e}catch{}const s=Array.isArray(e);let i=this.contextCache.get(t);i||(i=new WeakMap,this.contextCache.set(t,i));let a=i.get(n);return a||(a={triggerUpdate:t,makeReactiveValue:n},i.set(n,a)),F.getOrCreateProxy(e,a,s)}static markAsProxy(e){if(e)try{_.add(e)}catch{}}}let M=!1;function S(){return M}function O(){M=!0}function j(){M=!1}class V{currentComponentStack=[];componentData=new Map;stateStorage=new Map;trackingDisabled=!1;setCurrentComponent(e,t){if(this.currentComponentStack.push(e),!this.componentData.has(e))this.componentData.set(e,{dependencies:new Set,renderFn:t,stateIndex:0,lastWarnTime:0,watchers:new Map});else{const n=this.componentData.get(e);if(n.watchers&&n.watchers.size){for(const s of n.watchers.values())try{this.cleanup(s)}catch{}n.watchers.clear()}n.renderFn=t,n.stateIndex=0}}clearCurrentComponent(){this.currentComponentStack.pop()}getCurrentComponentId(){return this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null}registerWatcher(e,t){const n=this.componentData.get(e);n&&n.watchers.set(t,t)}disableTracking(){this.trackingDisabled=!0}enableTracking(){this.trackingDisabled=!1}isRenderingComponent(){return this.currentComponentStack.length>0}shouldEmitRenderWarning(){const e=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!e)return!0;const t=this.componentData.get(e);if(!t)return!0;const n=Date.now();return n-t.lastWarnTime<1e3?!1:(t.lastWarnTime=n,!0)}withoutTracking(e){const t=this.trackingDisabled;this.trackingDisabled=!0;try{return e()}finally{this.trackingDisabled=t}}getOrCreateState(e){const t=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!t)return new E(e);const n=this.componentData.get(t);if(!n)return new E(e);const s=`${t}:${n.stateIndex++}`;let i=this.stateStorage.get(s);return i||(i=new E(e),this.stateStorage.set(s,i)),i}trackDependency(e){if(this.trackingDisabled)return;const t=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!t)return;const n=this.componentData.get(t);n&&(n.dependencies.add(e),e.addDependent(t))}propagateDependencies(e){if(this.trackingDisabled)return;const t=this.currentComponentStack.length?this.currentComponentStack[this.currentComponentStack.length-1]:null;if(!t||t===e)return;const n=this.componentData.get(e);if(!n)return;const s=this.componentData.get(t);if(s)for(const i of n.dependencies)s.dependencies.add(i),i.addDependent(t)}triggerUpdate(e){const t=e.getDependents();for(const n of t){const s=this.componentData.get(n);s&&D(s.renderFn,n)}}cleanup(e){const t=this.componentData.get(e);if(t){for(const s of t.dependencies)s.removeDependent(e);this.componentData.delete(e)}const n=e+":";for(const s of this.stateStorage.keys())s.startsWith(n)&&this.stateStorage.delete(s)}}const c=new V;class E{_value;_rawValue;dependents=new Set;constructor(e){this._rawValue=e,this._value=this.makeReactive(e);try{Object.defineProperty(this,Symbol.for("@cer/ReactiveState"),{value:!0,enumerable:!1,configurable:!1})}catch{}}get value(){return c.trackDependency(this),this._value}set value(e){Object.is(e,this._rawValue)||(c.isRenderingComponent()&&c.shouldEmitRenderWarning()&&d.devWarn(`🚨 State modification detected during render! This can cause infinite loops.
2
+ • Move state updates to event handlers
3
+ • Use watchEffect/watch for side effects
4
+ • Ensure computed properties don't modify state`),this._rawValue=e,this._value=this.makeReactive(e),c.triggerUpdate(this))}peek(){return this._value}initSilent(e){this._rawValue=e,this._value=e}addDependent(e){this.dependents.add(e)}removeDependent(e){this.dependents.delete(e)}getDependents(){return this.dependents}makeReactive(e){return e===null||typeof e!="object"||e instanceof Node||e instanceof Element||e instanceof HTMLElement?e:U.createReactiveProxy(e,()=>c.triggerUpdate(this),t=>this.makeReactive(t))}}function z(r){return c.getOrCreateState(r===void 0?null:r)}function g(r){if(!r||typeof r!="object")return!1;try{const e=Symbol.for("@cer/ReactiveState");return Object.prototype.hasOwnProperty.call(r,e)}catch{return!1}}function q(r){let e,t=!0;const n=`computed-${crypto.randomUUID()}`,s=()=>{t=!0};try{const i=c.getCurrentComponentId();i&&c.registerWatcher(i,n)}catch{}return c.setCurrentComponent(n,s),e=r(),c.clearCurrentComponent(),t=!1,{get value(){return t&&(c.setCurrentComponent(n,s),e=r(),c.clearCurrentComponent(),t=!1),c.propagateDependencies(n),e}}}function G(r){if(S())return()=>{};const e=`effect-${crypto.randomUUID()}`;try{const n=c.getCurrentComponentId();n&&c.registerWatcher(n,e)}catch{}const t=()=>{c.setCurrentComponent(e,t);try{r()}finally{c.clearCurrentComponent()}};return t(),()=>{c.cleanup(e)}}function w(r,e=new WeakMap){if(r===null||typeof r!="object")return r;const t=r;if(e.has(t))return e.get(t);if(typeof Node<"u"&&t instanceof Node)return r;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t)){const s=[];e.set(t,s);for(let i=0;i<t.length;i++)s.push(w(t[i],e));return s}const n={};e.set(t,n);for(const s of Object.keys(t))try{n[s]=w(t[s],e)}catch{}return n}function $(r,e,t){if(S())return()=>{};let n;const s=g(r)?()=>r.value:r,i=`watch-${crypto.randomUUID()}`;try{const o=c.getCurrentComponentId();o&&c.registerWatcher(o,i)}catch{}const a=()=>{c.setCurrentComponent(i,a);const o=s();if(c.clearCurrentComponent(),t?.deep){const u=c.withoutTracking(()=>w(o));e(u,n),n=u}else o!==n&&(e(o,n),n=o)};return c.setCurrentComponent(i,a),n=s(),c.clearCurrentComponent(),t?.deep&&(n=c.withoutTracking(()=>w(n))),t&&t.immediate&&e(n,void 0),()=>{c.cleanup(i)}}const Z=r=>{try{r()}catch{}},m=new Map,y=new Map,C=new Map,k=500;let f,N,v=!1,A=!1,T;const X=!!globalThis.process?.versions?.node;function K(r){if(m.has(r))return m.get(r);const e=r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return m.size<k&&m.set(r,e),e}function B(r){if(y.has(r))return y.get(r);const e=r.replace(/-([a-z])/g,(t,n)=>n.toUpperCase());return y.size<k&&y.set(r,e),e}function J(r){if(typeof r=="string"){if(C.has(r))return C.get(r);const e=r.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]);return e!==r&&C.size<k&&C.set(r,e),e}return r}function l(r){if(!r)return"";const e=String(r);if(typeof document<"u"&&typeof document.createElement=="function"){const o=e.replace(/</g,"").replace(/>/g,""),u=T||(T=document.createElement("div"));try{l._el=u}catch{}return u.innerHTML=o,(u.textContent||"").replace(new RegExp("","g"),"<").replace(new RegExp("","g"),">")}const t={lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "},n=f??l._namedMap;let s=n;if(!s&&X)try{const i=globalThis.require;if(typeof i=="function"){const a=["@jasonshimmy/custom-elements-runtime/entities.json","../../entities.json","../../../entities.json","../entities.json","./entities.json"];for(const o of a)try{const u=i(o);if(u&&typeof u=="object"){s=u;break}}catch{}}}catch{}if(!s){s=t,v=!0;try{l._usedFallback=!0}catch{}const i=l._namedMapLoader??N;i&&i().then(a=>{f=a;try{l._namedMap=a}catch{}}).catch(()=>{})}if((v||l._usedFallback)&&!(A||l._warnedFallback)){A=!0;try{l._warnedFallback=!0}catch{}try{d.devWarn("decodeEntities: using small SSR fallback entity map. Register the full entities.json via registerEntityMap(entities) on the server to enable full HTML5 named-entity decoding.")}catch{}}return e.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g,(i,a)=>{if(a.charCodeAt(0)===35){const h=(a.charAt(1)||"").toLowerCase()==="x"?parseInt(a.slice(2),16):parseInt(a.slice(1),10);return Number.isNaN(h)?`&${a};`:String.fromCodePoint(h)}const o=s[a]??(n&&n[a]);return o!==void 0?o:`&${a};`})}async function b(){const r=["@jasonshimmy","custom-elements-runtime","entities.json"].join("/");try{const e=await import(r);return e&&(e.default||e)}catch{try{const e=[r,"./entities.json","../../entities.json","../../../entities.json"];for(const t of e)try{const n=await import(t);if(n)return n&&(n.default||n)}catch{}return{lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "}}catch{return{lt:"<",gt:">",amp:"&",quot:'"',apos:"'",nbsp:" "}}}}N=b;l._namedMapLoader=b;function Q(r,e){!r||typeof r!="object"||f&&!e?.overwrite||(f=r)}function Y(){f=void 0}function ee(r){const e=String(r);return{__unsafeHTML:e,__rawHTML:e}}function te(r){return!!r&&(typeof r.__unsafeHTML=="string"||typeof r.__rawHTML=="string")}function ne(r,e){if(typeof e=="string"){if(e==="")return;const t=e.split(".");let n=r;for(const s of t){if(n==null||typeof n!="object"){n=void 0;break}n=n[s]}return g(n)?n.value:n}return e}function re(r,e,t){const n=String(e).split("."),s=n.pop();if(!s)return;const i=n.reduce((a,o)=>(a[o]==null&&(a[o]={}),a[o]),r);g(i[s])?i[s].value=t:i[s]=t}function se(r){try{if(r&&typeof r=="object"){if(g(r))return r.value;if("value"in r){const e=r.value;return e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:r}}}catch{}return r}function ie(r){const e=se(r);if(e==null)return null;const t=typeof e;return t==="string"||t==="number"||t==="boolean"?String(e):null}function ae(r){if(!r||typeof r!="string")return!1;if(r==="class"||r.endsWith("Class"))return!0;if(r.includes("-"))try{if(r.split("-").some(t=>t==="class"))return!0}catch{}return!1}const R={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function ce(r,e,t){try{if(!e||!e.includes(":")){r.setAttribute(e,t);return}const n=e.indexOf(":"),s=e.substring(0,n),i=e.substring(n+1),a=R[s];a?r.setAttributeNS(a,i,t):r.setAttribute(e,t)}catch{try{r.setAttribute(e,t)}catch{}}}function oe(r,e){try{if(!e||!e.includes(":")){r.removeAttribute(e);return}const t=e.indexOf(":"),n=e.substring(0,t),s=e.substring(t+1),i=R[n];i?r.removeAttributeNS(i,s):r.removeAttribute(e)}catch{try{r.removeAttribute(e)}catch{}}}const H="http://www.w3.org/2000/svg",ue="http://www.w3.org/1998/Math/MathML",le={svg:H,math:ue};exports.ReactiveState=E;exports.SVG_NS=H;exports.TAG_NAMESPACE_MAP=le;exports.beginDiscoveryRender=O;exports.clearRegisteredEntityMap=Y;exports.computed=q;exports.decodeEntities=l;exports.endDiscoveryRender=j;exports.escapeHTML=J;exports.flushDOMUpdates=x;exports.getNestedValue=ne;exports.isClassLikeAttr=ae;exports.isDiscoveryRender=S;exports.isReactiveState=g;exports.isUnsafeHTML=te;exports.loadEntityMap=b;exports.nextTick=W;exports.reactiveSystem=c;exports.ref=z;exports.registerEntityMap=Q;exports.removeAttributeSmart=oe;exports.safe=Z;exports.safeSerializeAttr=ie;exports.scheduleDOMUpdate=D;exports.scheduleWithPriority=P;exports.setAttributeSmart=ce;exports.setNestedValue=re;exports.toCamel=B;exports.toKebab=K;exports.unsafeHTML=ee;exports.watch=$;exports.watchEffect=G;
5
+ //# sourceMappingURL=namespace-helpers-Ctd_h7j2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespace-helpers-Ctd_h7j2.cjs","sources":["../src/lib/runtime/scheduler.ts","../src/lib/runtime/reactive-proxy-cache.ts","../src/lib/runtime/discovery-state.ts","../src/lib/runtime/reactive.ts","../src/lib/runtime/helpers.ts","../src/lib/runtime/namespace-helpers.ts"],"sourcesContent":["/**\n * Update Scheduler for batching DOM updates\n * Prevents excessive re-renders and improves performance\n */\nimport { devWarn, devError } from './logger';\n\n/**\n * A scheduled update function to be executed in the next flush cycle.\n */\ntype ScheduledUpdate = () => void;\n\n/**\n * Scheduling priority for update tasks.\n *\n * - `'immediate'` — Run synchronously before returning (use sparingly).\n * - `'normal'` — Batch via microtask (default).\n * - `'idle'` — Defer to browser idle time via `requestIdleCallback`\n * (time-sliced, non-blocking rendering for low-priority work).\n */\nexport type UpdatePriority = 'immediate' | 'normal' | 'idle';\n\n/**\n * Environment detection utilities\n */\ninterface TestEnvironment {\n isTest: boolean;\n isVitest: boolean;\n isCypress: boolean;\n}\n\n/**\n * Detect test environment with improved reliability\n */\nfunction detectTestEnvironment(): TestEnvironment {\n // Check Node.js environment first\n const nodeEnv = (() => {\n try {\n const process = (\n globalThis as { process?: { env?: { NODE_ENV?: string } } }\n ).process;\n return process?.env?.NODE_ENV;\n } catch {\n return undefined;\n }\n })();\n\n // Check browser test environments\n const browserTestEnv = (() => {\n try {\n if (typeof window === 'undefined')\n return { vitest: false, cypress: false };\n\n const win = window as { __vitest__?: unknown; Cypress?: unknown };\n return {\n vitest: Boolean(win.__vitest__),\n cypress: Boolean(win.Cypress),\n };\n } catch {\n return { vitest: false, cypress: false };\n }\n })();\n\n const isTest =\n nodeEnv === 'test' || browserTestEnv.vitest || browserTestEnv.cypress;\n\n return {\n isTest,\n isVitest: browserTestEnv.vitest,\n isCypress: browserTestEnv.cypress,\n };\n}\n\nclass UpdateScheduler {\n private pendingUpdates = new Map<string | (() => void), ScheduledUpdate>();\n private isFlushScheduled = false;\n private isFlushing = false;\n private readonly testEnv: TestEnvironment;\n private lastCleanup = 0;\n private readonly CLEANUP_INTERVAL = 5 * 60 * 1000; // 5 minutes\n private readonly MAX_PENDING_SIZE = 10000; // Prevent memory bloat\n\n // Idle / time-sliced priority support\n private pendingIdleUpdates = new Map<\n string | (() => void),\n ScheduledUpdate\n >();\n private idleCallbackHandle: ReturnType<typeof setTimeout> | null = null;\n\n constructor() {\n // Cache environment detection result to avoid repeated checks\n this.testEnv = detectTestEnvironment();\n this.schedulePeriodicCleanup();\n }\n\n /**\n * Schedule an update to be executed in the next microtask\n * Uses component identity to deduplicate multiple render requests for the same component\n */\n schedule(update: () => void, componentId?: string): void {\n // IMPORTANT: Never use update.toString() as it breaks with minification!\n // Use the componentId if provided, otherwise use the function reference directly as the key\n // since Map supports using function references as keys (identity-based comparison)\n const key = componentId || update;\n\n // Prevent memory bloat by limiting pending updates\n if (this.pendingUpdates.size >= this.MAX_PENDING_SIZE) {\n this.performEmergencyCleanup();\n }\n\n this.pendingUpdates.set(key, update);\n\n if (!this.isFlushScheduled) {\n this.scheduleFlush();\n }\n }\n\n /**\n * Schedule the flush operation based on environment\n */\n private scheduleFlush(): void {\n this.isFlushScheduled = true;\n\n if (this.testEnv.isTest && !this.isFlushing) {\n // Safe to flush synchronously in test environment to avoid timing issues\n this.flush();\n } else {\n // Batch via microtask in production or when already flushing\n queueMicrotask(() => this.flush());\n }\n }\n\n /**\n * Execute all pending updates with priority ordering\n * Execute all pending updates with priority ordering\n */\n private flush(): void {\n // Prevent reentrant flushes\n if (this.isFlushing) {\n return;\n }\n\n this.isFlushing = true;\n\n // Capture current updates and reset state\n const updates = this.pendingUpdates;\n this.pendingUpdates = new Map();\n this.isFlushScheduled = false;\n\n try {\n // Execute all updates in batch\n for (const update of updates.values()) {\n try {\n update();\n } catch (error) {\n // Continue with other updates even if one fails\n devError('Error in batched update:', error);\n }\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n /**\n * Force flush any pending DOM updates immediately. This is useful in\n * test environments or callers that require synchronous guarantees after\n * state changes. Prefer relying on the scheduler's automatic flush when\n * possible; use this only when a caller needs to synchronously observe\n * rendered DOM changes.\n */\n flushImmediately(): void {\n if (this.pendingUpdates.size === 0) {\n return;\n }\n\n // Clear any scheduled flush since we're doing it now\n this.isFlushScheduled = false;\n this.flush();\n }\n\n /**\n * Get the number of pending updates\n */\n get pendingCount(): number {\n return this.pendingUpdates.size;\n }\n\n /**\n * Check if there are pending updates\n */\n get hasPendingUpdates(): boolean {\n return this.pendingUpdates.size > 0;\n }\n\n /**\n * Check if currently flushing updates\n */\n get isFlushingUpdates(): boolean {\n return this.isFlushing;\n }\n\n /**\n * Schedule periodic cleanup to prevent memory leaks\n */\n private schedulePeriodicCleanup(): void {\n if (this.testEnv.isTest) return; // Skip in tests\n\n const cleanup = () => {\n this.performPeriodicCleanup();\n if (!this.testEnv.isTest) {\n setTimeout(cleanup, this.CLEANUP_INTERVAL);\n }\n };\n\n setTimeout(cleanup, this.CLEANUP_INTERVAL);\n }\n\n /**\n * Perform periodic cleanup of stale entries\n */\n private performPeriodicCleanup(): void {\n const now = Date.now();\n if (now - this.lastCleanup < this.CLEANUP_INTERVAL) return;\n\n // In normal operation, pending updates should be processed quickly\n // If we have many pending updates for a long time, something might be wrong\n if (this.pendingUpdates.size > 100) {\n devWarn(\n `Scheduler has ${this.pendingUpdates.size} pending updates. Consider investigating.`,\n );\n }\n\n this.lastCleanup = now;\n }\n\n /**\n * Emergency cleanup when pending updates exceed safe limits\n */\n private performEmergencyCleanup(): void {\n devWarn(\n 'Scheduler emergency cleanup: too many pending updates, clearing oldest entries',\n );\n\n // Clear half of the pending updates (oldest first by insertion order)\n const entries = Array.from(this.pendingUpdates.entries());\n const toRemove = Math.floor(entries.length / 2);\n\n for (let i = 0; i < toRemove; i++) {\n this.pendingUpdates.delete(entries[i][0]);\n }\n }\n\n /**\n * Schedule an update with an explicit priority level.\n *\n * - `'immediate'` — Runs synchronously before returning.\n * - `'normal'` — Default microtask batching (same as `schedule()`).\n * - `'idle'` — Deferred to browser idle time via `requestIdleCallback`\n * with time-slicing to avoid blocking the main thread.\n * Falls back to a 5 ms `setTimeout` when\n * `requestIdleCallback` is unavailable (e.g. Safari < 16).\n *\n * @example Defer a low-priority analytics flush\n * ```ts\n * scheduleWithPriority(() => flushAnalytics(), 'idle');\n * ```\n */\n scheduleWithPriority(\n update: () => void,\n priority: UpdatePriority = 'normal',\n componentId?: string,\n ): void {\n if (priority === 'immediate') {\n try {\n update();\n } catch (error) {\n devError('Error in immediate update:', error);\n }\n return;\n }\n\n if (priority === 'idle') {\n const key = componentId ?? update;\n if (this.pendingIdleUpdates.size >= this.MAX_PENDING_SIZE) {\n this.performEmergencyCleanup();\n }\n this.pendingIdleUpdates.set(key, update);\n this.scheduleIdleFlush();\n return;\n }\n\n // 'normal' → microtask-batched path, always via queueMicrotask so that\n // multiple synchronous calls with the same componentId are deduped before\n // the flush fires (even in test environments where schedule() auto-flushes\n // synchronously to simplify timing).\n const key = componentId ?? update;\n if (this.pendingUpdates.size >= this.MAX_PENDING_SIZE) {\n this.performEmergencyCleanup();\n }\n this.pendingUpdates.set(key, update);\n if (!this.isFlushScheduled) {\n this.isFlushScheduled = true;\n queueMicrotask(() => this.flush());\n }\n }\n\n /**\n * Schedule a flush of idle-priority updates.\n * Uses `requestIdleCallback` when available; falls back to a short `setTimeout`.\n */\n private scheduleIdleFlush(): void {\n if (this.idleCallbackHandle !== null) return;\n\n if (this.testEnv.isTest) {\n // In tests, run after current call stack via microtask so updates are\n // observable synchronously in the same tick.\n this.idleCallbackHandle = setTimeout(() => {\n this.idleCallbackHandle = null;\n this.flushIdleUpdates(null);\n }, 0);\n return;\n }\n\n // Use requestIdleCallback when the browser supports it (Chrome/Firefox/Edge)\n if (typeof requestIdleCallback !== 'undefined') {\n const handle = requestIdleCallback(\n (deadline) => {\n this.idleCallbackHandle = null;\n this.flushIdleUpdates(deadline);\n },\n { timeout: 2000 },\n ) as unknown as ReturnType<typeof setTimeout>;\n this.idleCallbackHandle = handle;\n } else {\n // Polyfill: simulate a ~50 ms idle deadline via setTimeout\n this.idleCallbackHandle = setTimeout(() => {\n this.idleCallbackHandle = null;\n const start = Date.now();\n this.flushIdleUpdates({\n timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),\n didTimeout: false,\n });\n }, 5);\n }\n }\n\n /**\n * Process pending idle-priority updates in a time-sliced manner.\n * Yields back to the browser when the deadline's `timeRemaining()` reaches\n * zero and reschedules any unprocessed work.\n */\n private flushIdleUpdates(\n deadline: { timeRemaining: () => number; didTimeout: boolean } | null,\n ): void {\n // Snapshot and clear current idle queue\n const updates = Array.from(this.pendingIdleUpdates.entries());\n this.pendingIdleUpdates = new Map();\n\n for (let i = 0; i < updates.length; i++) {\n // Yield if we've used our idle time (unless the callback timed out,\n // in which case we must finish to avoid indefinite deferral)\n if (deadline && !deadline.didTimeout && deadline.timeRemaining() <= 0) {\n // Re-queue remaining work for the next idle window\n for (let j = i; j < updates.length; j++) {\n this.pendingIdleUpdates.set(updates[j][0], updates[j][1]);\n }\n this.scheduleIdleFlush();\n return;\n }\n\n try {\n updates[i][1]();\n } catch (error) {\n devError('Error in idle update:', error);\n }\n }\n }\n}\n\n// Global scheduler instance\nexport const updateScheduler = new UpdateScheduler();\n\n/**\n * Schedule a DOM update to be batched with optional component identity and priority\n * Schedule a DOM update to be batched with optional component identity and priority\n */\nexport function scheduleDOMUpdate(\n update: () => void,\n componentId?: string,\n): void {\n updateScheduler.schedule(update, componentId);\n}\n\n/**\n * Schedule an update with explicit priority.\n * See `UpdateScheduler.scheduleWithPriority` for full documentation.\n *\n * @example\n * ```ts\n * // Defer low-priority work to browser idle time (time-sliced, non-blocking)\n * scheduleWithPriority(() => updateAnalyticsDashboard(), 'idle');\n *\n * // Run a critical update before any async code resumes\n * scheduleWithPriority(() => updateCriticalUI(), 'immediate');\n * ```\n */\nexport function scheduleWithPriority(\n update: () => void,\n priority: UpdatePriority = 'normal',\n componentId?: string,\n): void {\n updateScheduler.scheduleWithPriority(update, priority, componentId);\n}\n\n/**\n * Force flush any pending DOM updates immediately. This is useful in\n * test environments or callers that require synchronous guarantees after\n * state changes. Prefer relying on the scheduler's automatic flush when\n * possible; use this only when a caller needs to synchronously observe\n * rendered DOM changes.\n */\nexport function flushDOMUpdates(): void {\n updateScheduler.flushImmediately();\n}\n\n/**\n * Returns a Promise that resolves after the next DOM update cycle completes.\n * Equivalent to Vue's `nextTick()` — useful when you need to observe DOM\n * state that reflects the latest reactive changes.\n *\n * @example\n * ```ts\n * count.value++;\n * await nextTick();\n * console.log(element.shadowRoot.querySelector('span').textContent); // updated\n * ```\n */\nexport function nextTick(): Promise<void> {\n // If there are pending updates, flush them and wait for the microtask queue to drain.\n // Otherwise, just wait one microtask so callers always get post-render timing.\n return new Promise<void>((resolve) => {\n if (updateScheduler.hasPendingUpdates) {\n updateScheduler.flushImmediately();\n }\n // Queue resolution after any pending microtasks (including the scheduler's queueMicrotask flush)\n queueMicrotask(resolve);\n });\n}\n","/**\n * Reactive proxy cache to optimize proxy creation and reuse\n * Uses WeakMap for automatic garbage collection when objects are no longer referenced\n */\n\n/**\n * Cache for reactive proxies to avoid creating multiple proxies for the same object\n */\n// legacy symbol marker removed — use WeakSet and non-enumerable flag instead\n// Track actual proxy instances with a WeakSet for robust detection\nconst proxiedObjects = new WeakSet<object>();\n// No legacy flag: rely solely on WeakSet and WeakMap for proxy detection\n\nclass ReactiveProxyCache {\n private static cache = new WeakMap<object, object>();\n private static arrayHandlerCache = new WeakMap<\n object,\n ProxyHandler<object>\n >();\n private static objectHandlerCache = new WeakMap<\n object,\n ProxyHandler<object>\n >();\n\n /**\n * Get or create a reactive proxy for an object\n */\n static getOrCreateProxy<T extends object>(\n obj: T,\n reactiveState: {\n triggerUpdate: () => void;\n makeReactiveValue: (value: unknown) => unknown;\n },\n isArray: boolean = false,\n ): T {\n // Check if we already have a cached proxy\n const cached = this.cache.get(obj);\n if (cached) {\n return cached as T;\n }\n\n // Create appropriate handler\n const handler = isArray\n ? this.getOrCreateArrayHandler(reactiveState)\n : this.getOrCreateObjectHandler(reactiveState);\n\n // Create proxy\n const proxy = new Proxy(obj, handler);\n\n // Mark and track the proxy instance (do this via the optimizer helper)\n try {\n ProxyOptimizer.markAsProxy(proxy as Record<string | symbol, unknown>);\n } catch {\n void 0;\n }\n\n // Cache the proxy by the original target object\n this.cache.set(obj, proxy);\n\n return proxy as T;\n }\n\n /**\n * Get or create a cached array handler\n */\n private static getOrCreateArrayHandler(reactiveState: {\n triggerUpdate: () => void;\n makeReactiveValue: (value: unknown) => unknown;\n }): ProxyHandler<object> {\n // Create a unique handler for this reactive state\n if (!this.arrayHandlerCache.has(reactiveState)) {\n const handler: ProxyHandler<unknown[]> = {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n\n // Intercept array mutating methods\n if (typeof value === 'function' && typeof prop === 'string') {\n const mutatingMethods = [\n 'push',\n 'pop',\n 'shift',\n 'unshift',\n 'splice',\n 'sort',\n 'reverse',\n 'fill',\n 'copyWithin',\n ];\n if (mutatingMethods.includes(prop)) {\n return function (...args: unknown[]) {\n const result = value.apply(target, args);\n // Trigger update after mutation\n reactiveState.triggerUpdate();\n return result;\n };\n }\n }\n\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof prop === 'string'\n ) {\n return reactiveState.makeReactiveValue(value);\n }\n return value;\n },\n set: (target, prop, value) => {\n (target as unknown as Record<string | symbol, unknown>)[prop] =\n reactiveState.makeReactiveValue(value);\n reactiveState.triggerUpdate();\n return true;\n },\n deleteProperty: (target, prop) => {\n delete (target as unknown as Record<string | symbol, unknown>)[prop];\n reactiveState.triggerUpdate();\n return true;\n },\n };\n\n this.arrayHandlerCache.set(reactiveState, handler);\n }\n\n return this.arrayHandlerCache.get(reactiveState)!;\n }\n\n /**\n * Get or create a cached object handler\n */\n private static getOrCreateObjectHandler(reactiveState: {\n triggerUpdate: () => void;\n makeReactiveValue: (value: unknown) => unknown;\n }): ProxyHandler<object> {\n // Create a unique handler for this reactive state\n if (!this.objectHandlerCache.has(reactiveState)) {\n const handler: ProxyHandler<Record<string | symbol, unknown>> = {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof prop === 'string'\n ) {\n return reactiveState.makeReactiveValue(value);\n }\n return value;\n },\n set: (target, prop, value) => {\n (target as Record<string | symbol, unknown>)[prop] =\n reactiveState.makeReactiveValue(value);\n reactiveState.triggerUpdate();\n return true;\n },\n deleteProperty: (target, prop) => {\n delete (target as Record<string | symbol, unknown>)[prop];\n reactiveState.triggerUpdate();\n return true;\n },\n };\n\n this.objectHandlerCache.set(reactiveState, handler);\n }\n\n return this.objectHandlerCache.get(reactiveState)!;\n }\n\n /**\n * Check if an object already has a cached proxy\n */\n static hasProxy(obj: object): boolean {\n return this.cache.has(obj);\n }\n\n /**\n * Clear all cached proxies (useful for testing)\n */\n static clear(): void {\n this.cache = new WeakMap();\n this.arrayHandlerCache = new WeakMap();\n this.objectHandlerCache = new WeakMap();\n }\n\n /**\n * Get cache statistics (for debugging)\n * Note: WeakMap doesn't provide size, so this is limited\n */\n static getStats(): { hasCachedProxies: boolean } {\n // WeakMap doesn't expose size, but we can check if we have any handlers cached\n return {\n hasCachedProxies: this.cache instanceof WeakMap,\n };\n }\n}\n\n/**\n * Optimized proxy creation utilities\n */\nclass ProxyOptimizer {\n // Cache a stable reactiveContext object keyed by onUpdate -> makeReactive\n // This allows handler caches in ReactiveProxyCache to reuse handlers\n // for identical reactive contexts instead of creating a new context object\n // on each createReactiveProxy call.\n private static contextCache = new WeakMap<\n (...args: unknown[]) => unknown,\n WeakMap<\n (...args: unknown[]) => unknown,\n {\n triggerUpdate: () => void;\n makeReactiveValue: (value: unknown) => unknown;\n }\n >\n >();\n /**\n * Create an optimized reactive proxy with minimal overhead\n */\n static createReactiveProxy<T extends object>(\n obj: T,\n onUpdate: () => void,\n makeReactive: (value: unknown) => unknown,\n ): T {\n // If the argument is already a proxy instance, return it directly.\n try {\n if (proxiedObjects.has(obj)) return obj;\n } catch {\n // ignore\n }\n\n const isArray = Array.isArray(obj);\n\n // Reuse a stable reactiveContext object per (onUpdate, makeReactive) pair.\n let inner = this.contextCache.get(onUpdate);\n if (!inner) {\n inner = new WeakMap();\n this.contextCache.set(onUpdate, inner);\n }\n let reactiveContext = inner.get(makeReactive);\n if (!reactiveContext) {\n reactiveContext = {\n triggerUpdate: onUpdate,\n makeReactiveValue: makeReactive,\n };\n inner.set(makeReactive, reactiveContext);\n }\n\n // Delegate to the cache which will return an existing proxy for the target\n // or create one if it doesn't exist yet.\n return ReactiveProxyCache.getOrCreateProxy(obj, reactiveContext, isArray);\n }\n\n /**\n * Mark an object as a proxy (for optimization)\n */\n static markAsProxy(obj: object): void {\n if (!obj) return;\n\n // Prefer adding the actual proxy instance to the WeakSet which does not trigger proxy traps\n try {\n proxiedObjects.add(obj);\n } catch {\n // ignore\n }\n }\n}\n\nexport { ReactiveProxyCache, ProxyOptimizer };\n","/**\n * discovery-state.ts\n *\n * Isolated discovery-render flag. Extracted from hooks.ts to break the\n * circular dependency between hooks.ts and reactive.ts — both modules need\n * to check `isDiscoveryRender()`, but hooks.ts also imports from reactive.ts.\n *\n * All side-effectful hooks (watchEffect, watch, useOnConnected, useStyle,\n * provide, inject, useEmit, …) must guard their setup with\n * `isDiscoveryRender()` and return early / return no-ops when it is true.\n */\n\nlet _discoveryRender = false;\n\n/**\n * Returns `true` while a discovery render is in progress.\n * Used by `html` tagged templates and hooks to short-circuit side effects.\n * @internal\n */\nexport function isDiscoveryRender(): boolean {\n return _discoveryRender;\n}\n\n/**\n * Mark the start of a discovery render pass.\n * Call this immediately before invoking the render function for the first time\n * (before `useProps` prop-name collection).\n * @internal\n */\nexport function beginDiscoveryRender(): void {\n _discoveryRender = true;\n}\n\n/**\n * Mark the end of a discovery render pass.\n * Call this in a `finally` block after the discovery render function returns.\n * @internal\n */\nexport function endDiscoveryRender(): void {\n _discoveryRender = false;\n}\n","import { scheduleDOMUpdate } from './scheduler';\nimport { ProxyOptimizer } from './reactive-proxy-cache';\nimport { devWarn } from './logger';\nimport { isDiscoveryRender } from './discovery-state';\nimport type { WatchOptions } from './types';\n\n/**\n * Global reactive system for tracking dependencies and triggering updates\n */\nclass ReactiveSystem {\n // Use a stack to support nested callers (component render -> watcher)\n // so that watchers can temporarily become the \"current component\" while\n // establishing dependencies without clobbering the outer component id.\n private currentComponentStack: string[] = [];\n // Consolidated component data: stores dependencies, render function, state index, and last warning time\n private componentData = new Map<\n string,\n {\n dependencies: Set<ReactiveState<unknown>>;\n renderFn: () => void;\n stateIndex: number;\n lastWarnTime: number;\n // watchers registered by the component during render\n watchers: Map<string, string>;\n }\n >();\n // Flat storage: compound key `${componentId}:${stateIndex}` -> ReactiveState\n private stateStorage = new Map<string, ReactiveState<unknown>>();\n private trackingDisabled = false;\n\n /**\n * Set the current component being rendered for dependency tracking\n */\n setCurrentComponent(componentId: string, renderFn: () => void): void {\n // Push onto the stack so nested calls can restore previous component\n this.currentComponentStack.push(componentId);\n // (no-op) push logged in debug builds\n if (!this.componentData.has(componentId)) {\n this.componentData.set(componentId, {\n dependencies: new Set(),\n renderFn,\n stateIndex: 0,\n lastWarnTime: 0,\n watchers: new Map(),\n });\n } else {\n const data = this.componentData.get(componentId)!;\n // Clean up watchers from previous renders so they don't accumulate\n if (data.watchers && data.watchers.size) {\n for (const wid of data.watchers.values()) {\n try {\n this.cleanup(wid);\n } catch {\n // swallow\n }\n }\n data.watchers.clear();\n }\n data.renderFn = renderFn;\n data.stateIndex = 0; // Reset state index for this render\n }\n }\n\n /**\n * Clear the current component after rendering\n */\n clearCurrentComponent(): void {\n // Pop the current component off the stack and restore the previous one\n this.currentComponentStack.pop();\n }\n\n /**\n * Get the current component id (top of stack) or null\n */\n getCurrentComponentId(): string | null {\n return this.currentComponentStack.length\n ? this.currentComponentStack[this.currentComponentStack.length - 1]\n : null;\n }\n\n /**\n * Register a watcher id under a component so it can be cleaned up on re-render\n */\n registerWatcher(componentId: string, watcherId: string): void {\n const data = this.componentData.get(componentId);\n if (!data) return;\n data.watchers.set(watcherId, watcherId);\n }\n\n /**\n * Temporarily disable dependency tracking\n */\n disableTracking(): void {\n this.trackingDisabled = true;\n }\n\n /**\n * Re-enable dependency tracking\n */\n enableTracking(): void {\n this.trackingDisabled = false;\n }\n\n /**\n * Check if a component is currently rendering\n */\n isRenderingComponent(): boolean {\n return this.currentComponentStack.length > 0;\n }\n\n /**\n * Return whether we should emit a render-time warning for the current component.\n * This throttles warnings to avoid spamming the console for legitimate rapid updates.\n */\n shouldEmitRenderWarning(): boolean {\n const current = this.currentComponentStack.length\n ? this.currentComponentStack[this.currentComponentStack.length - 1]\n : null;\n if (!current) return true;\n const data = this.componentData.get(current);\n if (!data) return true;\n\n const now = Date.now();\n const THROTTLE_MS = 1000; // 1 second per component\n if (now - data.lastWarnTime < THROTTLE_MS) return false;\n\n data.lastWarnTime = now;\n return true;\n }\n\n /**\n * Execute a function with tracking disabled\n */\n withoutTracking<T>(fn: () => T): T {\n const wasDisabled = this.trackingDisabled;\n this.trackingDisabled = true;\n try {\n return fn();\n } finally {\n this.trackingDisabled = wasDisabled;\n }\n }\n\n /**\n * Get or create a state instance for the current component\n */\n getOrCreateState<T>(initialValue: T): ReactiveState<T> {\n const current = this.currentComponentStack.length\n ? this.currentComponentStack[this.currentComponentStack.length - 1]\n : null;\n if (!current) {\n return new ReactiveState(initialValue);\n }\n\n const data = this.componentData.get(current);\n if (!data) {\n return new ReactiveState(initialValue);\n }\n const stateKey = `${current}:${data.stateIndex++}`;\n let state = this.stateStorage.get(stateKey) as ReactiveState<T> | undefined;\n\n if (!state) {\n state = new ReactiveState(initialValue);\n this.stateStorage.set(stateKey, state);\n }\n\n return state;\n }\n\n /**\n * Track a dependency for the current component\n */\n trackDependency(state: ReactiveState<unknown>): void {\n if (this.trackingDisabled) return;\n const current = this.currentComponentStack.length\n ? this.currentComponentStack[this.currentComponentStack.length - 1]\n : null;\n if (!current) return;\n\n const data = this.componentData.get(current);\n if (data) {\n data.dependencies.add(state);\n state.addDependent(current);\n // dependency tracked\n }\n }\n\n /**\n * Re-register all reactive dependencies that `fromId` tracks into the\n * currently-active (outer) component context.\n *\n * Used by `computed()` to forward its dep-set to the consuming component\n * without re-executing the getter function a second time.\n */\n propagateDependencies(fromId: string): void {\n if (this.trackingDisabled) return;\n const current = this.currentComponentStack.length\n ? this.currentComponentStack[this.currentComponentStack.length - 1]\n : null;\n if (!current || current === fromId) return;\n const sourceData = this.componentData.get(fromId);\n if (!sourceData) return;\n const targetData = this.componentData.get(current);\n if (!targetData) return;\n for (const state of sourceData.dependencies) {\n targetData.dependencies.add(state);\n state.addDependent(current);\n }\n }\n\n /**\n * Trigger updates for all components that depend on a state\n */\n triggerUpdate(state: ReactiveState<unknown>): void {\n const deps = state.getDependents();\n // trigger update for dependents\n for (const componentId of deps) {\n const data = this.componentData.get(componentId);\n if (data) {\n scheduleDOMUpdate(data.renderFn, componentId);\n }\n }\n }\n\n /**\n * Clean up component dependencies when component is destroyed\n */\n cleanup(componentId: string): void {\n const data = this.componentData.get(componentId);\n if (data) {\n for (const state of data.dependencies) {\n state.removeDependent(componentId);\n }\n this.componentData.delete(componentId);\n }\n // Remove any flat-stored state keys for this component\n const prefix = componentId + ':';\n for (const key of this.stateStorage.keys()) {\n if (key.startsWith(prefix)) {\n this.stateStorage.delete(key);\n }\n }\n }\n}\n\nconst reactiveSystem = new ReactiveSystem();\n\n// Export for internal use\nexport { reactiveSystem };\n\n/**\n * Internal reactive state class\n */\nexport class ReactiveState<T> {\n private _value: T;\n /** The unwrapped value last assigned — used for Object.is equality checks. */\n private _rawValue: T;\n private dependents = new Set<string>();\n\n constructor(initialValue: T) {\n this._rawValue = initialValue;\n this._value = this.makeReactive(initialValue);\n // Mark instances with a stable cross-bundle symbol so other modules\n // can reliably detect ReactiveState objects even when classes are\n // renamed/minified or when multiple copies of the package exist.\n try {\n // Use a global symbol key to make it resilient across realms/bundles\n const key = Symbol.for('@cer/ReactiveState');\n Object.defineProperty(this, key, {\n value: true,\n enumerable: false,\n configurable: false,\n });\n } catch {\n // ignore if Symbol.for or defineProperty fails in exotic runtimes\n }\n }\n\n get value(): T {\n // Track this state as a dependency when accessed during render\n reactiveSystem.trackDependency(this);\n return this._value;\n }\n\n set value(newValue: T) {\n // Skip update entirely when the new value is identical to the current raw\n // value. This prevents spurious triggerUpdate() calls and downstream\n // re-renders when the same primitive or same object reference is re-assigned\n // (e.g. setting viewYear.value = viewYear.value has zero cost).\n if (Object.is(newValue, this._rawValue)) return;\n\n // Check for state modifications during render (potential infinite loop)\n if (reactiveSystem.isRenderingComponent()) {\n if (reactiveSystem.shouldEmitRenderWarning()) {\n devWarn(\n '🚨 State modification detected during render! This can cause infinite loops.\\n' +\n ' • Move state updates to event handlers\\n' +\n ' • Use watchEffect/watch for side effects\\n' +\n \" • Ensure computed properties don't modify state\",\n );\n }\n }\n\n this._rawValue = newValue;\n this._value = this.makeReactive(newValue);\n // Trigger updates for all dependent components\n reactiveSystem.triggerUpdate(this);\n }\n\n /**\n * Read the current value without registering a reactive dependency.\n * Useful for internal infrastructure (e.g. stable hook slots) that must\n * inspect the stored value without re-triggering the containing component.\n * @internal\n */\n peek(): T {\n return this._value;\n }\n\n /**\n * Set the initial value without triggering any reactive updates or warnings.\n * Only intended for internal/infrastructure use (e.g. storing a stable hook\n * handle in a reactive slot without causing a spurious re-render).\n * The value is stored as-is without reactive proxy wrapping so that opaque\n * objects (e.g. TeleportHandle) are not accidentally instrumented.\n * @internal\n */\n initSilent(value: T): void {\n this._rawValue = value;\n this._value = value;\n }\n\n addDependent(componentId: string): void {\n this.dependents.add(componentId);\n }\n\n removeDependent(componentId: string): void {\n this.dependents.delete(componentId);\n }\n\n getDependents(): Set<string> {\n return this.dependents;\n }\n\n private makeReactive<U>(obj: U): U {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Skip reactivity for DOM nodes - they should not be made reactive\n if (\n (obj as unknown) instanceof Node ||\n (obj as unknown) instanceof Element ||\n (obj as unknown) instanceof HTMLElement\n ) {\n return obj;\n }\n\n // Use optimized proxy creation\n return ProxyOptimizer.createReactiveProxy(\n obj as unknown as object,\n () => reactiveSystem.triggerUpdate(this),\n (value: unknown) => this.makeReactive(value),\n ) as U;\n }\n}\n\n/**\n * Create reactive state that automatically triggers component re-renders\n * when accessed during render and modified afterwards.\n * Defaults to null if no initial value is provided (Vue-style ref).\n *\n * @example\n * ```ts\n * const counter = ref(0);\n * const user = ref({ name: 'John', age: 30 });\n * const emptyRef = ref(); // defaults to null\n *\n * // Usage in component\n * counter.value++; // triggers re-render\n * user.value.name = 'Jane'; // triggers re-render\n * console.log(emptyRef.value); // null\n * ```\n */\nexport function ref(): ReactiveState<null>;\nexport function ref<T>(initialValue: T): ReactiveState<T>;\nexport function ref<T>(initialValue?: T): ReactiveState<T | null> {\n // Ensure the created state has the union type T | null and explicitly\n // tell getOrCreateState the correct generic to avoid conditional-type recursion.\n return reactiveSystem.getOrCreateState<T | null>(\n (initialValue === undefined ? null : (initialValue as T)) as T | null,\n );\n}\n\n/**\n * Type guard to detect ReactiveState instances in a robust way that works\n * across bundlers, minifiers, and multiple package copies.\n */\nexport function isReactiveState(v: unknown): v is ReactiveState<unknown> {\n if (!v || typeof v !== 'object') return false;\n try {\n const key = Symbol.for('@cer/ReactiveState');\n // Safely check for the presence of the symbol-keyed property without indexing with a unique symbol\n return Object.prototype.hasOwnProperty.call(v, key);\n } catch {\n return false;\n }\n}\n\n/**\n * Create computed state that derives from other reactive state.\n * The result is cached and only recomputed when tracked reactive dependencies change.\n *\n * @example\n * ```ts\n * const firstName = ref('John');\n * const lastName = ref('Doe');\n * const fullName = computed(() => `${firstName.value} ${lastName.value}`);\n * console.log(fullName.value); // 'John Doe' — cached until firstName or lastName changes\n * ```\n */\nexport function computed<T>(fn: () => T): { readonly value: T } {\n let cachedValue: T;\n let isDirty = true;\n\n // Unique identifier used ONLY to track which reactive states this computed depends\n // on (for cache invalidation). It does NOT serve as a \"current component\" for\n // downstream notification — that is handled by running fn() in the outer context.\n const computedId = `computed-${crypto.randomUUID()}`;\n\n // invalidate() only marks the cache stale. It does NOT call triggerUpdate because\n // the calling component is notified directly via the outer fn() call (see get value()).\n const invalidate = (): void => {\n isDirty = true;\n };\n\n // Register under the current component (if inside a render) so cleanup is automatic.\n try {\n const parentComp = reactiveSystem.getCurrentComponentId();\n if (parentComp) {\n reactiveSystem.registerWatcher(parentComp, computedId);\n }\n } catch {\n /* ignore */\n }\n\n // Initial computation: establishes which reactive sources this computed depends on\n // for invalidation tracking.\n reactiveSystem.setCurrentComponent(computedId, invalidate);\n cachedValue = fn();\n reactiveSystem.clearCurrentComponent();\n isDirty = false;\n\n return {\n get value(): T {\n if (isDirty) {\n // Re-run fn() in computedId's context to re-subscribe for future invalidations.\n reactiveSystem.setCurrentComponent(computedId, invalidate);\n cachedValue = fn();\n reactiveSystem.clearCurrentComponent();\n isDirty = false;\n }\n\n // Forward the computed's tracked dependencies into the calling context so\n // that the outer component (or outer computed) is notified directly when any\n // dep changes — without re-executing fn() a second time.\n reactiveSystem.propagateDependencies(computedId);\n\n return cachedValue;\n },\n };\n}\n\n/**\n * Run a side-effect function immediately and automatically re-run it whenever\n * any reactive state accessed inside `fn` changes. Similar to Vue's `watchEffect`.\n *\n * @returns A cleanup function that stops the effect.\n *\n * @example\n * ```ts\n * const count = ref(0);\n * const stop = watchEffect(() => {\n * document.title = `Count: ${count.value}`;\n * });\n * count.value++; // automatically re-runs the effect\n * stop(); // cancel the effect\n * ```\n */\nexport function watchEffect(fn: () => void): () => void {\n // During discovery render, skip setting up effects — fn may have side effects\n // (API calls, mutations) that should only run in real render contexts.\n if (isDiscoveryRender()) return () => {};\n\n const effectId = `effect-${crypto.randomUUID()}`;\n\n // Register under the current component for automatic cleanup on re-render/destroy.\n try {\n const parentComp = reactiveSystem.getCurrentComponentId();\n if (parentComp) {\n reactiveSystem.registerWatcher(parentComp, effectId);\n }\n } catch {\n /* ignore */\n }\n\n const run = (): void => {\n reactiveSystem.setCurrentComponent(effectId, run);\n try {\n fn();\n } finally {\n reactiveSystem.clearCurrentComponent();\n }\n };\n\n // Run immediately to establish dependencies and execute the initial side effect.\n run();\n\n return () => {\n reactiveSystem.cleanup(effectId);\n };\n}\n\n/**\n * Recursively deep-clone a value into a plain (non-reactive) snapshot.\n *\n * Rules:\n * - Primitives and functions are returned as-is.\n * - `Date` instances are cloned.\n * - Arrays are cloned element-by-element (works through Proxy).\n * - Plain objects are cloned key-by-key (works through Proxy `get` traps).\n * - DOM nodes are returned as-is (cloning nodes is out of scope).\n * - Circular references are handled via a `WeakMap` seen-set.\n *\n * @internal — used by deep watchers to capture before/after state snapshots.\n */\nfunction deepClone<T>(value: T, seen = new WeakMap<object, unknown>()): T {\n if (value === null || typeof value !== 'object') return value;\n const obj = value as object;\n if (seen.has(obj)) return seen.get(obj) as T;\n // Do not attempt to clone DOM nodes\n if (typeof Node !== 'undefined' && obj instanceof Node) return value;\n // Clone Date\n if (obj instanceof Date) return new Date(obj.getTime()) as unknown as T;\n // Clone Array (Array.isArray is Proxy-transparent)\n if (Array.isArray(obj)) {\n const arr: unknown[] = [];\n seen.set(obj, arr);\n for (let i = 0; i < (obj as unknown[]).length; i++) {\n arr.push(deepClone((obj as unknown[])[i], seen));\n }\n return arr as unknown as T;\n }\n // Clone plain object (Object.keys + Reflect.get work through Proxy)\n const copy: Record<string, unknown> = {};\n seen.set(obj, copy);\n for (const key of Object.keys(obj)) {\n try {\n copy[key] = deepClone((obj as Record<string, unknown>)[key], seen);\n } catch {\n // skip inaccessible or throwing properties\n }\n }\n return copy as unknown as T;\n}\n\n/**\n * Create a watcher that runs when dependencies change\n *\n * @example\n * ```ts\n * const count = ref(0);\n * watch(() => count.value, (newVal, oldVal) => {\n * console.log(`Count changed from ${oldVal} to ${newVal}`);\n * });\n * ```\n */\nexport function watch<T>(\n source: ReactiveState<T>,\n callback: (newValue: T, oldValue?: T) => void,\n options?: WatchOptions,\n): () => void;\nexport function watch<T>(\n source: () => T,\n callback: (newValue: T, oldValue?: T) => void,\n options?: WatchOptions,\n): () => void;\nexport function watch<T>(\n source: ReactiveState<T> | (() => T),\n callback: (newValue: T, oldValue?: T) => void,\n options?: WatchOptions,\n): () => void {\n // During discovery render, skip setting up watchers — callbacks may contain\n // side effects that should only run against real component instances.\n if (isDiscoveryRender()) return () => {};\n\n // Note: we must establish reactive dependencies first (a tracked\n // call) and only then capture the initial `oldValue`. Capturing\n // `oldValue` before registering as a dependent means the first\n // tracked value may differ and lead to missed or spurious callbacks.\n let oldValue: T;\n // Normalize source: accept either a ReactiveState or a getter function\n const getter: () => T = ((): (() => T) => {\n // runtime check for ReactiveState instances\n if (isReactiveState(source)) {\n // cast to ReactiveState<T> and return getter\n return () => (source as ReactiveState<T>).value;\n }\n return source as () => T;\n })();\n\n // Create a dummy component to track dependencies\n const watcherId = `watch-${crypto.randomUUID()}`;\n\n // If called during a component render, register this watcher under that\n // component so watchers created in render are cleaned up on re-render.\n try {\n const parentComp = reactiveSystem.getCurrentComponentId();\n if (parentComp) {\n reactiveSystem.registerWatcher(parentComp, watcherId);\n }\n } catch {\n /* ignore */\n }\n\n const updateWatcher = () => {\n reactiveSystem.setCurrentComponent(watcherId, updateWatcher);\n const newValue = getter();\n reactiveSystem.clearCurrentComponent();\n\n if (options?.deep) {\n // Deep watchers: nested mutations keep the same proxy reference, so\n // reference equality is not a reliable change signal. Always fire\n // the callback and provide independent deep-cloned snapshots so\n // callers receive distinct before/after plain-object values.\n const newSnapshot = reactiveSystem.withoutTracking(() =>\n deepClone(newValue),\n ) as T;\n callback(newSnapshot, oldValue);\n oldValue = newSnapshot;\n } else if (newValue !== oldValue) {\n callback(newValue, oldValue);\n oldValue = newValue;\n }\n };\n\n // Initial run to establish dependencies\n reactiveSystem.setCurrentComponent(watcherId, updateWatcher);\n // Capture the tracked initial value as the baseline\n oldValue = getter();\n reactiveSystem.clearCurrentComponent();\n\n // For deep watchers, snapshot the initial value so that oldValue is a\n // stable plain-object clone that won't be mutated in-place by the user.\n if (options?.deep) {\n oldValue = reactiveSystem.withoutTracking(() => deepClone(oldValue)) as T;\n }\n\n // If immediate is requested, invoke the callback once with the\n // current value as `newValue` and `undefined` as the previous value\n // to match Vue's common semantics.\n if (options && options.immediate) {\n callback(oldValue, undefined);\n }\n\n // Return cleanup function\n return () => {\n reactiveSystem.cleanup(watcherId);\n };\n}\n","/**\n * Safe execution helper - silently ignores errors\n */\nexport const safe = (fn: () => void): void => {\n try {\n fn();\n } catch {\n void 0;\n }\n};\n\nimport { isReactiveState } from './reactive';\nimport { devWarn } from './logger';\n\n// Caches for string transformations to improve performance\nconst KEBAB_CASE_CACHE = new Map<string, string>();\nconst CAMEL_CASE_CACHE = new Map<string, string>();\nconst HTML_ESCAPE_CACHE = new Map<string, string>();\n\n// Cache size limits to prevent memory bloat\nconst MAX_CACHE_SIZE = 500;\n\n// Module-level state for entity map and loader. Using module-level vars avoids\n// reliance on attaching properties to functions which can be brittle when\n// minifiers are configured to mangle properties.\nlet _namedEntityMap: Record<string, string> | undefined;\n// eslint-disable-next-line prefer-const\nlet _namedEntityMapLoader: (() => Promise<Record<string, string>>) | undefined;\nlet _usedEntityFallback = false;\nlet _warnedEntityFallback = false;\n// Module-level decode element used in browser environments to avoid attaching\n// an element to the function object (function properties can be mangled by\n// aggressive minifiers). Keep a function-attached reference only for backward\n// compatibility but prefer `_decodeEl` at runtime.\nlet _decodeEl: HTMLDivElement | undefined;\n// NOTE (internal): The runtime prefers module-level state for the entity map\n// and decode element to ensure minifier-safe behavior in production builds.\n// We intentionally retain assignments to function-attached properties in a\n// few places solely for backward compatibility with older tests and code\n// paths. New code should rely on `registerEntityMap`, `loadEntityMap`, and\n// the exported `decodeEntities` function rather than inspecting internal\n// function properties.\n// Use globalThis to avoid TypeScript requiring Node typings for `process`.\nconst _isNode = !!(globalThis as { process?: { versions?: { node?: string } } })\n .process?.versions?.node;\n\n/**\n * Convert camelCase to kebab-case with caching\n */\nexport function toKebab(str: string): string {\n if (KEBAB_CASE_CACHE.has(str)) {\n return KEBAB_CASE_CACHE.get(str)!;\n }\n\n const result = str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n\n // Prevent memory bloat with size limit\n if (KEBAB_CASE_CACHE.size < MAX_CACHE_SIZE) {\n KEBAB_CASE_CACHE.set(str, result);\n }\n\n return result;\n}\n\n/**\n * Convert kebab-case to camelCase with caching\n */\nexport function toCamel(str: string): string {\n if (CAMEL_CASE_CACHE.has(str)) {\n return CAMEL_CASE_CACHE.get(str)!;\n }\n\n const result = str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n\n if (CAMEL_CASE_CACHE.size < MAX_CACHE_SIZE) {\n CAMEL_CASE_CACHE.set(str, result);\n }\n\n return result;\n}\n\n/**\n * Clear string transformation caches (useful for testing)\n */\nexport function clearStringCaches(): void {\n KEBAB_CASE_CACHE.clear();\n CAMEL_CASE_CACHE.clear();\n HTML_ESCAPE_CACHE.clear();\n}\n\n/**\n * Get cache statistics for debugging\n */\nexport function getStringCacheStats(): {\n kebabCacheSize: number;\n camelCacheSize: number;\n htmlEscapeCacheSize: number;\n} {\n return {\n kebabCacheSize: KEBAB_CASE_CACHE.size,\n camelCacheSize: CAMEL_CASE_CACHE.size,\n htmlEscapeCacheSize: HTML_ESCAPE_CACHE.size,\n };\n}\n\nexport function escapeHTML(\n str: string | number | boolean,\n): string | number | boolean {\n if (typeof str === 'string') {\n // Check cache first for frequently escaped strings\n if (HTML_ESCAPE_CACHE.has(str)) {\n return HTML_ESCAPE_CACHE.get(str)!;\n }\n\n const result = str.replace(\n /[&<>\"']/g,\n (c) =>\n ({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n })[c]!,\n );\n\n // Only cache strings that contain entities to escape\n if (result !== str && HTML_ESCAPE_CACHE.size < MAX_CACHE_SIZE) {\n HTML_ESCAPE_CACHE.set(str, result);\n }\n\n return result;\n }\n return str;\n}\n\n/**\n * Decode HTML entities (named and numeric) into their character equivalents.\n * - In browser: uses a DOM-based technique to decode entities while preserving\n * existing raw tags.\n * - In non-DOM (SSR) environments: handles numeric references and a conservative\n * named-entity map for common entities.\n *\n * @param str - string containing HTML entities\n * @returns decoded string\n */\nexport function decodeEntities(str: string): string {\n if (!str) return '';\n const s = String(str);\n\n // Browser environment: use a DOM element to decode the full set of named entities.\n if (\n typeof document !== 'undefined' &&\n typeof document.createElement === 'function'\n ) {\n const SENTINEL_L = '\\uF000';\n const SENTINEL_G = '\\uF001';\n // Protect existing literal tags so they won't be parsed as HTML by innerHTML\n const protectedStr = s.replace(/</g, SENTINEL_L).replace(/>/g, SENTINEL_G);\n\n // Prefer module-level el to avoid relying on function-attached properties\n // which can be renamed/mangled by some minifiers. Keep function-attached\n // `_el` for backward compatibility but do not depend on it.\n const el = _decodeEl || (_decodeEl = document.createElement('div'));\n try {\n (decodeEntities as { _el?: HTMLElement })._el = el;\n } catch {\n void 0;\n }\n\n el.innerHTML = protectedStr;\n const decoded = el.textContent || '';\n return decoded\n .replace(new RegExp(SENTINEL_L, 'g'), '<')\n .replace(new RegExp(SENTINEL_G, 'g'), '>');\n }\n\n // SSR / non-DOM fallback: handle numeric refs and named entities via an external JSON map.\n // Keep a tiny inline map for the most common entities so decodeEntities remains sync.\n const tinyMap: Record<string, string> = {\n lt: '<',\n gt: '>',\n amp: '&',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00A0',\n };\n\n // Prefer module-level registered map first (minifier-safe). Keep function\n // attached map as a fallback for backward compatibility only.\n const registered =\n _namedEntityMap ??\n (decodeEntities as { _namedMap?: Record<string, string> })._namedMap;\n\n // Select map: module-level registered > function-attached registered > sync require (Node-only) > tinyMap.\n let namedMap: Record<string, string> | undefined = registered;\n\n if (!namedMap && _isNode) {\n // Try to synchronously require the JSON in Node-like environments without importing `require`.\n try {\n // Use globalThis to avoid referencing `require` directly (prevents TS needing node types)\n const maybeRequire = (globalThis as { require?: (id: string) => unknown })\n .require;\n if (typeof maybeRequire === 'function') {\n // Try several common require paths (installed package, dist layout, src layout)\n const candidates = [\n '@jasonshimmy/custom-elements-runtime/entities.json', // installed package export\n '../../entities.json', // dist/runtime -> ../../entities.json\n '../../../entities.json', // src/lib/runtime -> ../../../entities.json\n '../entities.json',\n './entities.json',\n ];\n for (const p of candidates) {\n try {\n const m = maybeRequire(p);\n // Ensure the required value is an object before assigning and cast it to the expected type\n if (m && typeof m === 'object') {\n namedMap = m as Record<string, string>;\n break;\n }\n } catch {\n void 0;\n }\n }\n }\n } catch {\n void 0;\n }\n }\n\n // If we still don't have a map, fall back to tinyMap and trigger background loader if present.\n if (!namedMap) {\n namedMap = tinyMap;\n // Keep both module and function-level flags in sync for backward compatibility.\n // Mark fallback usage primarily on module-level flags (minifier-safe).\n _usedEntityFallback = true;\n try {\n (decodeEntities as { _usedFallback?: boolean })._usedFallback = true;\n } catch {\n void 0;\n }\n const loader =\n (\n decodeEntities as {\n _namedMapLoader?: () => Promise<Record<string, string>>;\n }\n )._namedMapLoader ?? _namedEntityMapLoader;\n if (loader) {\n // Load asynchronously; when ready, cache it for future sync calls and sync to function props.\n loader()\n .then((m: Record<string, string>) => {\n _namedEntityMap = m;\n try {\n (\n decodeEntities as { _namedMap?: Record<string, string> }\n )._namedMap = m;\n } catch {\n void 0;\n }\n })\n .catch(() => {});\n }\n }\n\n // Emit a one-time dev warning if we used the tiny fallback.\n // Prefer module-level flags first, then function-attached fallbacks for\n // backward compatibility. This avoids depending on function property names\n // which some minifiers may mangle.\n if (\n (_usedEntityFallback ||\n (decodeEntities as { _usedFallback?: boolean })._usedFallback) &&\n !(\n _warnedEntityFallback ||\n (decodeEntities as { _warnedFallback?: boolean })._warnedFallback\n )\n ) {\n _warnedEntityFallback = true;\n try {\n (decodeEntities as { _warnedFallback?: boolean })._warnedFallback = true;\n } catch {\n void 0;\n }\n try {\n devWarn(\n 'decodeEntities: using small SSR fallback entity map. Register the full entities.json via registerEntityMap(entities) on the server to enable full HTML5 named-entity decoding.',\n );\n } catch {\n void 0;\n }\n }\n\n // Replace entities: numeric (hex/dec) or named.\n return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (_, entity) => {\n if (entity.charCodeAt(0) === 35) {\n // '#'\n const isHex = (entity.charAt(1) || '').toLowerCase() === 'x';\n const num = isHex\n ? parseInt(entity.slice(2), 16)\n : parseInt(entity.slice(1), 10);\n return Number.isNaN(num) ? `&${entity};` : String.fromCodePoint(num);\n }\n const mapped =\n (namedMap as Record<string, string>)[entity] ??\n (registered && registered[entity]);\n return mapped !== undefined ? mapped : `&${entity};`;\n });\n}\n\n/**\n * Dynamically load the full named-entity map (used in SSR). Exported for testing and\n * to allow bundlers to exclude the JSON from client bundles when dynamic import\n * is used behind a DOM check.\n */\nexport async function loadEntityMap(): Promise<Record<string, string>> {\n // Prefer dynamic import so bundlers can code-split or ignore this file for browser bundles.\n // Try the published package export first; in installed packages this is usually the most\n // reliable path. Make the specifier a runtime string to discourage bundlers from inlining.\n const pkgExport = [\n '@jasonshimmy',\n 'custom-elements-runtime',\n 'entities.json',\n ].join('/');\n try {\n // @vite-ignore: dynamic import specifier constructed at runtime\n const mPkg = await import(/* @vite-ignore */ pkgExport as string);\n return (mPkg && (mPkg.default || mPkg)) as Record<string, string>;\n } catch {\n // Next try relative local JSON (useful during development or mono-repo installs)\n try {\n // Try several reasonable local import paths (development vs built layouts)\n const localCandidates = [\n pkgExport, // try package export via dynamic import too (best for installed packages)\n './entities.json',\n '../../entities.json',\n '../../../entities.json',\n ];\n for (const p of localCandidates) {\n try {\n // @vite-ignore: intentionally dynamic path candidates for dev/local resolution\n const mLocal = await import(/* @vite-ignore */ p as string);\n if (mLocal)\n return (mLocal && (mLocal.default || mLocal)) as Record<\n string,\n string\n >;\n } catch {\n void 0;\n }\n }\n // If none of the dynamic imports succeeded, fall back to the small map.\n return {\n lt: '<',\n gt: '>',\n amp: '&',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00A0',\n };\n } catch {\n // Final small fallback\n return {\n lt: '<',\n gt: '>',\n amp: '&',\n quot: '\"',\n apos: \"'\",\n nbsp: '\\u00A0',\n };\n }\n }\n}\n\n// Attach loader to module state and (for backward compatibility) to the function\n// as well. Using module-level state avoids property-mangling risks in minified\n// builds; attaching to the function keeps tests that reference the property\n// working until they can be updated.\n_namedEntityMapLoader = loadEntityMap;\n(\n decodeEntities as typeof decodeEntities & {\n _namedMapLoader?: typeof loadEntityMap;\n }\n)._namedMapLoader = loadEntityMap;\n\n/**\n * Register a full named-entity map for SSR. Intended for server startup code to\n * provide the authoritative HTML5 entity mapping. This keeps the client bundle\n * small because the map is only injected on the server side.\n *\n * registerEntityMap should be called once at server startup prior to rendering.\n */\nexport function registerEntityMap(\n map: Record<string, string>,\n options?: { overwrite?: boolean },\n): void {\n if (!map || typeof map !== 'object') return;\n const existing = _namedEntityMap;\n if (existing && !options?.overwrite) return; // first registration wins by default\n _namedEntityMap = map;\n}\n\n/**\n * Clear any registered entity map. Useful for tests or restarting state.\n */\nexport function clearRegisteredEntityMap(): void {\n _namedEntityMap = undefined;\n}\n\n/**\n * Wrap a string as raw HTML. This is intentionally unsafe — callers must\n * sanitize untrusted input before using this. The returned object provides\n * two property names to be compatible with different parts of the runtime.\n */\nexport function unsafeHTML(html: string): {\n __unsafeHTML: string;\n __rawHTML: string;\n} {\n const s = String(html);\n // Provide both property names to be compatible with compiler/renderer expectations\n return { __unsafeHTML: s, __rawHTML: s };\n}\n\n/** Type-guard for unsafeHTML wrapper */\nexport function isUnsafeHTML(\n value: unknown,\n): value is { __unsafeHTML?: string; __rawHTML?: string } {\n return (\n !!value &&\n (typeof (value as { __unsafeHTML?: unknown }).__unsafeHTML === 'string' ||\n typeof (value as { __rawHTML?: unknown }).__rawHTML === 'string')\n );\n}\n\n/**\n * Get nested property value from object using dot notation\n */\nexport function getNestedValue(\n obj: Record<string, unknown>,\n path: string,\n): unknown {\n if (typeof path === 'string') {\n // Handle empty path explicitly: return undefined to indicate no lookup\n if (path === '') return undefined;\n const keys = path.split('.');\n let current: unknown = obj;\n\n for (const key of keys) {\n if (current == null || typeof current !== 'object') {\n current = undefined;\n break;\n }\n current = (current as Record<string, unknown>)[key];\n }\n\n // If the result is a ReactiveState object, return its value\n if (isReactiveState(current)) {\n return (current as { value: unknown }).value;\n }\n return current;\n }\n return path;\n}\n\n/**\n * Set nested property value in object using dot notation\n */\nexport function setNestedValue(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): void {\n const keys = String(path).split('.');\n const lastKey = keys.pop();\n if (!lastKey) return;\n const target = keys.reduce(\n (current: Record<string, unknown>, key: string) => {\n if (current[key] == null) current[key] = {};\n return current[key] as Record<string, unknown>;\n },\n obj,\n ) as Record<string, unknown>;\n\n // If target[lastKey] is a ReactiveState object, set its value property\n if (isReactiveState(target[lastKey])) {\n target[lastKey].value = value;\n } else {\n target[lastKey] = value;\n }\n}\n\n/**\n * Safely unwrap reactive-like wrappers to their inner primitive when safe.\n * Returns the original value when it's not safe to coerce to a primitive.\n */\nexport function unwrapIfPrimitive(val: unknown): unknown {\n try {\n if (val && typeof val === 'object') {\n if (isReactiveState(val)) return (val as { value: unknown }).value;\n if ('value' in val) {\n const maybe = (val as { value: unknown }).value;\n // Only return primitive inner values; otherwise return original\n if (\n maybe === null ||\n maybe === undefined ||\n typeof maybe === 'string' ||\n typeof maybe === 'number' ||\n typeof maybe === 'boolean'\n ) {\n return maybe;\n }\n return val;\n }\n }\n } catch {\n // ignore\n }\n return val;\n}\n\n/**\n * Return a serialized string for an attribute value when safe to write to DOM.\n * Returns `null` when the value should not be written as an attribute.\n */\nexport function safeSerializeAttr(val: unknown): string | null {\n const v = unwrapIfPrimitive(val);\n if (v === null || v === undefined) return null;\n const t = typeof v;\n if (t === 'string' || t === 'number' || t === 'boolean') return String(v);\n return null; // complex objects, nodes, functions -> do not serialize\n}\n\n/**\n * Determine if an attribute name is class-like and should be preserved on hosts.\n * Class-like: exactly 'class', camelCase ending with 'Class', or kebab-case ending with '-class'.\n */\nexport function isClassLikeAttr(name: string): boolean {\n if (!name || typeof name !== 'string') return false;\n if (name === 'class') return true;\n if (name.endsWith('Class')) return true;\n // Kebab-case: consider attributes where one of the hyphen-separated tokens is 'class'\n if (name.includes('-')) {\n try {\n const parts = name.split('-');\n if (parts.some((p) => p === 'class')) return true;\n } catch {\n // fallthrough\n }\n }\n return false;\n}\n","/**\n * Namespace-aware attribute helpers.\n * Provides small, fast utilities to set/remove attributes using the\n * appropriate namespace when an attribute uses a known prefix (e.g. xlink:href).\n */\n\nconst ATTR_NAMESPACE_MAP: Record<string, string> = {\n xlink: 'http://www.w3.org/1999/xlink',\n xml: 'http://www.w3.org/XML/1998/namespace',\n};\n\n/**\n * Set attribute using namespace when the key contains a known prefix.\n */\nexport function setAttributeSmart(\n el: Element,\n key: string,\n value: string,\n): void {\n try {\n if (!key || !key.includes(':')) {\n el.setAttribute(key, value);\n return;\n }\n const idx = key.indexOf(':');\n const prefix = key.substring(0, idx);\n const local = key.substring(idx + 1);\n const ns = ATTR_NAMESPACE_MAP[prefix];\n if (ns) el.setAttributeNS(ns, local, value);\n else el.setAttribute(key, value);\n } catch {\n try {\n // Fallback to un-namespaced setAttribute on error\n el.setAttribute(key, value);\n } catch {\n /* swallow */\n }\n }\n}\n\n/**\n * Remove attribute using namespace when the key contains a known prefix.\n */\nexport function removeAttributeSmart(el: Element, key: string): void {\n try {\n if (!key || !key.includes(':')) {\n el.removeAttribute(key);\n return;\n }\n const idx = key.indexOf(':');\n const prefix = key.substring(0, idx);\n const local = key.substring(idx + 1);\n const ns = ATTR_NAMESPACE_MAP[prefix];\n if (ns) el.removeAttributeNS(ns, local);\n else el.removeAttribute(key);\n } catch {\n try {\n el.removeAttribute(key);\n } catch {\n /* swallow */\n }\n }\n}\n\nexport const __TEST_ONLY_ATTR_NS_MAP = ATTR_NAMESPACE_MAP;\n\n// Common element namespace URIs and a small tag->namespace map used by\n// both the client renderer and the SSR serializer. Exporting these from\n// this module keeps namespace knowledge centralized and prevents\n// accidental duplication between runtime and SSR code.\nexport const SVG_NS = 'http://www.w3.org/2000/svg';\nexport const MATHML_NS = 'http://www.w3.org/1998/Math/MathML';\n\nexport const TAG_NAMESPACE_MAP: Record<string, string> = {\n svg: SVG_NS,\n math: MATHML_NS,\n};\n"],"names":["detectTestEnvironment","nodeEnv","browserTestEnv","win","UpdateScheduler","update","componentId","key","updates","error","devError","cleanup","now","devWarn","entries","toRemove","i","priority","handle","deadline","start","j","updateScheduler","scheduleDOMUpdate","scheduleWithPriority","flushDOMUpdates","nextTick","resolve","proxiedObjects","ReactiveProxyCache","obj","reactiveState","isArray","cached","handler","proxy","ProxyOptimizer","target","prop","receiver","value","args","result","onUpdate","makeReactive","inner","reactiveContext","_discoveryRender","isDiscoveryRender","beginDiscoveryRender","endDiscoveryRender","ReactiveSystem","renderFn","data","wid","watcherId","current","fn","wasDisabled","initialValue","ReactiveState","stateKey","state","fromId","sourceData","targetData","deps","prefix","reactiveSystem","newValue","ref","isReactiveState","v","computed","cachedValue","isDirty","computedId","invalidate","parentComp","watchEffect","effectId","run","deepClone","seen","arr","copy","watch","source","callback","options","oldValue","getter","updateWatcher","newSnapshot","safe","KEBAB_CASE_CACHE","CAMEL_CASE_CACHE","HTML_ESCAPE_CACHE","MAX_CACHE_SIZE","_namedEntityMap","_namedEntityMapLoader","_usedEntityFallback","_warnedEntityFallback","_decodeEl","_isNode","toKebab","str","toCamel","_","letter","escapeHTML","c","decodeEntities","s","protectedStr","el","tinyMap","registered","namedMap","maybeRequire","candidates","p","m","loader","entity","num","mapped","loadEntityMap","pkgExport","mPkg","localCandidates","mLocal","registerEntityMap","map","clearRegisteredEntityMap","unsafeHTML","html","isUnsafeHTML","getNestedValue","path","keys","setNestedValue","lastKey","unwrapIfPrimitive","val","maybe","safeSerializeAttr","isClassLikeAttr","name","ATTR_NAMESPACE_MAP","setAttributeSmart","idx","local","ns","removeAttributeSmart","SVG_NS","MATHML_NS","TAG_NAMESPACE_MAP"],"mappings":"sDAiCA,SAASA,GAAyC,CAEhD,MAAMC,GAAW,IAAM,CACrB,GAAI,CAIF,OAFE,WACA,SACc,KAAK,QACvB,MAAQ,CACN,MACF,CACF,GAAA,EAGMC,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