@real-router/core 0.173.0 → 0.173.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/api.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{_ as e}from"./route-batch-BHxxucx6.mjs";import{A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,K as u,L as d,M as f,N as p,O as m,P as h,R as ee,S as g,T as _,U as v,V as y,W as b,_ as x,a as S,b as te,c as C,d as w,f as T,g as E,h as D,i as O,j as k,k as A,l as j,m as M,n as N,o as P,p as ne,q as re,r as ie,s as ae,t as oe,u as F,w as se,x as I,y as L,z as R}from"./Router-BuBcRFcb.mjs";import{C as z,E as ce,O as B,T as le,t as ue,z as V}from"./helpers-LeSZEDaV.mjs";const H=z(`router`);function U(e,t){if(e())throw H.code(V.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside a subscribeChanges handler — the mutation would run while a TREE_CHANGED emit is on the stack and the tree must stay atomic. Defer it: queueMicrotask(() => routes.add(...)) or await.`;if(t())throw H.code(V.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside replace()'s revalidation — the tree would move under a state that has not been revalidated yet. Defer it: queueMicrotask(() => routes.replace(...)) or await.`}function de(e,t,n){if(t){let r=t===e;if(r||t.startsWith(`${e}.`)){let i=r?``:` (current: "${t}")`;return n.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return!0}function fe(e,t){t.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. Removing a route the router is navigating to (or an ancestor of it) fails that navigation with "ROUTE_NOT_FOUND" — the rejected navigate() promise and onTransitionError carry the same code, and onTransitionCancel never fires. The committed state is not affected either way.`)}function W(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function pe(e,t,n,r){return n&&W(e)!==W(t)?(r.error(`router.setRootPath`,"Cannot change the root PATH while navigation is in progress — it moves every route's path, including the one being navigated to. Wait for navigation to complete. (Changing only the `?`-declared query names is allowed here: it moves no paths.)"),!1):!0}const G=z(`router`,`claimContextNamespace`),me=z(`router`,`extendRouter`),K=Object.freeze,q=Object.keys,J=new WeakMap;function he(t){let i=J.get(t);if(i)return i;let o=y(t),c={makeState:(e,t,n,r)=>o.makeState(e,t,n,r),forwardState:(e,t,r)=>(v(o.checks,n[`forwardState:entry`],e,t,r),o.forwardState(e,t,r)),matchPath:e=>o.matchPath(e,o.getOptions()),navigateToState:(e,t)=>o.navigateToState(e,t),setRootPath:e=>{if(b(o.isDisposed),U(o.routeGetStore().treeChanged.isEmitting,()=>o.routeGetStore().revalidating),!pe(o.getRootPath(),e,o.isTransitioning(),o.logger))return!1;let t=o.getRootPath();return o.setRootPath(e),t!==e&&o.routeGetStore().treeChanged.emit({op:`rootPath`,previous:t,next:e}),!0},getRootPath:o.getRootPath,addEventListener:(e,t)=>o.addEventListener(e,t),buildNavigationState:(t,r={},i={})=>{s(o,`buildNavigationState`,t,r);let c=ue(r);v(o.checks,n[`buildNavigationState:state`],t,c,i);let l=a(o.port(),t,c,i,{diagnoseUndeclared:!0});if(!o.buildStateResolved(l.name,l.path))return;e(`buildNavigationState`,l.name,l.path,o.port().queryNames(l.name));let u=se(l,_(l,o.port()));return o.port().reportCodecRoundTrip?.(u),u},buildPathResolved:(e,t,n)=>o.buildPathResolved(e,t,n),getAdoptedOrigins:o.getAdoptedOrigins,logger:K({log:(e,t,...n)=>{o.logger.log(e,t,...n)},warn:(e,t,...n)=>{o.logger.warn(e,t,...n)},error:(e,t,...n)=>{o.logger.error(e,t,...n)}}),getDeclaredQueryNames:e=>o.getDeclaredQueryNames(e),getUrlParams:e=>r(o.routeGetStore(),e),getForwardMap:()=>{let e=ce();return le(e,o.routeGetStore().config.forwardMap),K(e)},getResolvedLimits:()=>o.dependenciesGetStore().limits,getDependencyKeys:()=>K(q(o.dependenciesGetStore().dependencies)),getExternalGuardNames:()=>{let[e,t]=o.routeGetStore().lifecycleNamespace.getFactoriesByOrigin().external;return K([...new Set([...q(e),...q(t)])])},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{b(o.isDisposed),h(e,t);let n=o.interceptors.get(e);n||(n=[],o.interceptors.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},subscribeDiagnostic:o.subscribeDiagnostic,addCheck:(e,t)=>{b(o.isDisposed),k(e,t);let n=o.checks.get(e);n||(n=[],o.checks.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:e=>{b(o.isDisposed),f(e);let n=q(e);for(let e of n)if(e in t)throw me.code(V.PLUGIN_CONFLICT)`Cannot extend router: property "${e}" already exists`;let r=n.map(t=>e[t]),i={keys:n};for(let[e,i]of n.entries())t[i]=r[e];o.routerExtensions.push(i);let a=!1;return()=>{if(a)return;a=!0;for(let e of i.keys)delete t[e];let e=o.routerExtensions.indexOf(i);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{b(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:e=>{if(b(o.isDisposed),typeof e!=`string`||e===``)throw G.type`namespace must be a non-empty string, got ${typeof e==`string`?`an empty string`:typeof e}`;if(o.contextClaimRecords.has(e))throw G.code(V.CONTEXT_NAMESPACE_ALREADY_CLAIMED)`Cannot claim context namespace: "${e}" is already claimed by another plugin`;let t={write(n,r){o.contextClaimRecords.get(e)===t&&B(n.context,e,r)},release(){o.contextClaimRecords.get(e)===t&&o.contextClaimRecords.delete(e)}};return o.contextClaimRecords.set(e,t),t}},l=K(c);return J.set(t,l),l}const ge=z(`router`,`clear`),Y=Object.freeze,X=Object.keys,_e=Object.freeze({replace:!0,revalidate:!0}),ve=Object.freeze([]);function ye(e,t,n,r){let i=t=>e.has(t);I(t.decoders,i),I(t.encoders,i),I(t.defaultParams,i),I(t.defaultSearch,i),I(t.forwardMap,i),I(t.forwardFnMap,i),I(n,i),I(t.forwardMap,e=>i(t.forwardMap[e]));let[a,o]=r.getFactories();for(let e of X(o))i(e)&&r.clearCanActivate(e,`both`);for(let e of X(a))i(e)&&r.clearCanDeactivate(e,`both`)}function be(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.defaultSearch&&(e.defaultSearch=n.defaultSearch[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function xe(e,t,n,r){let i={name:e.name,path:e.path};return be(i,t,n,r),e.children&&B(i,`children`,e.children.map(e=>xe(e,`${t}.${e.name}`,n,r))),i}function Se(e,t,n,r){let i={name:e,path:t};return be(i,e,n,r),Y(i)}function Z(e,t){let n=new Map,r=e.lifecycleNamespace.getFactories(),i=(a,o)=>{for(let s of a){let a=o?`${o}.${s.name}`:s.name;t(a)&&n.set(a,Se(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function Ce(e,t){let n=Z(e,e=>t.has(e));return Y([...n.values()])}function we(e,t,n){let r=n.lifecycleNamespace.getFactories(),i=[],a=(e,t)=>{for(let o of e){let e=t?`${t}.${o.name}`:o.name;i.push(Se(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Y(i)}function Te(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:Y(n),added:Y(r)}}function Ee(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.defaultSearch!==void 0&&(t.defaultSearch=e.defaultSearch),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Y(t)}function De(e,t,n,r){S(e,t,n);let i=T(e,t,n,r);L(i.matcher,i.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(i.pendingCanActivate.keys(),i.pendingCanDeactivate.keys(),!1),O(e,i)}function Oe(e,t,n){e.systemCommit(t,n,_e)}function ke(e,t,n,r,i){j(t,`addRoute`),w(t,`addRoute`),P(t,`addRoute`),ae(t,``,`addRoute`),C(t,``,`addRoute`);let a=ne(t,e.rootPath,e.matcherOptions,n.logger);L(a.matcher,a.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(a.pendingCanActivate.keys(),a.pendingCanDeactivate.keys(),!0);let o=E(a,e.depsStore);e.lifecycleNamespace.clearDefinitionGuards(),O(e,a,o),b(n.isDisposed),e.revalidating=!0;let s=r();try{if(i?.(),s!==void 0){let t=n.matchPath(s.path,n.getOptions());if(t){if(t.name===s.name)Oe(n,{...t,context:s.context,transition:s.transition},s);else{let{toDeactivate:r,toActivate:i,intersection:a}=N(t,s,n.getMetaForState);if(e.lifecycleNamespace.canNavigateTo([],i,t,s,`replace`)){let e={phase:`activating`,from:s.name,reason:`success`,replace:!0,segments:{deactivated:r,activated:i,intersection:a}};Oe(n,{...t,transition:e},s)}else n.revalidateToNotFound(s.path)}}else n.revalidateToNotFound(s.path)}}finally{e.revalidating=!1}}function Ae(e,t,n){let r=e.definitions,i=g(r,t);if(i===void 0)return;let a=n?Ce(e,i):ve;return ye(i,e.config,e.routeCustomFields,e.lifecycleNamespace),D(e,r),a}function je(e,t){let n=e.matcher.getSegmentsByName(t);if(!n)return;let r=n.at(-1),i=u(r),a=e.lifecycleNamespace.getFactories();return xe(i,t,e.config,a)}const Q=new WeakMap;function Me(e){let t=Q.get(e);if(t)return t;let r=y(e),i=r.routeGetStore(),a=e=>{i.treeChanged.emit(e)},o=Y({add:(e,t)=>{b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating);let o=Array.isArray(e)?e:[e],s=t?.parent,c=d(o);if(v(r.checks,n[`addRoute:batch`],c,s),De(i,c,s,r.logger),b(r.isDisposed),i.treeChanged.listenerCount()>0){let e=we(c,s,i);a(s===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:s})}},remove:e=>{if(b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating),v(r.checks,n[`removeRoute:entry`],e),F(e,`removeRoute`),!de(e,r.getStateName(),r.logger))return;let t=i.treeChanged.listenerCount()>0,o=Ae(i,e,t);o===void 0?r.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`):(r.isTransitioning()&&fe(e,r.logger),t&&a({op:`remove`,name:e,removedSubtree:o}))},update:(e,t)=>{if(b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating),v(r.checks,n[`updateRoute:entry`],e,t),F(e,`updateRoute`),!i.matcher.hasRoute(e))return;r.isTransitioning()&&r.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`);let o=i.lifecycleNamespace,s=M(i,o,e,t);if(b(r.isDisposed),i.treeChanged.listenerCount()>0){let t=Ee(s);X(t).length>0&&a({op:`update`,name:e,patch:t})}},clear:()=>{if(b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating),r.getStateName()!==void 0)throw ge.code(V.ROUTER_NOT_STOPPED)`Cannot clear routes while a state is committed. Use replace(routes) to swap the tree on a running router, or stop() first.`;if(r.isTransitioning()){r.logger.error(`router.clear`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`);return}let e=i.treeChanged.listenerCount()>0?Y([...Z(i,()=>!0).values()]):void 0;x(i),i.lifecycleNamespace.clearAll(),e!==void 0&&a({op:`clear`,removed:e})},has:e=>(v(r.checks,n[`hasRoute:entry`],e),i.matcher.hasRoute(e)),get:e=>(v(r.checks,n[`getRoute:entry`],e),je(i,e)),replace:t=>{b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating);let o=Array.isArray(t)?t:[t];if(r.isTransitioning()){r.logger.error(`router.replace`,`Cannot replace routes while navigation is in progress. Wait for navigation to complete.`);return}let s=d(o);v(r.checks,n[`replaceRoutes:batch`],s);let c=i.treeChanged.listenerCount()>0?Z(i,()=>!0):void 0;ke(i,s,r,()=>e.getState(),c===void 0?void 0:()=>{let e=Z(i,()=>!0),{removed:t,added:n}=Te(c,e);a({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>(l(e),i.treeChanged.subscribe(e))});return Q.set(e,o),o}const Ne=Object.hasOwn,Pe=Object.keys,Fe=e=>typeof e==`symbol`?e:String(e),Ie=[];function Le(e,t,r,i){if(i===void 0)return;let a=e.dependencies,o=Fe(r),{diagnostics:s}=e,l=c(t,n[`setDependency:count`])||s.listenerCount(R.SET_DEPENDENCY_COUNT)>0||s.listenerCount(R.SET_DEPENDENCY_OVERWRITE)>0?Pe(a):Ie;if(l.includes(o)){let e=a[o];e!==i&&!(Number.isNaN(e)&&Number.isNaN(i))&&s.emit(R.SET_DEPENDENCY_OVERWRITE,String(o))}else v(t,n[`setDependency:count`],l.length,e.limits.maxDependencies),s.emit(R.SET_DEPENDENCY_COUNT,l.length,e.limits.maxDependencies);a[o]=i}function Re(e,r,i){let a=[],o=e.dependencies,{diagnostics:s}=e,l=new Set(c(r,n[`setDependencies:count`])||s.listenerCount(R.SET_DEPENDENCIES_COUNT)>0||s.listenerCount(R.SET_DEPENDENCIES_OVERWRITE)>0?Pe(o):Ie);ee(i,(i,c)=>{l.has(i)?a.push(i):(v(r,n[`setDependencies:count`],l.size,e.limits.maxDependencies),s.emit(R.SET_DEPENDENCIES_COUNT,l.size,e.limits.maxDependencies),l.add(i)),t(o,i,c)}),a.length>0&&s.emit(R.SET_DEPENDENCIES_OVERWRITE,a)}function ze(e){let t=y(e);return{get:e=>{v(t.checks,n[`getDependency:entry`],e);let r=t.dependenciesGetStore(),i=m(r,e);return v(t.checks,n[`getDependency:value`],e,i),i},getAll:()=>A(t.dependenciesGetStore()),set:(e,r)=>{b(t.isDisposed),v(t.checks,n[`setDependency:entry`],e,r),b(t.isDisposed),Le(t.dependenciesGetStore(),t.checks,e,r),b(t.isDisposed)},setAll:e=>{b(t.isDisposed),v(t.checks,n[`setDependencies:entry`],e),b(t.isDisposed),Re(t.dependenciesGetStore(),t.checks,e),b(t.isDisposed)},remove:e=>{b(t.isDisposed),v(t.checks,n[`removeDependency:entry`],e);let r=t.dependenciesGetStore(),i=Fe(e);Ne(r.dependencies,i)||r.diagnostics.emit(R.REMOVE_DEPENDENCY_MISSING,i),delete r.dependencies[i],b(t.isDisposed)},reset:()=>{b(t.isDisposed),i(t.dependenciesGetStore())},has:e=>(v(t.checks,n[`hasDependency:entry`],e),Ne(t.dependenciesGetStore().dependencies,e))}}function Be(e){let t=y(e),r=t.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,i){b(t.isDisposed),o(e,`addActivateGuard`),p(e,`addActivateGuard`),v(t.checks,n[`addActivateGuard:entry`],e,i),r.addCanActivate(e,i,!1),b(t.isDisposed)},addDeactivateGuard(e,i){b(t.isDisposed),o(e,`addDeactivateGuard`),p(e,`addDeactivateGuard`),v(t.checks,n[`addDeactivateGuard:entry`],e,i),r.addCanDeactivate(e,i,!1),b(t.isDisposed)},removeActivateGuard(e){b(t.isDisposed),o(e,`removeActivateGuard`),v(t.checks,n[`removeActivateGuard:entry`],e),r.clearCanActivate(e,`external`)},removeDeactivateGuard(e){b(t.isDisposed),o(e,`removeDeactivateGuard`),v(t.checks,n[`removeDeactivateGuard:entry`],e),r.clearCanDeactivate(e,`external`)}}}const $=Object.entries,Ve=Object.hasOwn,He=z(`cloneRouter`);function Ue(e,t,r){let i=y(e),a=()=>{if(i.isDisposed())throw He.code(V.ROUTER_DISPOSED)`cannot clone a disposed router — dispose() is terminal`};a(),v(i.checks,n[`cloneRouter:entry`],t);let o=i.routeGetStore(),s=re(o.tree),c=o.config,l=o.resolvedForwardMap,u=o.routeCustomFields,{options:d,dependencies:f,pluginFactories:p,loggerConfig:m,limits:h,limitKeys:g}=i.getCloneState(),{definition:_,external:b}=o.lifecycleNamespace.getFactoriesByOrigin(),x={...f};t!==void 0&&ee(t,(e,t)=>{B(x,e,t)});let S=r?.logger,C=S?{...m,...S}:m;a();let w=new oe(s,{...d,...o.matcherOptions?.queryParams!==void 0&&{queryParams:o.matcherOptions.queryParams},logger:C,...g!==void 0&&{limits:Object.fromEntries(g.filter(e=>Ve(h,e)).map(e=>[e,h[e]]))},...o.matcherOptions?.urlParamsEncoding!==void 0&&{urlParamsEncoding:o.matcherOptions.urlParamsEncoding}},x),T=y(w),E=T.routeGetStore(),D=E.lifecycleNamespace;te(E.config,c),ie(E,Object.assign(E.resolvedForwardMap,l)),Object.assign(E.routeCustomFields,u),o.rootPath!==``&&T.setRootPath(o.rootPath);let[O,k]=_,[A,j]=b;for(let[e,t]of $(O))D.addCanDeactivate(e,t,!0);for(let[e,t]of $(k))D.addCanActivate(e,t,!0);let M=Be(w);for(let[e,t]of $(A))M.addDeactivateGuard(e,t);for(let[e,t]of $(j))M.addActivateGuard(e,t);let N=new Set(T.getCloneState().pluginFactories),P=p.filter(e=>!N.has(e));return P.length>0&&w.usePlugin(...P),w}export{Ue as cloneRouter,ze as getDependenciesApi,Be as getLifecycleApi,he as getPluginApi,Me as getRoutesApi};
1
+ import{_ as e}from"./route-batch-LdEAJqGb.mjs";import{A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,K as u,L as d,M as f,N as p,O as m,P as h,R as ee,S as g,T as _,U as v,V as y,W as b,_ as x,a as S,b as te,c as C,d as w,f as T,g as E,h as D,i as O,j as k,k as A,l as j,m as M,n as N,o as P,p as ne,q as re,r as ie,s as ae,t as oe,u as F,w as se,x as I,y as L,z as R}from"./Router-CFnIWPT3.mjs";import{C as z,E as ce,O as B,T as le,t as ue,z as V}from"./helpers-LeSZEDaV.mjs";const H=z(`router`);function U(e,t){if(e())throw H.code(V.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside a subscribeChanges handler — the mutation would run while a TREE_CHANGED emit is on the stack and the tree must stay atomic. Defer it: queueMicrotask(() => routes.add(...)) or await.`;if(t())throw H.code(V.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside replace()'s revalidation — the tree would move under a state that has not been revalidated yet. Defer it: queueMicrotask(() => routes.replace(...)) or await.`}function de(e,t,n){if(t){let r=t===e;if(r||t.startsWith(`${e}.`)){let i=r?``:` (current: "${t}")`;return n.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return!0}function fe(e,t){t.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. Removing a route the router is navigating to (or an ancestor of it) fails that navigation with "ROUTE_NOT_FOUND" — the rejected navigate() promise and onTransitionError carry the same code, and onTransitionCancel never fires. The committed state is not affected either way.`)}function W(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function pe(e,t,n,r){return n&&W(e)!==W(t)?(r.error(`router.setRootPath`,"Cannot change the root PATH while navigation is in progress — it moves every route's path, including the one being navigated to. Wait for navigation to complete. (Changing only the `?`-declared query names is allowed here: it moves no paths.)"),!1):!0}const G=z(`router`,`claimContextNamespace`),me=z(`router`,`extendRouter`),K=Object.freeze,q=Object.keys,J=new WeakMap;function he(t){let i=J.get(t);if(i)return i;let o=y(t),c={makeState:(e,t,n,r)=>o.makeState(e,t,n,r),forwardState:(e,t,r)=>(v(o.checks,n[`forwardState:entry`],e,t,r),o.forwardState(e,t,r)),matchPath:e=>o.matchPath(e,o.getOptions()),navigateToState:(e,t)=>o.navigateToState(e,t),setRootPath:e=>{if(b(o.isDisposed),U(o.routeGetStore().treeChanged.isEmitting,()=>o.routeGetStore().revalidating),!pe(o.getRootPath(),e,o.isTransitioning(),o.logger))return!1;let t=o.getRootPath();return o.setRootPath(e),t!==e&&o.routeGetStore().treeChanged.emit({op:`rootPath`,previous:t,next:e}),!0},getRootPath:o.getRootPath,addEventListener:(e,t)=>o.addEventListener(e,t),buildNavigationState:(t,r={},i={})=>{s(o,`buildNavigationState`,t,r);let c=ue(r);v(o.checks,n[`buildNavigationState:state`],t,c,i);let l=a(o.port(),t,c,i,{diagnoseUndeclared:!0});if(!o.buildStateResolved(l.name,l.path))return;e(`buildNavigationState`,l.name,l.path,o.port().queryNames(l.name));let u=se(l,_(l,o.port()));return o.port().reportCodecRoundTrip?.(u),u},buildPathResolved:(e,t,n)=>o.buildPathResolved(e,t,n),getAdoptedOrigins:o.getAdoptedOrigins,logger:K({log:(e,t,...n)=>{o.logger.log(e,t,...n)},warn:(e,t,...n)=>{o.logger.warn(e,t,...n)},error:(e,t,...n)=>{o.logger.error(e,t,...n)}}),getDeclaredQueryNames:e=>o.getDeclaredQueryNames(e),getUrlParams:e=>r(o.routeGetStore(),e),getForwardMap:()=>{let e=ce();return le(e,o.routeGetStore().config.forwardMap),K(e)},getResolvedLimits:()=>o.dependenciesGetStore().limits,getDependencyKeys:()=>K(q(o.dependenciesGetStore().dependencies)),getExternalGuardNames:()=>{let[e,t]=o.routeGetStore().lifecycleNamespace.getFactoriesByOrigin().external;return K([...new Set([...q(e),...q(t)])])},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{b(o.isDisposed),h(e,t);let n=o.interceptors.get(e);n||(n=[],o.interceptors.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},subscribeDiagnostic:o.subscribeDiagnostic,addCheck:(e,t)=>{b(o.isDisposed),k(e,t);let n=o.checks.get(e);n||(n=[],o.checks.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:e=>{b(o.isDisposed),f(e);let n=q(e);for(let e of n)if(e in t)throw me.code(V.PLUGIN_CONFLICT)`Cannot extend router: property "${e}" already exists`;let r=n.map(t=>e[t]),i={keys:n};for(let[e,i]of n.entries())t[i]=r[e];o.routerExtensions.push(i);let a=!1;return()=>{if(a)return;a=!0;for(let e of i.keys)delete t[e];let e=o.routerExtensions.indexOf(i);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{b(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:e=>{if(b(o.isDisposed),typeof e!=`string`||e===``)throw G.type`namespace must be a non-empty string, got ${typeof e==`string`?`an empty string`:typeof e}`;if(o.contextClaimRecords.has(e))throw G.code(V.CONTEXT_NAMESPACE_ALREADY_CLAIMED)`Cannot claim context namespace: "${e}" is already claimed by another plugin`;let t={write(n,r){o.contextClaimRecords.get(e)===t&&B(n.context,e,r)},release(){o.contextClaimRecords.get(e)===t&&o.contextClaimRecords.delete(e)}};return o.contextClaimRecords.set(e,t),t}},l=K(c);return J.set(t,l),l}const ge=z(`router`,`clear`),Y=Object.freeze,X=Object.keys,_e=Object.freeze({replace:!0,revalidate:!0}),ve=Object.freeze([]);function ye(e,t,n,r){let i=t=>e.has(t);I(t.decoders,i),I(t.encoders,i),I(t.defaultParams,i),I(t.defaultSearch,i),I(t.forwardMap,i),I(t.forwardFnMap,i),I(n,i),I(t.forwardMap,e=>i(t.forwardMap[e]));let[a,o]=r.getFactories();for(let e of X(o))i(e)&&r.clearCanActivate(e,`both`);for(let e of X(a))i(e)&&r.clearCanDeactivate(e,`both`)}function be(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.defaultSearch&&(e.defaultSearch=n.defaultSearch[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function xe(e,t,n,r){let i={name:e.name,path:e.path};return be(i,t,n,r),e.children&&B(i,`children`,e.children.map(e=>xe(e,`${t}.${e.name}`,n,r))),i}function Se(e,t,n,r){let i={name:e,path:t};return be(i,e,n,r),Y(i)}function Z(e,t){let n=new Map,r=e.lifecycleNamespace.getFactories(),i=(a,o)=>{for(let s of a){let a=o?`${o}.${s.name}`:s.name;t(a)&&n.set(a,Se(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function Ce(e,t){let n=Z(e,e=>t.has(e));return Y([...n.values()])}function we(e,t,n){let r=n.lifecycleNamespace.getFactories(),i=[],a=(e,t)=>{for(let o of e){let e=t?`${t}.${o.name}`:o.name;i.push(Se(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Y(i)}function Te(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:Y(n),added:Y(r)}}function Ee(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.defaultSearch!==void 0&&(t.defaultSearch=e.defaultSearch),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Y(t)}function De(e,t,n,r){S(e,t,n);let i=T(e,t,n,r);L(i.matcher,i.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(i.pendingCanActivate.keys(),i.pendingCanDeactivate.keys(),!1),O(e,i)}function Oe(e,t,n){e.systemCommit(t,n,_e)}function ke(e,t,n,r,i){j(t,`addRoute`),w(t,`addRoute`),P(t,`addRoute`),ae(t,``,`addRoute`),C(t,``,`addRoute`);let a=ne(t,e.rootPath,e.matcherOptions,n.logger);L(a.matcher,a.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(a.pendingCanActivate.keys(),a.pendingCanDeactivate.keys(),!0);let o=E(a,e.depsStore);e.lifecycleNamespace.clearDefinitionGuards(),O(e,a,o),b(n.isDisposed),e.revalidating=!0;let s=r();try{if(i?.(),s!==void 0){let t=n.matchPath(s.path,n.getOptions());if(t){if(t.name===s.name)Oe(n,{...t,context:s.context,transition:s.transition},s);else{let{toDeactivate:r,toActivate:i,intersection:a}=N(t,s,n.getMetaForState);if(e.lifecycleNamespace.canNavigateTo([],i,t,s,`replace`)){let e={phase:`activating`,from:s.name,reason:`success`,replace:!0,segments:{deactivated:r,activated:i,intersection:a}};Oe(n,{...t,transition:e},s)}else n.revalidateToNotFound(s.path)}}else n.revalidateToNotFound(s.path)}}finally{e.revalidating=!1}}function Ae(e,t,n){let r=e.definitions,i=g(r,t);if(i===void 0)return;let a=n?Ce(e,i):ve;return ye(i,e.config,e.routeCustomFields,e.lifecycleNamespace),D(e,r),a}function je(e,t){let n=e.matcher.getSegmentsByName(t);if(!n)return;let r=n.at(-1),i=u(r),a=e.lifecycleNamespace.getFactories();return xe(i,t,e.config,a)}const Q=new WeakMap;function Me(e){let t=Q.get(e);if(t)return t;let r=y(e),i=r.routeGetStore(),a=e=>{i.treeChanged.emit(e)},o=Y({add:(e,t)=>{b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating);let o=Array.isArray(e)?e:[e],s=t?.parent,c=d(o);if(v(r.checks,n[`addRoute:batch`],c,s),De(i,c,s,r.logger),b(r.isDisposed),i.treeChanged.listenerCount()>0){let e=we(c,s,i);a(s===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:s})}},remove:e=>{if(b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating),v(r.checks,n[`removeRoute:entry`],e),F(e,`removeRoute`),!de(e,r.getStateName(),r.logger))return;let t=i.treeChanged.listenerCount()>0,o=Ae(i,e,t);o===void 0?r.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`):(r.isTransitioning()&&fe(e,r.logger),t&&a({op:`remove`,name:e,removedSubtree:o}))},update:(e,t)=>{if(b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating),v(r.checks,n[`updateRoute:entry`],e,t),F(e,`updateRoute`),!i.matcher.hasRoute(e))return;r.isTransitioning()&&r.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`);let o=i.lifecycleNamespace,s=M(i,o,e,t);if(b(r.isDisposed),i.treeChanged.listenerCount()>0){let t=Ee(s);X(t).length>0&&a({op:`update`,name:e,patch:t})}},clear:()=>{if(b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating),r.getStateName()!==void 0)throw ge.code(V.ROUTER_NOT_STOPPED)`Cannot clear routes while a state is committed. Use replace(routes) to swap the tree on a running router, or stop() first.`;if(r.isTransitioning()){r.logger.error(`router.clear`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`);return}let e=i.treeChanged.listenerCount()>0?Y([...Z(i,()=>!0).values()]):void 0;x(i),i.lifecycleNamespace.clearAll(),e!==void 0&&a({op:`clear`,removed:e})},has:e=>(v(r.checks,n[`hasRoute:entry`],e),i.matcher.hasRoute(e)),get:e=>(v(r.checks,n[`getRoute:entry`],e),je(i,e)),replace:t=>{b(r.isDisposed),U(i.treeChanged.isEmitting,()=>i.revalidating);let o=Array.isArray(t)?t:[t];if(r.isTransitioning()){r.logger.error(`router.replace`,`Cannot replace routes while navigation is in progress. Wait for navigation to complete.`);return}let s=d(o);v(r.checks,n[`replaceRoutes:batch`],s);let c=i.treeChanged.listenerCount()>0?Z(i,()=>!0):void 0;ke(i,s,r,()=>e.getState(),c===void 0?void 0:()=>{let e=Z(i,()=>!0),{removed:t,added:n}=Te(c,e);a({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>(l(e),i.treeChanged.subscribe(e))});return Q.set(e,o),o}const Ne=Object.hasOwn,Pe=Object.keys,Fe=e=>typeof e==`symbol`?e:String(e),Ie=[];function Le(e,t,r,i){if(i===void 0)return;let a=e.dependencies,o=Fe(r),{diagnostics:s}=e,l=c(t,n[`setDependency:count`])||s.listenerCount(R.SET_DEPENDENCY_COUNT)>0||s.listenerCount(R.SET_DEPENDENCY_OVERWRITE)>0?Pe(a):Ie;if(l.includes(o)){let e=a[o];e!==i&&!(Number.isNaN(e)&&Number.isNaN(i))&&s.emit(R.SET_DEPENDENCY_OVERWRITE,String(o))}else v(t,n[`setDependency:count`],l.length,e.limits.maxDependencies),s.emit(R.SET_DEPENDENCY_COUNT,l.length,e.limits.maxDependencies);a[o]=i}function Re(e,r,i){let a=[],o=e.dependencies,{diagnostics:s}=e,l=new Set(c(r,n[`setDependencies:count`])||s.listenerCount(R.SET_DEPENDENCIES_COUNT)>0||s.listenerCount(R.SET_DEPENDENCIES_OVERWRITE)>0?Pe(o):Ie);ee(i,(i,c)=>{l.has(i)?a.push(i):(v(r,n[`setDependencies:count`],l.size,e.limits.maxDependencies),s.emit(R.SET_DEPENDENCIES_COUNT,l.size,e.limits.maxDependencies),l.add(i)),t(o,i,c)}),a.length>0&&s.emit(R.SET_DEPENDENCIES_OVERWRITE,a)}function ze(e){let t=y(e);return{get:e=>{v(t.checks,n[`getDependency:entry`],e);let r=t.dependenciesGetStore(),i=m(r,e);return v(t.checks,n[`getDependency:value`],e,i),i},getAll:()=>A(t.dependenciesGetStore()),set:(e,r)=>{b(t.isDisposed),v(t.checks,n[`setDependency:entry`],e,r),b(t.isDisposed),Le(t.dependenciesGetStore(),t.checks,e,r),b(t.isDisposed)},setAll:e=>{b(t.isDisposed),v(t.checks,n[`setDependencies:entry`],e),b(t.isDisposed),Re(t.dependenciesGetStore(),t.checks,e),b(t.isDisposed)},remove:e=>{b(t.isDisposed),v(t.checks,n[`removeDependency:entry`],e);let r=t.dependenciesGetStore(),i=Fe(e);Ne(r.dependencies,i)||r.diagnostics.emit(R.REMOVE_DEPENDENCY_MISSING,i),delete r.dependencies[i],b(t.isDisposed)},reset:()=>{b(t.isDisposed),i(t.dependenciesGetStore())},has:e=>(v(t.checks,n[`hasDependency:entry`],e),Ne(t.dependenciesGetStore().dependencies,e))}}function Be(e){let t=y(e),r=t.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,i){b(t.isDisposed),o(e,`addActivateGuard`),p(e,`addActivateGuard`),v(t.checks,n[`addActivateGuard:entry`],e,i),r.addCanActivate(e,i,!1),b(t.isDisposed)},addDeactivateGuard(e,i){b(t.isDisposed),o(e,`addDeactivateGuard`),p(e,`addDeactivateGuard`),v(t.checks,n[`addDeactivateGuard:entry`],e,i),r.addCanDeactivate(e,i,!1),b(t.isDisposed)},removeActivateGuard(e){b(t.isDisposed),o(e,`removeActivateGuard`),v(t.checks,n[`removeActivateGuard:entry`],e),r.clearCanActivate(e,`external`)},removeDeactivateGuard(e){b(t.isDisposed),o(e,`removeDeactivateGuard`),v(t.checks,n[`removeDeactivateGuard:entry`],e),r.clearCanDeactivate(e,`external`)}}}const $=Object.entries,Ve=Object.hasOwn,He=z(`cloneRouter`);function Ue(e,t,r){let i=y(e),a=()=>{if(i.isDisposed())throw He.code(V.ROUTER_DISPOSED)`cannot clone a disposed router — dispose() is terminal`};a(),v(i.checks,n[`cloneRouter:entry`],t);let o=i.routeGetStore(),s=re(o.tree),c=o.config,l=o.resolvedForwardMap,u=o.routeCustomFields,{options:d,dependencies:f,pluginFactories:p,loggerConfig:m,limits:h,limitKeys:g}=i.getCloneState(),{definition:_,external:b}=o.lifecycleNamespace.getFactoriesByOrigin(),x={...f};t!==void 0&&ee(t,(e,t)=>{B(x,e,t)});let S=r?.logger,C=S?{...m,...S}:m;a();let w=new oe(s,{...d,...o.matcherOptions?.queryParams!==void 0&&{queryParams:o.matcherOptions.queryParams},logger:C,...g!==void 0&&{limits:Object.fromEntries(g.filter(e=>Ve(h,e)).map(e=>[e,h[e]]))},...o.matcherOptions?.urlParamsEncoding!==void 0&&{urlParamsEncoding:o.matcherOptions.urlParamsEncoding}},x),T=y(w),E=T.routeGetStore(),D=E.lifecycleNamespace;te(E.config,c),ie(E,Object.assign(E.resolvedForwardMap,l)),Object.assign(E.routeCustomFields,u),o.rootPath!==``&&T.setRootPath(o.rootPath);let[O,k]=_,[A,j]=b;for(let[e,t]of $(O))D.addCanDeactivate(e,t,!0);for(let[e,t]of $(k))D.addCanActivate(e,t,!0);let M=Be(w);for(let[e,t]of $(A))M.addDeactivateGuard(e,t);for(let[e,t]of $(j))M.addActivateGuard(e,t);let N=new Set(T.getCloneState().pluginFactories),P=p.filter(e=>!N.has(e));return P.length>0&&w.usePlugin(...P),w}export{Ue as cloneRouter,ze as getDependenciesApi,Be as getLifecycleApi,he as getPluginApi,Me as getRoutesApi};
2
2
  //# sourceMappingURL=api.mjs.map
@@ -1,2 +1,2 @@
1
- import{t as e,v as t}from"./Router-BuBcRFcb.mjs";import{B as n,I as r,R as i,b as a,z as o}from"./helpers-LeSZEDaV.mjs";const s=(t=[],n={},r={})=>new e(t,n,r),c=Object.freeze,l=new WeakMap,u=e=>{let t=l.get(e);return t||(t=c({navigate:e.navigate,getState:e.getState,isActiveRoute:e.isActiveRoute,canNavigateTo:e.canNavigateTo,subscribe:e.subscribe,subscribeLeave:e.subscribeLeave,isLeaveApproved:e.isLeaveApproved}),l.set(e,t)),t};export{e as Router,a as RouterError,r as UNKNOWN_ROUTE,i as constants,s as createRouter,o as errorCodes,n as events,u as getNavigator,t as resolveForwardChain};
1
+ import{t as e,v as t}from"./Router-CFnIWPT3.mjs";import{B as n,I as r,R as i,b as a,z as o}from"./helpers-LeSZEDaV.mjs";const s=(t=[],n={},r={})=>new e(t,n,r),c=Object.freeze,l=new WeakMap,u=e=>{let t=l.get(e);return t||(t=c({navigate:e.navigate,getState:e.getState,isActiveRoute:e.isActiveRoute,canNavigateTo:e.canNavigateTo,subscribe:e.subscribe,subscribeLeave:e.subscribeLeave,isLeaveApproved:e.isLeaveApproved}),l.set(e,t)),t};export{e as Router,a as RouterError,r as UNKNOWN_ROUTE,i as constants,s as createRouter,o as errorCodes,n as events,u as getNavigator,t as resolveForwardChain};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,2 @@
1
+ import{C as e,D as t,E as n,O as r}from"./helpers-LeSZEDaV.mjs";const i=Object.hasOwn;function a(e,t){if(t.length!==0&&e!=null)for(let n of t){if(!i(e,n))continue;let t;try{t=e[n]}catch{return}if(t!==void 0)return n}}function o(t,n,r,i,o,s){let l=a(r,i);if(l!==void 0)throw e(`router`,t).type`${c(n,l,typeof o==`function`?o():o,s)}`}function s(e,t,n,r){o(e,t,n,r,"the `params` bag this call is about to ship — the channel check above it read a different value, so the caller's object answered differently between the two reads")}function c(e,t,n="the `params` argument",r="Pass it in `search` instead"){return`Route "${e}" declares \`${t}\` as a query param, but it was given in ${n} — the path channel. ${r}; the two channels are separate since RFC-4 M2 and the router never moves a key between them.`}const l=e=>e===58||e===42;function u(e){let t=[],n=0;for(let r=0;r<e.length;r+=1)e.charCodeAt(r)===47&&(t.push(e.slice(n,r)),n=r+1);return t.push(e.slice(n)),t}function d(e){let t=e.length;if(t===0)return{kind:`static`,text:``};if(!l(e.charCodeAt(0))){for(let n=0;n<t;n+=1){let r=e.charCodeAt(n);if(r===60||r===62)return{error:`constraint-removed`};if(l(r)&&n+1<t)return{error:`fused-marker`}}return e.charCodeAt(t-1)===63?{error:`name-less`}:{kind:`static`,text:e}}let n=e.charCodeAt(0)===42,r=1;for(;r<t;){let t=e.charCodeAt(r);if(t===60||t===62||t===63)break;r+=1}let i=e.slice(1,r);return i.length===0?{error:`name-less`}:l(i.charCodeAt(i.length-1))?{error:`trailing-marker`}:r<t?e.charCodeAt(r)===63?{error:`optional-removed`}:{error:`constraint-removed`}:n?{kind:`splat`,name:i}:{kind:`param`,name:i}}function ee(e){for(let t of u(e)){let e=d(t);if(`error`in e)return e.error}}function f(e){let t=u(e);for(let e=0;e<t.length;e+=1){let n=d(t[e]);if(`error`in n){if(n.error===`optional-removed`){let n=t[e],r=[...t];return r[e]=n.slice(0,n.indexOf(`?`)),{code:`optional-removed`,segment:n,withoutSegment:t.filter((t,n)=>n!==e).join(`/`),requiredForm:r.join(`/`)}}return n.error===`constraint-removed`?{code:`constraint-removed`,segment:t[e]}:void 0}}}const p=/[<>]/u;function m(e){for(let t=0;t<e.length;t+=1){if(e.codePointAt(t)!==63)continue;let n=t+1<e.length?e.codePointAt(t+1):-1;if(![-1,47,63,60].includes(n))return t}return-1}const h=Object.freeze([]),g=Object.freeze({}),te=Object.freeze({urlParams:h,queryParams:h,paramTypeMap:g,pathPattern:``});function ne(e,t,n){for(let r of u(e)){if(r.length===0)continue;let e=d(r);`error`in e||e.kind===`static`||(t.push(e.name),n[e.name]=`url`)}}function _(e){let r=[],i=[],a=n(),o=m(e);if(o!==-1){let t=e.slice(o+1).split(`&`);for(let e of t){let t=e.trim();t.length>0&&(i.push(t),a[t]=`query`)}e=e.slice(0,o)}return ne(e,r,a),v(r,i,t(a),e)}function v(e,t,n,r){return{urlParams:e.length===0?h:e,queryParams:t.length===0?h:t,paramTypeMap:e.length===0&&t.length===0?g:n,pathPattern:r}}const y=e=>{let t=e.indexOf(`%`),n=e.indexOf(`+`);if(t===-1&&n===-1)return e;let r=n===-1?e:e.replaceAll(`+`,` `);return t===-1?r:decodeURIComponent(r)},b=(e,t)=>{if(e===void 0)return t.boolean.decodeUndefined();let n=t.boolean.decodeRaw(e);if(n!==null)return n;let r=y(e),i=t.number.decode(r);return i===null?t.boolean.decodeValue(r):i},re=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,x=e=>{try{return encodeURIComponent(e)}catch(t){if(!(t instanceof URIError))throw t;return encodeURIComponent(String(e).replaceAll(re,`�`))}},ie=e(`router`),S=e=>{let t=typeof e;if(t!==`string`&&t!==`number`&&t!==`boolean`)throw ie.type`Invalid query value: an array element must be a string, number, or boolean — received ${t}`;return x(e)},C=(e,t,n,r)=>{let i=`${e}${n}`,a=[];for(let e of t)if(e===null){let e=r.encode(i);e&&a.push(e)}else a.push(`${i}=${S(e)}`);return a.join(`&`)},w={none:{encodeArray:(e,t,n)=>C(e,t,``,n)},brackets:{encodeArray:(e,t,n)=>C(e,t,`[]`,n)},index:{encodeArray:(e,t,n)=>{let r=[];for(let[i,a]of t.entries()){let t=`${e}[${i}]`;if(a===null){let e=n.encode(t);e&&r.push(e)}else r.push(`${t}=${S(a)}`)}return r.join(`&`)},indexed:!0},comma:{encodeArray:(e,t)=>{let n=[];for(let e of t)e!==null&&n.push(S(e));return n.length===0?``:`${e}=${n.join(`,`)}`},decodeValue:e=>e.includes(`,`)?e.split(`,`):null}},T={none:{encode:(e,t)=>`${e}=${t}`,decodeUndefined:()=>null,decodeRaw:()=>null,decodeValue:e=>e},auto:{encode:(e,t)=>`${e}=${t}`,decodeUndefined:()=>null,decodeRaw:e=>e===`true`||e!==`false`&&null,decodeValue:e=>e},"empty-true":{encode:(e,t)=>t?e:`${e}=false`,decodeUndefined:()=>!0,decodeRaw:e=>e===`true`||e!==`false`&&null,decodeValue:e=>e}},E={default:{encode:e=>e},hidden:{encode:()=>``}},D={auto:{decode:e=>{let t=e.length;if(t===0)return null;let n=+(e.codePointAt(0)===45);if(n===t||t-n>1&&e.codePointAt(n)===48&&e.codePointAt(n+1)!==46)return null;let r=!1;for(let i=n;i<t;i++){let a=e.codePointAt(i);if(!(a!==void 0&&a>=48&&a<=57)){if(a===46&&!r&&i!==n&&i!==t-1)r=!0;else return null}}let i=Number(e);return String(i)!==e||!Number.isSafeInteger(i)&&!r?null:i}},none:{decode:()=>null}},ae=e(`router`),oe=Object.defineProperty,se=Object.keys,ce=Object.hasOwn,le=Symbol.for(`real-router.searchParams.configFault`),O=(e,t,n)=>{let r=typeof t==`string`?t:String(t);if(!ce(e,r)){let t=ae.type`Invalid "queryParams.${n}": "${r}" — expected ${se(e).map(e=>`"${e}"`).join(` | `)}`;throw oe(t,le,{value:!0}),t}return e[r]},ue=(e,t,n,r)=>({boolean:O(T,t,`booleanFormat`),null:O(E,n,`nullFormat`),number:O(D,r,`numberFormat`),array:O(w,e,`arrayFormat`)}),de=Object.freeze({boolean:T.auto,null:E.default,number:D.auto,array:w.none}),k=Object.freeze({arrayFormat:`none`,booleanFormat:`auto`,nullFormat:`default`,numberFormat:`auto`}),fe=Object.freeze({...k,strategies:de}),A=e=>{if(!e||e.arrayFormat===void 0&&e.booleanFormat===void 0&&e.nullFormat===void 0&&e.numberFormat===void 0)return fe;let t=e.arrayFormat??k.arrayFormat,n=e.booleanFormat??k.booleanFormat,r=e.nullFormat??k.nullFormat,i=e.numberFormat??k.numberFormat;return{arrayFormat:t,booleanFormat:n,nullFormat:r,numberFormat:i,strategies:ue(t,n,r,i)}},j=e=>x(e),M=(e,t,n)=>{let r=j(e);switch(typeof t){case`string`:case`number`:return`${r}=${j(t)}`;case`boolean`:return n.strategies.boolean.encode(r,t);case`object`:return t===null?n.strategies.null.encode(r):Array.isArray(t)?n.strategies.array.encodeArray(r,t,n.strategies.null):`${r}=${j(t)}`;default:return`${r}=${j(t)}`}},N=Object.hasOwn,P=Object.keys;function F(e,t,n){r(e,t,n)}function I(e,t,n,r){if(!N(e,t)){F(e,t,r?[n]:n);return}let i=e[t];Array.isArray(i)?i.push(n):F(e,t,[i,n])}function L(e,t,n){let r=t+1,i=0,a=!1;for(;r<n;){let t=e.codePointAt(r);if(t===93)return a?i:null;if(t!==void 0&&t>=48&&t<=57)i=i*10+(t-48),a=!0,r++;else return null}return null}function R(e,t,n){let{searchPart:r,nameEnd:i,nameSourceEnd:a,rawValue:o,decodedName:s}=e,c=L(r,i,a);if(c===null)return!1;let l=b(o,t),u=n.get(s);return u===void 0?n.set(s,[[c,l]]):u.push([c,l]),!0}function z(e,t,n,r,i,a,o){let s=a!==-1&&a<n?e.slice(a+1,n):void 0,c=s===void 0?n:a,l=c,u=!1;for(let n=t;n<c;n++)if(e.codePointAt(n)===91){l=n,u=!0;break}let d=y(e.slice(t,l));if(!(o!==void 0&&u&&R({searchPart:e,nameEnd:l,nameSourceEnd:c,rawValue:s,decodedName:d},i,o))){if(!u&&s!==void 0&&i.array.decodeValue){let e=i.array.decodeValue(s);if(e){for(let t of e)I(r,d,b(t,i),!0);return}}I(r,d,b(s,i),u)}}const B=(e,t)=>{if(e===``||e===`?`)return{};let n={};return V(e,n,t.strategies),n};function V(e,t,n){let r=n.array.indexed?new Map:void 0,i=0,a=e.length,o=-2;for(;i<a;){let s=e.indexOf(`&`,i);s===-1&&(s=a),s>i&&(o!==-1&&o<i&&(o=e.indexOf(`=`,i)),z(e,i,s,t,n,o,r)),i=s+1}if(r!==void 0)for(let[e,n]of r)n.sort((e,t)=>e[0]-t[0]),F(t,e,n.map(e=>e[1]))}const pe=(e,t,n)=>{let r=A(n);try{return H({[e]:t},r)===``}catch{return!1}},H=(e,t)=>{let n=P(e);if(n.length===0)return``;let r=[];for(let i of n){let n=e[i];if(n===void 0)continue;let a=M(i,n,t);a&&r.push(a)}return r.join(`&`)},me=/^[A-Z_a-z][\w-]*$/,he=/\S/,U=1e4;function W(t,n){if(t===``)throw e(`router`,n).type`Route name cannot be empty`}function ge(t,n){if(!he.test(t))throw e(`router`,n).type`Route name cannot contain only whitespace`}function _e(t,n){if(t.length>U)throw e(`router`,n).type`Route name exceeds maximum length of ${U} characters`}function G(t,n){if(t.includes(`.`))throw e(`router`,n).type`Route name "${t}" cannot contain dots. Use children array or { parent } option in addRoute() instead.`}function ve(t,n){if(!me.test(t))throw e(`router`,n).type`Invalid route name "${t}". Name must start with a letter or underscore, followed by letters, numbers, underscores, or hyphens.`}function K(t,n){return e(`router`,t).type`${n}`}function ye(e,t,n,r){let i=new Set;for(let a of e){if(i.has(a))throw K(n,`Invalid path for route "${t}": duplicate parameter name ':${a}' in "${r}" (a param name must be unique within a route — the second binding would overwrite the first)`);i.add(a)}}function be(e,t,n,r){for(let i of e)if(p.test(i))throw K(n,`Invalid path for route "${t}": invalid query-param name "${i}" in "${r}" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`)}function xe(e){let t=!0,n=!1;for(let r of e)if(r===`/`)t=!0;else if(t&&=(n=r===`:`||r===`*`,!1),!n&&r.codePointAt(0)>=128)return!0;return!1}function Se(e,t,n){switch(e){case`name-less`:case`trailing-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') without a name in "${n}"`;case`fused-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') must begin a segment, but "${n}" fuses one to a static prefix (use a boundary marker like "/a/:b")`}}function Ce(e,t){return e.code===`optional-removed`?`Invalid path for route "${t}": optional params are not supported — "${e.segment}". Declare two sibling routes instead: "${e.withoutSegment}" and "${e.requiredForm}" (the route hierarchy already expresses optionality)`:`Invalid path for route "${t}": regex constraints are not supported — '<' and '>' are reserved in path segments ("${e.segment}"). Match the segment as a plain string and validate the value in a guard (canActivate) or app code`}function we(e,t,n,r){if(typeof e!=`string`){let t;throw t=e===null?`null`:Array.isArray(e)?`array`:typeof e,K(n,`Route path must be a string, got ${t}`)}if(e===``)return;if(/\s/.test(e))throw K(n,`Invalid path for route "${t}": whitespace not allowed in "${e}"`);if(!/^([/?~]|[^/]+$)/.test(e))throw K(n,`Route "${t}" has invalid path format: "${e}". Path should start with '/', '~', '?' or be a relative segment.`);if(e.includes(`//`))throw K(n,`Invalid path for route "${t}": double slashes not allowed in "${e}"`);let{pathPattern:i,urlParams:a,queryParams:o}=_(e);ye(a,t,n,e),be(o,t,n,e);let s=f(i);if(s!==void 0)throw K(n,Ce(s,t));let c=ee(i);if(c!==void 0)throw K(n,Se(c,t,e));if(xe(i))throw K(n,`Invalid path for route "${t}": non-ASCII static segment in "${e}" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`);let l=r&&r.paramMeta.urlParams.length>0;if(e.startsWith(`~`)&&l)throw K(n,`Absolute path "${e}" cannot be used under parent route with URL parameters`)}const Te=Object.getOwnPropertyDescriptor,Ee=Object.keys,q=Object.getPrototypeOf;function J(e){if(e===null)return`null`;if(typeof e==`object`){try{let t=e.constructor;if(typeof t==`function`){let e=t.name;if(typeof e==`string`&&e!==``&&e!==`Object`)return e}}catch{}return`object`}return typeof e}function De(e){for(let t of Ee(e)){let n=Te(e,t);if(n&&(n.get||n.set))return!0}return!1}function Y(t,n){if(!t||typeof t!=`object`)throw e(`router`,n).type`Route must be an object, got ${J(t)}`;let r=q(t);if(r!==Object.prototype&&r!==null)throw e(`router`,n).type`Route must be a plain object, got ${J(t)}`;if(De(t))throw e(`router`,n).type`Route must not have getters or setters`}function X(t,n,r,i){if(typeof n!=`function`)throw e(`router`,i).type`Route "${r}" ${t} must be a function`}function Z(e,t,n,r){t!==void 0&&X(e,t,n,r)}function Oe(t,n){if(typeof t.name!=`string`)throw e(`router`,n).type`Route name must be a string, got ${J(t.name)}`;let r=t.name;W(r,n),ge(r,n),_e(r,n),r.startsWith(`@@`)||(G(r,n),ve(r,n))}function Q(e,t){if(!t.includes(`.`))return e.children.get(t);let n=e;for(let e of t.split(`.`))if(n=n.children.get(e),!n)return;return n}function ke(t,n,r){if(Q(t,n))throw e(`router`,r).plain`Route "${n}" already exists`}function Ae(t,n,r){if(t.has(n))throw e(`router`,r).plain`Duplicate route "${n}" in batch`;t.add(n)}function je(t,n,r,i){let a=n===``?t:Q(t,n);if(a){for(let t of a.children.values())if(t.path===r)throw e(`router`,i).plain`Path "${r}" is already defined`}}function Me(t,n,r,i){let a=t.get(n);if(a?.has(r))throw e(`router`,i).plain`Path "${r}" is already defined`;a?a.add(r):t.set(n,new Set([r]))}function $(t,n,r,i=``,a,o){Y(t,n);let s=t;Oe(s,n),we(s.path,s.name,n,r);let c=s.name,l=i?`${i}.${c}`:c;Z(`encodeParams`,s.encodeParams,l,n),Z(`decodeParams`,s.decodeParams,l,n),r&&l&&ke(r,l,n),a&&Ae(a,l,n);let u=s.path,d=i;if(r&&je(r,d,u,n),o&&Me(o,d,u,n),s.children!==void 0){if(!Array.isArray(s.children))throw e(`router`,n).type`Route "${c}" children must be an array, got ${J(s.children)}`;for(let e of s.children)$(e,n,r,l,a,o)}}export{s as _,W as a,pe as c,te as d,p as f,o as g,u as h,G as i,k as l,d as m,$ as n,H as o,_ as p,Y as r,B as s,X as t,A as u,a as v,c as y};
2
+ //# sourceMappingURL=route-batch-LdEAJqGb.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-batch-LdEAJqGb.mjs","names":["hasOwn","LT","QUESTION","SLASH","atRouter","encodeValue","objectKeys","hasOwn","objectKeys","raiser","publishRecord","emptyRecord","putField","hasOwn$2","findMisChanneledKey","params","queryNames","key","value","assertChannelCorrect","method","routeName","source","remedy","misChanneledKeyMessage","assertShippedChannelCorrect","shipped","isMarker","code","splitPathSegments","path","segments","start","i","parseSegment","segment","length","splat","cursor","name","findSegmentGrammarError","token","describeRemovedForm","required","_","j","INVALID_QUERY_NAME_RGX","findQuerySeparator","next","EMPTY_PARAM_NAMES","EMPTY_PARAM_TYPE_MAP","EMPTY_PARAM_META","collectUrlParams","urlParams","paramTypeMap","buildParamMeta","queryParams","separator","param","paramName","shareEmptyCollections","pathPattern","decodeValue","percentIdx","plusIdx","withSpaces","decode","strategies","rawResult","decoded","numberResult","LONE_SURROGATE_RGX","safeEncode","error","atRouter$1","encodeValue$1","type","repeatKey","values","suffix","nullStrategy","parts","encoded","arrayStrategies","rawValue","booleanStrategies","raw","nullStrategies","numberStrategies","hasDot","ch","num","atRouter","defineProperty","objectKeys$2","hasOwn$1","CONFIG_FAULT","requireStrategy","table","field","resolveStrategies","arrayFormat","booleanFormat","nullFormat","numberFormat","DEFAULT_STRATEGIES","DEFAULT_QUERY_PARAMS","DEFAULT_OPTIONS","makeOptions","opts","encodeValue","encode","encodedName","hasOwn","objectKeys$1","assignParam","addToParams","decodedName","decodedValue","hasBrackets","currentValue","bracketIndex","searchPart","open","limit","hasDigit","collectIndexedChunk","chunk","indexedGroups","nameEnd","nameSourceEnd","index","group","processParamChunk","end","eqPos","part","parseQueryWith","search","options","parseIntoInternal","eqCache","pairs","left","right","pair","printsNoQueryKey","buildWith","keys","ROUTE_NAME_PATTERN","HAS_NON_WHITESPACE","MAX_ROUTE_NAME_LENGTH","assertRouteNameNotEmpty","methodName","assertRouteNameNotWhitespaceOnly","assertRouteNameWithinLength","assertNoDottedRouteName","assertRouteNameMatchesPattern","createRouterError","message","validateUniqueParamNames","seen","validateQueryParamDeclarations","hasNonAsciiStatic","atSegmentStart","segmentIsMarker","char","gateGrammarMessage","removedFormMessage","removed","validateRoutePath","parentNode","typeDesc","grammarError","hasUrlParams","getOwnPropertyDescriptor","objectKeys","getPrototypeOf","getTypeDescription","ctor","hasGettersOrSetters","obj","descriptor","validateRouteType","route","proto","assertRouteCodecIsFunction","codec","validateCodec","fullName","validateRouteName","findNodeByFullName","rootNode","current","checkTreeNameDuplicate","checkBatchNameDuplicate","seenNames","checkTreePathDuplicate","parentName","routePath","child","checkBatchPathDuplicate","seenPathsByParent","pathsAtLevel","validateRoute","routeDef","pathCheckParent"],"sources":["../../src/channels/guard.ts","../../src/engine/path-matcher/parseSegment.ts","../../src/engine/path-matcher/buildParamMeta.ts","../../src/engine/search-params/decode.ts","../../src/engine/search-params/utils.ts","../../src/engine/search-params/strategies/array.ts","../../src/engine/search-params/strategies/boolean.ts","../../src/engine/search-params/strategies/null.ts","../../src/engine/search-params/strategies/number.ts","../../src/engine/search-params/strategies/index.ts","../../src/engine/search-params/encode.ts","../../src/engine/search-params/searchParams.ts","../../src/engine/validation/route-name.ts","../../src/engine/validation/routes.ts","../../src/engine/validation/route-batch.ts"],"sourcesContent":["// packages/core/src/channels/guard.ts\n\nimport { raiser } from \"../RouterError\";\n\nimport type { Params } from \"../types\";\n\n/**\n * Intrinsics captured at module load: `hasOwn`.\n *\n * ⚑ A guard is only as strong as the intrinsic it reads WHEN IT RUNS, and an\n * application can re-point any of these AFTER boot — which is what this closes.\n * Measured on the uncaptured form: one naive `Object.hasOwn` polyfill walked\n * straight through five sibling readers while the single captured guard held.\n *\n * ⚠ The limit of what capture buys — and the shim order that defeats it — is\n * stated once, in `guards.ts`. Not restated here (#2091).\n */\nconst hasOwn = Object.hasOwn;\n\n/**\n * THE predicate of the always-on channel guard: the first key the caller put in\n * the PATH bag while the route declares it as a QUERY param, or `undefined`\n * when the bag is channel-correct.\n *\n * A DETECTOR, not a normaliser — the key is never moved. There is no stage ②\n * and no `separateChannels`: channel-correctness is the producer's contract,\n * not a repair the pipeline performs behind everyone's back.\n *\n * Scans `queryNames` (a route's declared query names — small, cached) rather\n * than the bag, so there is no `Object.keys` allocation, and short-circuits on\n * a route with no query declarations, which is the common case.\n *\n * `undefined` is absence on both sides (#1550 / #1551), so an\n * `undefined`-valued key is NOT a mis-channel: it is the documented removal\n * marker `persistent-params` relies on, and it never reaches a built state\n * anyway. A name that also occupies a path slot (`/items/:id?id`) is absent\n * from `queryNames` by construction (#843 / #1549 carve-out), so the collision\n * form is legitimately path-owned and passes.\n *\n * @internal\n */\nexport function findMisChanneledKey(\n params: Params | undefined,\n queryNames: readonly string[],\n): string | undefined {\n // ⚠ An absent BAG has two spellings, and `== null` is the intent: both\n // nullish values mean \"there is no bag\". `navigate(name, null)` is supported\n // runtime input while the signature admits only `Params | undefined`, so\n // testing `=== undefined` alone lets `Object.hasOwn` perform `ToObject` — and\n // this DIAGNOSTIC becomes the thing that throws (#1822).\n //\n // ⚑ In the predicate rather than in `assertChannelCorrect`: `canNavigateTo`\n // and `navigateToState` reach it directly, and neither may throw — the first\n // answers on the render path, the second rejects because URL plugins call it\n // from popstate handlers.\n if (queryNames.length === 0 || params == null) {\n return undefined;\n }\n\n for (const key of queryNames) {\n if (!hasOwn(params, key)) {\n continue;\n }\n\n let value: unknown;\n\n try {\n value = params[key];\n } catch {\n // A DIAGNOSTIC must never become the thing that throws. The bag may be\n // backed by accessors (a Proxy, a getter, a framework's reactive object),\n // and reading one here happens EARLIER than any consumer would have read\n // it — so an accessor that throws would surface from the guard instead of\n // from the code that actually needed the value, moving the origin of an\n // existing failure. Treat it as \"nothing to report\" and let the real\n // consumer hit the same accessor exactly as it did before.\n return undefined;\n }\n\n if (value !== undefined) {\n return key;\n }\n }\n\n return undefined;\n}\n\n/**\n * THE centralized channel check — the single place a mis-channelled bag is\n * refused, wherever it came from.\n *\n * A key the route declares with `?`, sitting in the PATH bag, is a producer's\n * mistake — the producer named the route, so it knows the declaration — and the\n * router SAYS so instead of quietly moving the field into the other object.\n * Moving it would be invisible: the caller keeps believing their bag is the one\n * that shipped, and two producers of the SAME intent can disagree about which\n * channel a key ended up in.\n *\n * `source` names WHOSE bag is wrong, which is the whole diagnostic value at a\n * seam: the caller's argument, a `forwardState` interceptor's return, or the\n * output of a route's own `decodeParams`. It takes a THUNK as well as a string\n * because the seam sits on the navigation hot path — a source that has to be\n * composed (naming the route a chain forwarded from) must not build its string\n * on every call just to discard it on the 99.99% of calls that pass.\n *\n * @internal\n */\nexport function assertChannelCorrect(\n method: string,\n routeName: string,\n params: Params | undefined,\n queryNames: readonly string[],\n source?: string | (() => string),\n remedy?: string,\n): void {\n const key = findMisChanneledKey(params, queryNames);\n\n if (key !== undefined) {\n const at = raiser(\"router\", method);\n\n throw at.type`${misChanneledKeyMessage(\n routeName,\n key,\n typeof source === \"function\" ? source() : source,\n remedy,\n )}`;\n }\n}\n\n/**\n * The channel verdict, re-asked on the bag that actually SHIPS (#1927).\n *\n * Every position above a producer reads the CALLER's object — P1 at the door,\n * the `forwardState` seam, the `decodeParams` boundary. The canonical bag is\n * then built by a SECOND read of that same object, and between the two it still\n * belongs to the application: a Proxy, a framework's reactive object, a plain\n * getter. A bag answering `undefined` while the guards look — the documented\n * removal marker, correctly waved through — commits a declared query name into\n * `state.params` while `state.path` prints without it. `read-count-authority`\n * owns how many times each door reads a caller-owned key; this file does not\n * restate the counts, because a number written twice goes stale twice.\n *\n * The SAME predicate, one position later, on core's own object. A canonical bag\n * has no accessors, so this verdict cannot be overtaken: the invariant is\n * structural rather than maintained by care.\n *\n * ⚑ Called by the four doors that PUBLISH a State, and by no one else. The two\n * render-path predicates — `buildPath` (a string) and `isActiveRoute` (a boolean)\n * — ship no value for a verdict to vouch for, and #1572 / #1581 record that they\n * are deliberately not instrumented: detecting there is fine, throwing is not.\n * They express that the way they always have, by not calling.\n *\n * ⚠ `canNavigateTo` produces a State too and is deliberately NOT here — measured,\n * not assumed. It discards the state, so nothing ships for a verdict to vouch\n * for, and every bag this check would refuse it already answers `false` to: the\n * seam sees the same key one read earlier. Adding the call changed no answer for\n * any blindness from 0 to 3 reads, while costing one predicate call on the render\n * path, which runs per `<Link>` per render.\n *\n * ⚑ On a canonical bag the `value !== undefined` arm is vacuous — those keys are\n * already dropped — so `undefined` stays the removal marker (#1550 / #1551).\n *\n * ⚑ The declarations are the RESOLVED route's, which is why callers pass\n * `canonical.name`: the bag came out of the chain, and the resolved route owns\n * the URL that gets printed — the same authority the seam names.\n */\nexport function assertShippedChannelCorrect(\n method: string,\n routeName: string,\n shipped: Params,\n queryNames: readonly string[],\n): void {\n assertChannelCorrect(\n method,\n routeName,\n shipped,\n queryNames,\n \"the `params` bag this call is about to ship — the channel check above it read a different value, so the caller's object answered differently between the two reads\",\n );\n}\n\n/**\n * The guard's actionable message. One builder for every position, so the\n * wording a user sees does not depend on which door they came through — the\n * facade's `TypeError`, the seam's, the decoder's, and `navigateToState`'s\n * `RouterError(WRONG_CHANNEL)`, which needs the wording WITHOUT the throw and is\n * why this is a separate function from {@link assertChannelCorrect}.\n *\n * @internal\n */\nexport function misChanneledKeyMessage(\n routeName: string,\n key: string,\n source = \"the `params` argument\",\n remedy = \"Pass it in `search` instead\",\n): string {\n return `Route \"${routeName}\" declares \\`${key}\\` as a query param, but it was given in ${source} — the path channel. ${remedy}; the two channels are separate since RFC-4 M2 and the router never moves a key between them.`;\n}\n","/**\n * Canonical route-segment tokenizer.\n *\n * The single owner of \"where does a name / marker / constraint end\" for ONE\n * path segment (post-`/`-split). It replaces the five name-boundary compositions\n * of `PARAM_NAME_PATTERN` currently spread across `buildParamMeta` (L1),\n * `registration` (L2 build + L3 trie), and `route-tree`'s validation gate (L4),\n * so those layers can never disagree on a boundary (the gate↔backstop drift\n * class — #858 / #1050 / #1150 / #1311 / #1149 / #1324).\n *\n * A single left-to-right `charCodeAt` scan produces either a token tuple or a\n * typed error. Grammar — **3 tokens only** (`static | :param | *splat`); the\n * grammar has no optional `:x?` or `<re>` constraint forms. Any `<`/`>` or a\n * post-name `?` in the path is a *registration error* carrying a replacement\n * recipe (`optional-removed` / `constraint-removed`), not a token:\n * 1. Leading `:`/`*` → param/splat; otherwise `static` (a marker glued *after* a\n * static prefix ⇒ `fused-marker`; any `<`/`>` (a former constraint) ⇒\n * `constraint-removed`; a trailing `?` on a marker-less segment ⇒ `name-less`\n * — the modifier has no param name, #1241 / `/faq?`).\n * 2. name = any char except `<`/`?` (no `/` remains inside a segment); a name\n * ending in a bare `:`/`*` ⇒ `trailing-marker` (#1324). A *mid* marker stays\n * a name char — `:a:b` → name `a:b`, preserved.\n * 3. empty name ⇒ `name-less` (#858).\n * 4. a `<` after the name (a former `<re>` constraint) ⇒ `constraint-removed`.\n * 5. a post-name `?` (a former optional modifier, on `:param` or `*splat`) ⇒\n * `optional-removed`.\n *\n * @module parseSegment\n */\n\n/* eslint-disable unicorn/prefer-code-point, unicorn/prefer-includes-over-repeated-comparisons, sonarjs/cognitive-complexity -- charCodeAt code-unit scan + a single inlined branchy pass are this RFC's char-scan perf basis (§9); the same deliberate choices as registration/trie.ts hasNonAsciiSegment (#1285) and SegmentMatcher's inlined #traverseFrom. A `[LT,GT,QUESTION].includes(code)` boundary check would allocate an array literal per scanned char. Markers compared are ASCII (`:` `*` `<` `>` `?`, < 0x80). */\n\n/** A successfully tokenized segment (3-token grammar: `static | :param | *splat`). */\nexport type SegmentTokens =\n | { readonly kind: \"static\"; readonly text: string }\n | { readonly kind: \"param\"; readonly name: string }\n | { readonly kind: \"splat\"; readonly name: string };\n\n/** Grammar-shape rejections, each mirroring a registration guard. */\nexport type SegmentErrorCode =\n | \"name-less\" // #858 — a marker with no name\n | \"trailing-marker\" // #1324 — a param name ending in a bare `:`/`*`\n | \"fused-marker\" // #1050 — a marker glued after a static prefix\n | \"optional-removed\" // M1 — a `:x?`/`*x?` optional modifier (removed; two sibling routes)\n | \"constraint-removed\"; // M1 — a `<re>` constraint or stray `<`/`>` (removed; validate in a guard)\n\nexport interface SegmentError {\n readonly error: SegmentErrorCode;\n}\n\nconst COLON = 58; // :\nconst STAR = 42; // *\nconst LT = 60; // <\nconst GT = 62; // >\nconst QUESTION = 63; // ?\nconst SLASH = 47; // /\n\nconst isMarker = (code: number): boolean => code === COLON || code === STAR;\n\n/**\n * Splits a path into its `/`-delimited segments. A plain `/`-split (M1): the\n * 3-token grammar has no `<...>` constraint whose body could legally contain a\n * `/`, so no constraint-awareness is needed — a stray `<`/`>` is a\n * `constraint-removed` error, caught per segment by `parseSegment`. This is the\n * **segmentation** half of the path-grammar unification: `parseSegment` owns the\n * per-segment grammar, `splitPathSegments` owns where a segment begins and ends.\n *\n * @param path - a route path (query already stripped by the caller)\n * @returns the segments in order, including empty leading/trailing/`//` segments\n * (the caller skips empties, matching the current behaviour)\n */\nexport function splitPathSegments(path: string): string[] {\n const segments: string[] = [];\n let start = 0;\n\n for (let i = 0; i < path.length; i += 1) {\n if (path.charCodeAt(i) !== SLASH) {\n continue;\n }\n\n segments.push(path.slice(start, i));\n start = i + 1;\n }\n\n segments.push(path.slice(start));\n\n return segments;\n}\n\n/**\n * Tokenizes a single path segment (already split on `/`).\n *\n * @param segment - one `/`-delimited segment of a route path\n * @returns the segment's tokens, or a typed grammar error\n */\nexport function parseSegment(segment: string): SegmentTokens | SegmentError {\n const length = segment.length;\n\n if (length === 0) {\n return { kind: \"static\", text: \"\" };\n }\n\n // ---- static segment (no leading marker) -------------------------------\n if (!isMarker(segment.charCodeAt(0))) {\n for (let i = 0; i < length; i += 1) {\n const code = segment.charCodeAt(i);\n\n // A `<`/`>` (a former `<re>` constraint or a stray delimiter) is no longer\n // grammar — M1 removed constraints. Reject with the constraint recipe.\n if (code === LT || code === GT) {\n return { error: \"constraint-removed\" };\n }\n\n // A marker glued after a static prefix is extracted as a param by build/meta\n // but compiled as a static literal by the trie (#1050) — reject it as fused.\n // A marker ENDING the segment (a static ending in `:`/`*` — `/a:`, `/a*`, F2)\n // is NOT fused: caught by `i + 1 < length` being false. Every other following\n // char is fused — including a `?` (`a:?`): that shape never reaches the\n // tokenizer through a real path (a `?` after a bare marker is not a valid\n // `:name?` form, so the query mask strips it before `/`-segmentation), so a\n // direct call correctly reports fused-marker. (`a<`/`a>` already returned\n // `constraint-removed` above, so no `<`-follows exception is needed here.)\n if (isMarker(code) && i + 1 < length) {\n return { error: \"fused-marker\" };\n }\n }\n\n // A trailing `?` is a former optional modifier; on a marker-less segment (no\n // param name) it is a modifier-with-no-name — name-less (#858/#1241, `/faq?`),\n // NOT `optional-removed` (there is no param to route to two siblings). The\n // backstop rejects it by the SAME rule: `processSegment` asks this tokenizer\n // for the segment's kind (#1998). Owning the `?` here (not\n // only in the marker branch) is what lets the gate and backstop agree on it —\n // otherwise the gate reads `faq?` as a valid static (#1324 §4).\n if (segment.charCodeAt(length - 1) === QUESTION) {\n return { error: \"name-less\" };\n }\n\n return { kind: \"static\", text: segment };\n }\n\n const splat = segment.charCodeAt(0) === STAR;\n\n // ---- name: up to the first `<`/`>` (former constraint delimiter, reserved —\n // B1.3) or `?` (former optional). A segment holds no `/`. -----------------\n let cursor = 1;\n\n while (cursor < length) {\n const code = segment.charCodeAt(cursor);\n\n if (code === LT || code === GT || code === QUESTION) {\n break;\n }\n\n cursor += 1;\n }\n\n const name = segment.slice(1, cursor);\n\n if (name.length === 0) {\n return { error: \"name-less\" }; // #858\n }\n\n if (isMarker(name.charCodeAt(name.length - 1))) {\n return { error: \"trailing-marker\" }; // #1324\n }\n\n // ---- former constraint / optional modifiers (removed in M1) ------------\n // The name scan stops at the first `<`/`>` or `?`. Either is a form removed\n // in M1: a `<re>` constraint (also a stray `<`/`>` — B1.3), or a `:x?`/`*x?`\n // optional. Only `?` is the optional; `<`/`>` are the constraint recipe.\n // Reject with the matching replacement recipe rather than tokenize it.\n if (cursor < length) {\n return segment.charCodeAt(cursor) === QUESTION\n ? { error: \"optional-removed\" }\n : { error: \"constraint-removed\" }; // LT or GT\n }\n\n return splat ? { kind: \"splat\", name } : { kind: \"param\", name };\n}\n\n/**\n * Returns the first per-segment grammar error in a path, or `undefined` if every\n * segment tokenizes cleanly.\n *\n * The **validation-facing** entry over the tokenizer: `route-tree`'s\n * `validateRoutePath` calls this instead of re-running its own split+parse loop,\n * so the gate and the matcher's own grammar cannot drift (#1324) and the loop\n * stays single-sourced here — the tokenizer primitives (`parseSegment`,\n * `splitPathSegments`) need not leak into the package's public surface. An empty\n * segment tokenizes as `static` (never an error), so leading/trailing/`//`\n * empties are skipped naturally.\n *\n * @param path - a route path (query already stripped by the caller)\n * @returns the first `SegmentErrorCode` (scanned left to right), or `undefined`\n */\nexport function findSegmentGrammarError(\n path: string,\n): SegmentErrorCode | undefined {\n for (const segment of splitPathSegments(path)) {\n const token = parseSegment(segment);\n\n if (\"error\" in token) {\n return token.error;\n }\n }\n\n return undefined;\n}\n\n/** A removed-form (M1) match, describing the offending segment and — for an\n * optional — the two sibling paths that replace it (path without the optional\n * segment + path with the param made required). The route-tree gate uses this to\n * build a route-contextual replacement recipe; the matcher backstop uses only the\n * error code (a shorter, path-free recipe). */\nexport type RemovedForm =\n | {\n readonly code: \"optional-removed\";\n readonly segment: string;\n readonly withoutSegment: string;\n readonly requiredForm: string;\n }\n | { readonly code: \"constraint-removed\"; readonly segment: string };\n\n/**\n * The rich (route-tree gate) view over the tokenizer for a removed form: finds\n * the first `optional-removed` / `constraint-removed` segment and, for an\n * optional, computes its two replacement sibling paths from the ACTUAL path\n * (dropping the segment → without-form; dropping the trailing `?` → required\n * form). Returns `undefined` if no removed form is present (the gate then uses\n * `findSegmentGrammarError` for a surviving grammar rejection).\n *\n * @param path - a route path (query already stripped by the caller)\n */\nexport function describeRemovedForm(path: string): RemovedForm | undefined {\n const segments = splitPathSegments(path);\n\n for (let i = 0; i < segments.length; i += 1) {\n const token = parseSegment(segments[i]);\n\n if (!(\"error\" in token)) {\n continue;\n }\n\n // First error wins (mirrors `findSegmentGrammarError`): describe it ONLY if\n // it is a removed form, else return undefined so the caller falls to the\n // surviving-code message — this keeps the gate's reason in lockstep with the\n // matcher backstop's first-error verdict.\n if (token.error === \"optional-removed\") {\n const segment = segments[i];\n const required = [...segments];\n\n // Drop the `?` optional modifier AND everything after it (the tokenizer\n // stopped the name at the first `?`, so it is the modifier). Using the `?`\n // index — not a blind `slice(0, -1)` — keeps the required sibling VALID for\n // a reverse/compound form whose `?` is not the last char: `:b?<x>` → `:b`\n // (not `:b?<x`), `:id??` → `:id` (not `:id?`). #1516\n required[i] = segment.slice(0, segment.indexOf(\"?\"));\n\n return {\n code: \"optional-removed\",\n segment,\n withoutSegment: segments.filter((_, j) => j !== i).join(\"/\"),\n requiredForm: required.join(\"/\"),\n };\n }\n\n return token.error === \"constraint-removed\"\n ? { code: \"constraint-removed\", segment: segments[i] }\n : undefined;\n }\n\n return undefined;\n}\n","/**\n * Route Parameter Metadata Extraction.\n *\n * Extracts parameter metadata from route path patterns without requiring\n * a full path-parser instance. Replaces parser.urlParams/queryParams.\n *\n * @module buildParamMeta\n */\n\nimport { parseSegment, splitPathSegments } from \"./parseSegment\";\nimport { emptyRecord, publishRecord } from \"../../utils/ingest\";\n\nimport type { ParamMeta } from \"./types\";\n\n/**\n * A query-param NAME may not contain `<`/`>` (#1242 §5.1) — a constraint\n * delimiter leaked into the query via a reverse-order modifier typo (`/a/:b?<c>`\n * parses the `?` as the query start, making `<c>` the query name). Consumed by\n * the route-tree gate and the `registerTree` backstop; relocated here from the\n * deleted `constraint-grammar.ts` when M1 removed constraints (query-param name\n * validation is a query concern, and this module owns query extraction).\n */\nexport const INVALID_QUERY_NAME_RGX = /[<>]/u;\n\nconst QUESTION = 0x3f; // ?\nconst SLASH = 0x2f; // /\nconst LT = 0x3c; // <\n\n/**\n * Locates the query separator `?` in a route path — the FIRST `?` whose tail is\n * non-empty and does not begin with `/`, `?`, or `<` (M1 §3.3). The 3-token\n * grammar leaves `?` a single role (there is no optional modifier and no\n * constraint body to hide one), so no length-preserving mask is needed. The three\n * excluded tails keep a REMOVED form in the path part, where `parseSegment`\n * rejects it with a recipe instead of mis-reading it as a query declaration:\n * - end-of-string (`/:id?`) and `/` (`/:id?/edit`) → a bare `:x?` optional;\n * - `?` (`/:id??tab`) → the leading `?` is the optional, the later `?` the query;\n * - `<` (`/a/:b?<x>`) → a reverse-order `:b?<x>` (optional then a former constraint).\n *\n * @param path - a route path\n * @returns the index of the query separator, or -1 if there is none\n */\nfunction findQuerySeparator(path: string): number {\n for (let i = 0; i < path.length; i += 1) {\n if (path.codePointAt(i) !== QUESTION) {\n continue;\n }\n\n // `next` is the code point after the `?`, or the `-1` sentinel at end-of-string.\n // The `-1` sentinel is the SOLE end-of-string guard, and a separate\n // `next !== undefined` conjunct would be dead: the ternary bounds the index,\n // so `codePointAt` never returns `undefined`; the `!` is a type assertion,\n // not a runtime branch, so it keeps the scan at 100% coverage. Mirrors\n // `#scanPath`.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- ternary-bounded in-range index; codePointAt is defined\n const next = i + 1 < path.length ? path.codePointAt(i + 1)! : -1;\n\n if (![-1, SLASH, QUESTION, LT].includes(next)) {\n return i;\n }\n }\n\n return -1;\n}\n\n// Shared frozen sentinels for the common no-params case — avoid a fresh empty\n// array/object per route (#1009). ParamMeta fields are Readonly*; match/build\n// only read them, and computeCaches' Object.freeze on the arrays/object is a\n// no-op on an already-frozen shared instance.\nconst EMPTY_PARAM_NAMES: readonly string[] = Object.freeze([]);\nconst EMPTY_PARAM_TYPE_MAP: Readonly<Record<string, \"url\" | \"query\">> =\n Object.freeze({});\n\n// Whole-meta shared sentinel for the fully-static case: every collection is a\n// #1009 sentinel AND pathPattern degenerates to the input path itself (no query\n// to strip), so the wrapper carries zero per-route information. The RETAINING\n// caller (route-tree's computeCaches) swaps a matching fresh result for this\n// instance — buildParamMeta itself keeps returning fresh objects so the\n// validation gate can read the real pathPattern of arbitrary input paths.\n// `pathPattern` is \"\" here; the one stored-meta reader (`registerNode`) falls\n// back to `node.path` on identity match.\nexport const EMPTY_PARAM_META: ParamMeta = Object.freeze({\n urlParams: EMPTY_PARAM_NAMES,\n queryParams: EMPTY_PARAM_NAMES,\n paramTypeMap: EMPTY_PARAM_TYPE_MAP,\n pathPattern: \"\",\n});\n\n/**\n * Extracts URL params (including splats) from a path's segments into the given accumulators\n * via the canonical `parseSegment` tokenizer. Split out of `buildParamMeta` so\n * the builder stays under the cognitive-complexity budget. A malformed segment\n * (token errors) or a `static` segment contributes nothing — a malformed route is\n * rejected downstream before it compiles, so its meta is moot.\n */\nfunction collectUrlParams(\n path: string,\n urlParams: string[],\n paramTypeMap: Record<string, \"url\" | \"query\">,\n): void {\n for (const segment of splitPathSegments(path)) {\n if (segment.length === 0) {\n continue;\n }\n\n const token = parseSegment(segment);\n\n if (\"error\" in token || token.kind === \"static\") {\n continue;\n }\n\n urlParams.push(token.name);\n paramTypeMap[token.name] = \"url\";\n }\n}\n\n/**\n * Builds parameter metadata from a route path pattern: the URL params its\n * `:param` and `*splat` slots declare, the query params its `?name`\n * declarations declare, each one's type, and the path without its query.\n *\n * A segment the path grammar refuses (a fused marker such as `a:b`) contributes\n * nothing, so read a path `validateRoute` accepts.\n *\n * @param path - Route path pattern (e.g., \"/users/:id/posts/:postId?q\")\n * @returns Parameter metadata object\n *\n * @example\n * ```typescript\n * buildParamMeta(\"/users/:id\")\n * // → { urlParams: [\"id\"], queryParams: [], paramTypeMap: { id: \"url\" },\n * // pathPattern: \"/users/:id\" }\n *\n * buildParamMeta(\"/search?q&page\")\n * // → { urlParams: [], queryParams: [\"q\", \"page\"],\n * // paramTypeMap: { q: \"query\", page: \"query\" }, pathPattern: \"/search\" }\n *\n * buildParamMeta(\"/files/*path\")\n * // → { urlParams: [\"path\"], queryParams: [], paramTypeMap: { path: \"url\" },\n * // pathPattern: \"/files/*path\" }\n * ```\n */\nexport function buildParamMeta(path: string): ParamMeta {\n const urlParams: string[] = [];\n const queryParams: string[] = [];\n const paramTypeMap = emptyRecord<\"url\" | \"query\">();\n\n // Locate the real query separator (M1 §3.3: first `?` whose tail is not a\n // former optional/reverse form).\n const separator = findQuerySeparator(path);\n\n if (separator !== -1) {\n const queryString = path.slice(separator + 1);\n const params = queryString.split(\"&\");\n\n for (const param of params) {\n const paramName = param.trim();\n\n if (paramName.length > 0) {\n queryParams.push(paramName);\n paramTypeMap[paramName] = \"query\";\n }\n }\n\n path = path.slice(0, separator);\n }\n\n collectUrlParams(path, urlParams, paramTypeMap);\n\n return shareEmptyCollections(\n urlParams,\n queryParams,\n publishRecord(paramTypeMap),\n path,\n );\n}\n\n// #1009: swap each freshly-built empty collection for a shared frozen sentinel\n// — factored out of buildParamMeta so the hot builder stays under the cognitive-\n// complexity budget. match/build only read these (Readonly*), and computeCaches'\n// Object.freeze is a no-op on an already-frozen shared instance.\nfunction shareEmptyCollections(\n urlParams: string[],\n queryParams: string[],\n paramTypeMap: Record<string, \"url\" | \"query\">,\n pathPattern: string,\n): ParamMeta {\n return {\n urlParams: urlParams.length === 0 ? EMPTY_PARAM_NAMES : urlParams,\n queryParams: queryParams.length === 0 ? EMPTY_PARAM_NAMES : queryParams,\n paramTypeMap:\n urlParams.length === 0 && queryParams.length === 0\n ? EMPTY_PARAM_TYPE_MAP\n : paramTypeMap,\n pathPattern,\n };\n}\n","/**\n * Decoding functions for search-params.\n *\n * Extracted from encode.ts for better separation of concerns.\n *\n * @module search-params/decode\n */\n\nimport type { ResolvedStrategies } from \"./strategies\";\nimport type { DecodeResult } from \"./types\";\n\n// =============================================================================\n// Value Decoding\n// =============================================================================\n\n/**\n * Decodes a URL-encoded value, handling + as space.\n * Optimized: only replaces + if present, skips decodeURIComponent if not needed.\n *\n * Uses indexOf for checking presence - more mutation-resistant than includes\n * because indexOf(\"x\") returns -1 when not found, while includes(\"\") always returns true.\n */\nexport const decodeValue = (value: string): string => {\n // Stryker disable next-line StringLiteral: equivalent — indexOf(\"%\") -> indexOf(\"\") returns 0, forcing the full decode path; decodeURIComponent is a no-op on a %-free string, so the result is identical (proven by injection). See the indexOf rationale above.\n const percentIdx = value.indexOf(\"%\");\n // Stryker disable next-line StringLiteral: equivalent — indexOf(\"+\") -> indexOf(\"\") returns 0, forcing replaceAll(\"+\",\" \") which is a no-op on a +-free string (proven by injection).\n const plusIdx = value.indexOf(\"+\");\n\n // Fast path: no encoding needed (common case - most values are simple)\n if (percentIdx === -1 && plusIdx === -1) {\n return value;\n }\n\n // Only replace + if present (avoid regex overhead)\n const withSpaces = plusIdx === -1 ? value : value.replaceAll(\"+\", \" \");\n\n // Only decode if % is present\n return percentIdx === -1 ? withSpaces : decodeURIComponent(withSpaces);\n};\n\n// =============================================================================\n// Main Decode\n// =============================================================================\n\n/**\n * Decodes a query parameter value using resolved strategies.\n *\n * @param value - Raw value from query string (undefined for key-only params)\n * @param strategies - Pre-resolved format strategies\n * @returns Decoded value (string, boolean, or null)\n */\nexport const decode = (\n value: string | undefined,\n strategies: ResolvedStrategies,\n): DecodeResult => {\n // Handle undefined (key-only params like ?flag)\n if (value === undefined) {\n return strategies.boolean.decodeUndefined();\n }\n\n // Check raw value for boolean formats (e.g., \"true\"/\"false\")\n const rawResult = strategies.boolean.decodeRaw(value);\n\n if (rawResult !== null) {\n return rawResult;\n }\n\n // Decode URI and check decoded value for boolean formats (e.g., ✓/✗)\n const decoded = decodeValue(value);\n\n const numberResult = strategies.number.decode(decoded);\n\n if (numberResult !== null) {\n return numberResult;\n }\n\n return strategies.boolean.decodeValue(decoded);\n};\n","/**\n * Utility functions for search-params.\n *\n * Internalized from https://github.com/troch/search-params\n *\n * @module search-params/utils\n */\n\n// =============================================================================\n// Total Percent-Encoding\n// =============================================================================\n\n/**\n * A lone (unpaired) surrogate — a high surrogate not followed by a low, or a low\n * not preceded by a high. This is a manual, lib-target-agnostic\n * `String.prototype.toWellFormed` (ES2024): consumers compile this `src` under their\n * OWN `tsconfig` (whose `lib` may predate es2024 — e.g. `hash-plugin`), so a regex\n * `replace` avoids a `toWellFormed` type error in every consumer while producing the\n * identical result (verified by parity across the surrogate space).\n */\nconst LONE_SURROGATE_RGX =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g;\n\n/**\n * Percent-encodes a value, staying TOTAL on a lone (unpaired) surrogate.\n *\n * `encodeURIComponent` throws `URIError` on an unpaired UTF-16 surrogate — the\n * only input it rejects. `parseQuery` accepts such a value (its non-percent decode\n * is an identity fast path), so `build(parseQuery(qs))` would throw and violate the\n * inverse-pair totality invariant `range(parseQuery) ⊆ dom(build)` (INVARIANTS\n * Parse/Build #12). We sanitize each lone surrogate to U+FFFD instead: the first\n * round-trip mutates the (already non-round-trippable) garbage, then stabilises;\n * well-formed inputs are untouched. Single source for BOTH encode sites — scalar/key\n * (`encode.ts`) and array element (`strategies/array.ts`) — so they cannot drift\n * (#1314).\n */\nexport const safeEncode = (value: string | number | boolean): string => {\n try {\n return encodeURIComponent(value);\n } catch (error) {\n // Only a lone surrogate (URIError) is sanitized. Anything else is a real error\n // the caller must see — e.g. a Symbol value throws `TypeError` here, and\n // `String(symbol)` would silently coerce it to \"Symbol(…)\" instead of rethrowing.\n if (!(error instanceof URIError)) {\n throw error;\n }\n\n // Lone surrogate → U+FFFD, keeping build total.\n return encodeURIComponent(\n String(value).replaceAll(LONE_SURROGATE_RGX, \"�\"),\n );\n }\n};\n","/**\n * Array encoding strategies.\n *\n * @module search-params/strategies/array\n */\n\nimport { raiser } from \"../../../RouterError\";\nimport { safeEncode } from \"../utils\";\n\nimport type { NullStrategy } from \"./null\";\nimport type { ArrayFormat } from \"../types\";\n\n/** One binding per door this module refuses behind (#2487). */\nconst atRouter = raiser(\"router\");\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for encoding array values.\n */\nexport interface ArrayStrategy {\n /**\n * Encodes an array as a query string segment.\n *\n * @param name - URL-encoded parameter name\n * @param values - Array values to encode\n * @param nullStrategy - Null strategy, so a `null` element encodes to the same\n * wire token a scalar null does (bare key under `default`, dropped under\n * `hidden`) — closing `range(parse) ⊆ dom(build)` (#1155)\n * @returns Query string segment (e.g., \"items=a&items=b\" or \"items=a,b\")\n */\n encodeArray: (\n name: string,\n values: unknown[],\n nullStrategy: NullStrategy,\n ) => string;\n\n /**\n * Splits a raw (URI-encoded) value into array parts during parsing.\n * Returns null if the value is not an array in this format.\n *\n * @param rawValue - Raw value before URI decoding\n * @returns Array of raw parts, or null if not an array\n */\n decodeValue?: (rawValue: string) => string[] | null;\n\n /**\n * When true, the parser orders bracketed elements (`a[n]`) by the numeric\n * index `n` rather than insertion order. Only `index` format sets this. (#856)\n */\n indexed?: boolean;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n// Encodes a non-null array element. `null` is handled per-format by the caller\n// (bare-key / skip); this throws only on genuinely unserialisable elements\n// (`undefined`, objects) — which `parse` never produces in an array.\nconst encodeValue = (value: unknown): string => {\n const type = typeof value;\n\n if (type !== \"string\" && type !== \"number\" && type !== \"boolean\") {\n // `null` is handled by the caller (bare-key / skip) and never reaches here,\n // so `type` names the offender directly (`undefined`, `object`, `symbol`, …).\n // ⚑ Bare `[router]`, not `[router.buildPath]`. This is a diagnosis of a\n // VALUE, and the URL build it sits in is reached from `navigate`,\n // `navigateToDefault` and `makeState` as well as from `buildPath` — FOUR\n // core doors, instrumented at the throw site. ⚠ Not six: `navigateToState`\n // never reaches it, and `getStaticPaths` lives in `@real-router/ssr-utils`\n // rather than core, so neither is a call here. `printsNoQueryKey` on\n // `@real-router/core/validation` reaches it too and answers `false`\n // instead of letting it out (#3037).\n // Core's own log then printed\n // `[router.navigate] Unexpected navigation error TypeError:\n // [router.buildPath] …`, two contradictory attributions on one line. The\n // sibling refusals name a call because they HAVE one; this one does not, so\n // it names none rather than naming the wrong one.\n throw atRouter.type`Invalid query value: an array element must be a string, number, or boolean — received ${type}`;\n }\n\n return safeEncode(value as string | number | boolean);\n};\n\n// Repeats `${name}${suffix}` keys joined by `&`. Shared between `none` (suffix\n// `\"\"`) and `brackets` (suffix `\"[]\"`). A `null` element encodes to the SAME\n// wire token a scalar null does via `nullStrategy` — the bare key\n// `${name}${suffix}` under `nullFormat: \"default\"`, or `\"\"` (dropped, filtered\n// below so no `&&` appears) under `\"hidden\"`. So `parseQuery(\"a&a=1\")` →\n// `{a:[null,\"1\"]}` round-trips to `\"a&a=1\"` instead of throwing (#1155).\nconst repeatKey = (\n name: string,\n values: unknown[],\n suffix: string,\n nullStrategy: NullStrategy,\n): string => {\n const key = `${name}${suffix}`;\n const parts: string[] = [];\n\n for (const value of values) {\n if (value === null) {\n const encoded = nullStrategy.encode(key);\n\n if (encoded) {\n parts.push(encoded);\n }\n } else {\n parts.push(`${key}=${encodeValue(value)}`);\n }\n }\n\n return parts.join(\"&\");\n};\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * Repeated keys without brackets.\n * Example: items=a&items=b\n */\nexport const noneArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values, nullStrategy) =>\n repeatKey(name, values, \"\", nullStrategy),\n};\n\n/**\n * Bracket notation without index.\n * Example: items[]=a&items[]=b\n */\nexport const bracketsArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values, nullStrategy) =>\n repeatKey(name, values, \"[]\", nullStrategy),\n};\n\n/**\n * Indexed bracket notation.\n * Example: items[0]=a&items[1]=b\n */\nexport const indexArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values, nullStrategy) => {\n const parts: string[] = [];\n\n for (const [i, value] of values.entries()) {\n const key = `${name}[${i}]`;\n\n if (value === null) {\n const encoded = nullStrategy.encode(key);\n\n if (encoded) {\n parts.push(encoded);\n }\n } else {\n parts.push(`${key}=${encodeValue(value)}`);\n }\n }\n\n return parts.join(\"&\");\n },\n\n indexed: true,\n};\n\n/**\n * Comma-separated values.\n * Example: items=a,b,c\n *\n * Comma has no per-element bare-key form (an empty part like `a=,` decodes to\n * the empty string, not `null`), so a `null` element is unrepresentable and\n * dropped. `parse` only yields null-in-array under `comma` via a bracketed\n * chunk (`a[]`) — a wire/format mismatch, never the comma-native path — so this\n * is a total-but-lossy edge. The `nullStrategy` arg is intentionally omitted\n * (a 2-arg impl satisfies the 3-arg interface).\n */\nexport const commaArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values) => {\n const parts: string[] = [];\n\n for (const value of values) {\n if (value !== null) {\n parts.push(encodeValue(value));\n }\n }\n\n if (parts.length === 0) {\n return \"\";\n }\n\n return `${name}=${parts.join(\",\")}`;\n },\n\n decodeValue: (rawValue) => {\n // No unencoded comma → not an array (single value).\n // Encoded commas (%2C) are part of the value, not separators.\n if (!rawValue.includes(\",\")) {\n return null;\n }\n\n return rawValue.split(\",\");\n },\n};\n\n/**\n * Map of array format to strategy implementation.\n */\nexport const arrayStrategies: Record<ArrayFormat, ArrayStrategy> = {\n none: noneArrayStrategy,\n brackets: bracketsArrayStrategy,\n index: indexArrayStrategy,\n comma: commaArrayStrategy,\n};\n","/**\n * Boolean encoding/decoding strategies.\n *\n * @module search-params/strategies/boolean\n */\n\nimport type { DecodeResult, BooleanFormat } from \"../types\";\n\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for encoding/decoding boolean values.\n */\nexport interface BooleanStrategy {\n /**\n * Encodes a boolean value as a query string segment.\n *\n * @param name - URL-encoded parameter name\n * @param value - Boolean value to encode\n * @returns Query string segment (e.g., \"flag=true\" or just \"flag\")\n */\n encode: (name: string, value: boolean) => string;\n\n /**\n * Handles undefined value (key-only params like ?flag).\n *\n * @returns Decoded value for undefined\n */\n decodeUndefined: () => DecodeResult;\n\n /**\n * Decodes a raw (not URI-decoded) value before decodeValue() is called.\n * Used for formats that check raw values (e.g., \"auto\" checks \"true\"/\"false\").\n *\n * @param rawValue - Raw value before URI decoding\n * @returns boolean if matched, null to continue with URI decoding\n */\n decodeRaw: (rawValue: string) => boolean | null;\n\n /**\n * Decodes a URI-decoded value.\n *\n * @param decodedValue - Value after URI decoding\n * @returns Decoded value (boolean or the same string)\n */\n decodeValue: (decodedValue: string) => DecodeResult;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * No special boolean handling - values are treated as strings.\n */\nexport const noneBooleanStrategy: BooleanStrategy = {\n encode: (name, value) => `${name}=${value}`,\n decodeUndefined: () => null,\n decodeRaw: () => null, // No raw value matching\n decodeValue: (decoded) => decoded, // Return as-is\n};\n\n/**\n * Auto-detect \"true\"/\"false\" strings as boolean values.\n * Checks raw value before URI decoding.\n */\nexport const autoBooleanStrategy: BooleanStrategy = {\n encode: (name, value) => `${name}=${value}`,\n decodeUndefined: () => null,\n decodeRaw: (raw) => {\n if (raw === \"true\") {\n return true;\n }\n if (raw === \"false\") {\n return false;\n }\n\n return null; // Continue with URI decoding\n },\n decodeValue: (decoded) => decoded, // Return decoded string\n};\n\n/**\n * Scalar true values are key-only (no =value); scalar false keeps an explicit\n * `=false`. Example: `?flag` for true, `?flag=false` for false. Array elements\n * always carry an explicit value (`?a=true&a=false`), so decoding must map both\n * `\"true\"`→true and `\"false\"`→false to round-trip booleans losslessly in either\n * position — a key-only param is `true` (decodeUndefined), and any explicit\n * `=true`/`=false` decodes back to the boolean (not the string).\n */\nexport const emptyTrueBooleanStrategy: BooleanStrategy = {\n encode: (name, value) => (value ? name : `${name}=false`),\n decodeUndefined: () => true, // Key-only means true\n decodeRaw: (raw) => {\n if (raw === \"true\") {\n return true;\n }\n if (raw === \"false\") {\n return false;\n }\n\n return null; // Continue with URI decoding\n },\n decodeValue: (decoded) => decoded, // Return as-is\n};\n\n/**\n * Map of boolean format to strategy implementation.\n */\nexport const booleanStrategies: Record<BooleanFormat, BooleanStrategy> = {\n none: noneBooleanStrategy,\n auto: autoBooleanStrategy,\n \"empty-true\": emptyTrueBooleanStrategy,\n};\n","/**\n * Null encoding/decoding strategies.\n *\n * @module search-params/strategies/null\n */\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for encoding/decoding null values.\n */\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\nimport type { NullFormat } from \"../types\";\n\nexport interface NullStrategy {\n /**\n * Encodes a null value as a query string segment.\n *\n * @param name - URL-encoded parameter name\n * @returns Query string segment (e.g., \"key\" or \"\")\n */\n encode: (name: string) => string;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * Default null format - key only without value.\n * Example: ?key (no equals sign)\n */\nexport const defaultNullStrategy: NullStrategy = {\n encode: (name) => name,\n};\n\n/**\n * Null values are hidden (omitted from query string).\n * Example: (nothing)\n */\nexport const hiddenNullStrategy: NullStrategy = {\n encode: () => \"\",\n};\n\n/**\n * Map of null format to strategy implementation.\n */\nexport const nullStrategies: Record<NullFormat, NullStrategy> = {\n default: defaultNullStrategy,\n hidden: hiddenNullStrategy,\n};\n","/**\n * Number decoding strategies.\n *\n * @module search-params/strategies/number\n */\n\nimport type { NumberFormat } from \"../types\";\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for decoding number values.\n */\nexport interface NumberStrategy {\n decode: (decodedValue: string) => number | null;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * No special number handling - values remain strings.\n */\nexport const noneNumberStrategy: NumberStrategy = {\n decode: () => null, // passthrough\n};\n\n/**\n * Auto-detect numeric values and parse as numbers.\n * Matches integers and decimals via charCode scan (faster than regex for short strings).\n *\n * Recognizes an optional leading `-` so negatives round-trip symmetrically with the\n * values `navigate()`/`build()` produce (`build({ n: -5 })` → `\"n=-5\"`). Leading-zero\n * and unsafe-integer rejection apply to the magnitude regardless of sign. Exponent\n * notation stays a string — `build` never emits a canonical safe exponent, and unsafe\n * exponents would lose precision. (#742)\n */\nexport const autoNumberStrategy: NumberStrategy = {\n decode: (value) => {\n const length = value.length;\n\n if (length === 0) {\n return null;\n }\n\n // Optional leading minus; the magnitude (digits) begins at `start`.\n const start = value.codePointAt(0) === 45 ? 1 : 0; // '-'\n\n // A bare \"-\" has no magnitude.\n if (start === length) {\n return null;\n }\n\n // Leading zeros are not canonical numbers (\"00\", \"007\", \"-007\") — preserve as strings.\n // Allow \"0\" and \"0.x\" (single zero or decimal starting with 0).\n if (\n length - start > 1 &&\n value.codePointAt(start) === 48 &&\n value.codePointAt(start + 1) !== 46\n ) {\n return null;\n }\n\n let hasDot = false;\n\n for (let i = start; i < length; i++) {\n const ch = value.codePointAt(i);\n\n if (ch !== undefined && ch >= 48 && ch <= 57) {\n continue; // '0'-'9'\n }\n\n if (ch === 46 && !hasDot && i !== start && i !== length - 1) {\n hasDot = true;\n\n continue;\n }\n\n return null; // non-digit, non-dot, or invalid dot position\n }\n\n const num = Number(value);\n\n // The stated criterion is round-trip stability, enforced directly rather than\n // through per-case guards: `build` prints a number with String(), so a value\n // may be coerced only when String() reproduces the exact text we parsed. This\n // subsumes the former negative-zero guard (String(-0) === \"0\" ≠ \"-0\", #898)\n // and closes the decimal family the safe-integer check below deliberately\n // exempts — trailing zeros (\"2.0\" → 2 → \"2\") and precision loss\n // (\"9007199254740993.5\" → 9007199254740994), both of which rebuilt a URL\n // different from the one that was matched. (#1565)\n if (String(num) !== value) {\n return null;\n }\n\n // Unsafe integers pass the text check (2**53 prints back exactly) but lose\n // precision in arithmetic, so they stay strings. Decimals are exempt: a\n // fractional value is never a \"safe integer\", and the check above already\n // proves its text round-trips.\n if (!Number.isSafeInteger(num) && !hasDot) {\n return null;\n }\n\n return num;\n },\n};\n\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\n/**\n * Map of number format to strategy implementation.\n */\nexport const numberStrategies: Record<NumberFormat, NumberStrategy> = {\n auto: autoNumberStrategy,\n none: noneNumberStrategy,\n};\n","/**\n * Search Params Strategies - Factory and Types.\n *\n * Provides a unified interface for format-specific encoding/decoding strategies.\n * Strategies are resolved once when options are created, avoiding repeated\n * format checks during encode/decode operations.\n *\n * @module search-params/strategies\n */\n\nimport { arrayStrategies, type ArrayStrategy } from \"./array\";\nimport { booleanStrategies, type BooleanStrategy } from \"./boolean\";\nimport { nullStrategies, type NullStrategy } from \"./null\";\nimport { numberStrategies, type NumberStrategy } from \"./number\";\nimport { raiser } from \"../../../RouterError\";\n\nimport type { FinalOptions } from \"../types\";\n\nconst atRouter = raiser(\"router\");\n\n/**\n * Intrinsics captured at module load: `defineProperty`, `objectKeys`, `hasOwn`.\n *\n * ⚑ A guard is only as strong as the intrinsic it reads WHEN IT RUNS, and an\n * application can re-point any of these AFTER boot — which is what this closes.\n * Measured on the uncaptured form: one naive `Object.hasOwn` polyfill walked\n * straight through five sibling readers while the single captured guard held.\n *\n * ⚠ The limit of what capture buys — and the shim order that defeats it — is\n * stated once, in `guards.ts`. Not restated here (#2091).\n */\nconst defineProperty = Object.defineProperty;\nconst objectKeys = Object.keys;\nconst hasOwn = Object.hasOwn;\n// =============================================================================\n// Exports\n// =============================================================================\n\nexport type { ArrayStrategy } from \"./array\";\n\nexport type { BooleanStrategy } from \"./boolean\";\n\nexport type { NullStrategy } from \"./null\";\n\nexport type { NumberStrategy } from \"./number\";\n\n// =============================================================================\n// Resolved Strategies\n// =============================================================================\n\n/**\n * Pre-resolved strategies based on options.\n * Created once when makeOptions() is called, avoiding repeated lookups.\n */\nexport interface ResolvedStrategies {\n readonly boolean: BooleanStrategy;\n readonly null: NullStrategy;\n readonly number: NumberStrategy;\n readonly array: ArrayStrategy;\n}\n\n/**\n * `Object.hasOwn`, captured before any application code can run.\n *\n * ⚑ This is the RAISER of the config fault `SegmentMatcher`'s predicate exists\n * to recognise, so leaving it reading the mutable global made hardening that\n * predicate pointless: measured, `Object.hasOwn = () => true` after boot let an\n * invalid format through `createRouter` and every query URL then resolved to\n * `UNKNOWN_ROUTE` — the #1318 symptom, restored.\n */\n\nexport const CONFIG_FAULT: unique symbol = Symbol.for(\n \"real-router.searchParams.configFault\",\n);\n\n/**\n * Fail fast on an unknown format. A `queryParams` typo in a JS consumer (no TS to\n * forbid it) otherwise indexes the strategy map to `undefined`, deferring a cryptic\n * `TypeError` to first use — which the router's `SegmentMatcher.#mergeQueryParams`\n * catch-all then masks as `UNKNOWN_ROUTE` for EVERY query URL, with zero diagnostics\n * (#1318). TS consumers are unaffected (the union types already forbid the typo).\n */\nconst requireStrategy = <T>(\n table: Record<string, T>,\n // ⚠ `unknown`, not `string`. The declared type is exactly what this guard\n // cannot trust: a TS consumer is already forbidden the typo by the union, so\n // every value that reaches the throw came from a JS consumer or a\n // runtime-assembled config. Typing it `string` made `String(value)` look like\n // a no-op to the linter, which is the same false confidence in reverse.\n value: unknown,\n field: string,\n): T => {\n // `Object.hasOwn` on the table, NOT `=== undefined` on a lookup the caller\n // already performed (#1796). These tables are plain object literals indexed by\n // a string the consumer supplies, so for any of `Object.prototype`'s twelve own\n // members the lookup returns a MEMBER instead of `undefined` (eleven of the\n // twelve are functions; `__proto__` yields `Object.prototype` itself, which\n // fails one step later since it carries no `encode` / `encodeArray`): the\n // `undefined` test passed and that member was installed as the live strategy —\n // precisely the deferred\n // `TypeError` this guard exists to prevent, reached through the one value class\n // its predicate could not see.\n //\n // The guard OWNS the lookup for the same reason. A predicate handed the RESULT\n // of someone else's read cannot tell \"absent\" from \"inherited\"; asking the\n // container directly is what makes the two inseparable.\n //\n // ⚑ And it owns the KEY, for the same reason once more. Owning the lookup is\n // only half of it: `Object.hasOwn` and the `table[…]` below each run\n // `ToPropertyKey`, so passing the caller's VALUE through both reads it twice.\n // A `{ toString }` answering \"none\" to the guard and \"toString\" to the lookup\n // was admitted as one format and used as another, which is the deferred\n // `opts.strategies.array.encodeArray is not a function` this guard exists to\n // prevent — the same defect one layer out from the one it fixed. One\n // coercion, above the check, and verdict and use cannot disagree.\n // ⚠ `typeof` first, not a bare `String(value)` — and NOT as a hot-path term.\n // Resolution happens at matcher construction, four calls per ROUTER, not\n // twice per `matchPath` where an unconditional coercion measured +3.5 %. It\n // stays because for a real string it returns the value untouched,\n // which is simply the honest shape, and because the coercion is reserved for\n // exactly the values this guard exists to refuse.\n const key = typeof value === \"string\" ? value : String(value);\n\n // ⚠ One consequence worth naming: a SYMBOL now yields this named error instead\n // of `Cannot convert a Symbol value to a string`. The guard always detected it\n // — `Object.hasOwn` answered `false` — but building the message threw from the\n // template, so the named error never reached the caller for that one class.\n\n // ⚑ The BARE head, and the option's FULL PATH. Two doors reach this refusal —\n // `createRouter` and `cloneRouter`, both through `new RouterClass(...)` — so a\n // head naming one of them would name a call half the callers did not make, and\n // `constructor` names one nobody types (#2487).\n //\n // ⚑ A `[search-params]` prefix is refused for a different reason: it names a\n // layer that is not a package (#1510) and that the caller never wrote; paired\n // with the bare field it points at neither a thing the user typed nor a thing\n // they could look up. The full path is what carries that instead.\n //\n // ⚠ The objection this survives — that the hoist also runs from `cloneRouter`\n // and every matcher rebuild, so the prefix would be false on most doors — is\n // refuted by measurement: the snapshot and its container are both frozen, so\n // a rebuild has nothing left that can fail, and `cloneRouter` raises through\n // `new RouterClass(...)`. Both doors that can raise ARE the constructor.\n if (!hasOwn(table, key)) {\n const error = atRouter.type`Invalid \"queryParams.${field}\": \"${key}\" — expected ${objectKeys(\n table,\n )\n .map((name) => `\"${name}\"`)\n .join(\" | \")}`;\n\n // ⚑ TAGGED, because the parse catch must recognise this by ORIGIN and not by\n // class. `match()` must never throw on INPUT, and the catch around the parse\n // is that contract's backstop; narrowing it to \"rethrow anything that is not\n // a `URIError`\" inverted the default from fail-safe to fail-open, and the\n // enumeration of throwers behind that inversion was incomplete. `assignParam`\n // writes `params[name] = value` with the name taken from the URL, so an\n // application setter on `Object.prototype` for that name runs inside the\n // guarded `try`, and its error is neither a `URIError` nor ours. Measured: a\n // throwing setter for a key a URL supplies propagated out of `matchPath` —\n // into the popstate handlers of the three URL plugins and `preload-plugin`'s\n // hover path, none of which catch.\n //\n // A marker on OUR error lets the catch rethrow exactly what it means to\n // rethrow — the config fault #1796 refuses to swallow — and go on swallowing\n // everything else, which is what the contract says. A property rather than a\n // subclass: the message and the `TypeError` identity are what consumers see,\n // and neither moves.\n defineProperty(error, CONFIG_FAULT, { value: true });\n\n throw error;\n }\n\n return table[key];\n};\n\nexport const resolveStrategies = (\n arrayFormat: FinalOptions[\"arrayFormat\"],\n booleanFormat: FinalOptions[\"booleanFormat\"],\n nullFormat: FinalOptions[\"nullFormat\"],\n numberFormat: FinalOptions[\"numberFormat\"],\n): ResolvedStrategies => ({\n boolean: requireStrategy(booleanStrategies, booleanFormat, \"booleanFormat\"),\n null: requireStrategy(nullStrategies, nullFormat, \"nullFormat\"),\n number: requireStrategy(numberStrategies, numberFormat, \"numberFormat\"),\n array: requireStrategy(arrayStrategies, arrayFormat, \"arrayFormat\"),\n});\n\n// =============================================================================\n// Default Strategies\n// =============================================================================\n\n/**\n * Default strategies matching DEFAULT_OPTIONS.\n * Used when no custom options are provided.\n */\nexport const DEFAULT_STRATEGIES: ResolvedStrategies = Object.freeze({\n boolean: booleanStrategies.auto,\n null: nullStrategies.default,\n number: numberStrategies.auto,\n array: arrayStrategies.none,\n});\n","/**\n * Encoding functions for search-params.\n *\n * Uses Strategy pattern for format-specific encoding.\n * Strategies are resolved once when options are created.\n *\n * @module search-params/encode\n */\n\nimport {\n DEFAULT_STRATEGIES,\n resolveStrategies,\n type ResolvedStrategies,\n} from \"./strategies\";\nimport { safeEncode } from \"./utils\";\n\nimport type { FinalOptions, Options } from \"./types\";\n\n// =============================================================================\n// Default Query Params\n// =============================================================================\n\n/**\n * Default query parameter options. Single source of truth for all packages.\n */\nexport const DEFAULT_QUERY_PARAMS: FinalOptions = Object.freeze({\n arrayFormat: \"none\",\n booleanFormat: \"auto\",\n nullFormat: \"default\",\n numberFormat: \"auto\",\n});\n\n// =============================================================================\n// Options with Strategies\n// =============================================================================\n\n/**\n * Extended options with pre-resolved strategies.\n */\nexport interface OptionsWithStrategies extends FinalOptions {\n readonly strategies: ResolvedStrategies;\n}\n\n/**\n * Cached default options with strategies - avoids allocation when no options passed.\n *\n * ⚑ FROZEN, and both siblings above with it. `makeOptions` hands this exact object\n * back by reference — a pinned perf invariant, not an accident — so an unfrozen\n * one is a process-global (the #897 class: `LEVEL_CONFIGS` exported unfrozen\n * corrupted the global threshold). Nothing in the engine mutates any of the\n * three; they are read-only by intent, and now by construction.\n *\n * ⚠ Who actually reaches THIS object is narrower than \"every default router\", and\n * the distinction is worth keeping straight because the two singletons differ.\n * `OptionsNamespace` fills `queryParams` with `DEFAULT_QUERY_PARAMS`, whose four\n * fields are all DEFINED — so the all-undefined guard below does not fire and a\n * default-configured router gets a FRESH object. `DEFAULT_QUERY_PARAMS` is the\n * one every such router shares by reference; this one is reached by a caller that\n * passes nothing, or a bag with no format set.\n *\n * Frozen HERE, at its own site, because nothing else SEALS it: it is\n * `OptionsNamespace`'s default `queryParams`, and that freeze stops at the level\n * core owns (#1832).\n */\nconst DEFAULT_OPTIONS: OptionsWithStrategies = Object.freeze({\n ...DEFAULT_QUERY_PARAMS,\n strategies: DEFAULT_STRATEGIES,\n});\n\n/**\n * Creates options with defaults and pre-resolved strategies.\n * Returns cached DEFAULT_OPTIONS when no custom options are specified.\n */\nexport const makeOptions = (opts?: Options): OptionsWithStrategies => {\n if (\n !opts ||\n (opts.arrayFormat === undefined &&\n opts.booleanFormat === undefined &&\n opts.nullFormat === undefined &&\n opts.numberFormat === undefined)\n ) {\n return DEFAULT_OPTIONS;\n }\n\n // Avoid object spread - direct property assignment is faster\n const arrayFormat = opts.arrayFormat ?? DEFAULT_QUERY_PARAMS.arrayFormat;\n const booleanFormat =\n opts.booleanFormat ?? DEFAULT_QUERY_PARAMS.booleanFormat;\n const nullFormat = opts.nullFormat ?? DEFAULT_QUERY_PARAMS.nullFormat;\n const numberFormat = opts.numberFormat ?? DEFAULT_QUERY_PARAMS.numberFormat;\n\n return {\n arrayFormat,\n booleanFormat,\n nullFormat,\n numberFormat,\n strategies: resolveStrategies(\n arrayFormat,\n booleanFormat,\n nullFormat,\n numberFormat,\n ),\n };\n};\n\n// =============================================================================\n// Value Encoding\n// =============================================================================\n\n/**\n * Encodes a value for use in a URL query string.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument\nexport const encodeValue = (value: any): string => safeEncode(value);\n\n// =============================================================================\n// Main Encode\n// =============================================================================\n\n/**\n * Encodes a parameter name and value as a query string segment.\n *\n * Uses pre-resolved strategies for format-specific encoding.\n * Strategies handle all formats uniformly - no inline optimizations\n * to avoid equivalent mutants in mutation testing.\n *\n * @param name - Parameter name\n * @param value - Parameter value\n * @param opts - Options with pre-resolved strategies\n * @returns Query string segment (e.g., \"key=value\")\n */\nexport const encode = (\n name: string,\n value: unknown,\n opts: OptionsWithStrategies,\n): string => {\n const encodedName = encodeValue(name);\n\n // Handle each type using strategies\n switch (typeof value) {\n case \"string\":\n case \"number\": {\n return `${encodedName}=${encodeValue(value)}`;\n }\n case \"boolean\": {\n return opts.strategies.boolean.encode(encodedName, value);\n }\n case \"object\": {\n // Null check\n if (value === null) {\n return opts.strategies.null.encode(encodedName);\n }\n // Array check\n if (Array.isArray(value)) {\n return opts.strategies.array.encodeArray(\n encodedName,\n value,\n opts.strategies.null,\n );\n }\n\n // Fallback for other objects - treat as string\n return `${encodedName}=${encodeValue(value)}`;\n }\n default: {\n // Fallback for other types (undefined handled by caller)\n return `${encodedName}=${encodeValue(value)}`;\n }\n }\n};\n","/**\n * Search Params - Query String Parsing and Building.\n *\n * Internalized from https://github.com/troch/search-params (MIT License)\n * for better code control and optimization.\n *\n * @module search-params/searchParams\n */\n\nimport { decode, decodeValue } from \"./decode\";\nimport { encode, makeOptions } from \"./encode\";\nimport { putField } from \"../../utils/ingest\";\n\nimport type { OptionsWithStrategies } from \"./encode\";\nimport type { ResolvedStrategies } from \"./strategies\";\nimport type { Options } from \"./types\";\n\n/**\n * Intrinsics captured at module load: `hasOwn`, `objectKeys`.\n *\n * ⚑ A guard is only as strong as the intrinsic it reads WHEN IT RUNS, and an\n * application can re-point any of these AFTER boot — which is what this closes.\n * Measured on the uncaptured form: one naive `Object.hasOwn` polyfill walked\n * straight through five sibling readers while the single captured guard held.\n *\n * ⚠ The limit of what capture buys — and the shim order that defeats it — is\n * stated once, in `guards.ts`. Not restated here (#2091).\n */\nconst hasOwn = Object.hasOwn;\nconst objectKeys = Object.keys;\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Assigns a parameter as an own data property.\n *\n * ⚑ The name comes straight out of the URL, so the whole prototype chain is in\n * play — not just `\"__proto__\"` (#1852), and `putField` is what covers the rest\n * of it. Measured on `matchPath('/q?tab=x')` with an ambient `tab`: a\n * getter-only or non-writable property made the URL STOP MATCHING (the throw is\n * swallowed by the documented fail-open `#737` catch, so the caller sees\n * `UNKNOWN_ROUTE` rather than an error), and a getter+setter pair stole the\n * value outright — `state.search` empty beside a `state.path` that still carried\n * the query.\n *\n * @internal\n */\nfunction assignParam(\n params: Record<string, unknown>,\n name: string,\n value: unknown,\n): void {\n putField(params, name, value);\n}\n\n/**\n * Adds a decoded value to params object, handling array accumulation.\n *\n * Collisions are detected via `Object.hasOwn`, not `params[name] !== undefined`:\n * a query key that shadows an `Object.prototype` member (`valueOf`, `constructor`,\n * `toString`, …) would otherwise read the inherited function and be mistaken for\n * a pre-existing value, corrupting the result into `[<fn>, value]`. (#855)\n *\n * @internal\n */\nfunction addToParams(\n params: Record<string, unknown>,\n decodedName: string,\n decodedValue: unknown,\n hasBrackets: boolean,\n): void {\n if (!hasOwn(params, decodedName)) {\n assignParam(\n params,\n decodedName,\n hasBrackets ? [decodedValue] : decodedValue,\n );\n\n return;\n }\n\n const currentValue = params[decodedName];\n\n if (Array.isArray(currentValue)) {\n currentValue.push(decodedValue);\n } else {\n assignParam(params, decodedName, [currentValue, decodedValue]);\n }\n}\n\n/**\n * Reads the non-negative integer index from a bracketed name (`a[12]`).\n *\n * `open` points at the `[`; digits up to the matching `]` form the index. Returns\n * `null` for `[]`, non-digit content (`a[x]`), or a missing `]` — those fall back\n * to insertion-order accumulation. (#856)\n *\n * @internal\n */\nfunction bracketIndex(\n searchPart: string,\n open: number,\n limit: number,\n): number | null {\n let i = open + 1;\n let value = 0;\n let hasDigit = false;\n\n while (i < limit) {\n const ch = searchPart.codePointAt(i);\n\n if (ch === 93) {\n // ']' — a numeric index only if at least one digit preceded it (\"[]\" → null)\n return hasDigit ? value : null;\n }\n\n if (ch !== undefined && ch >= 48 && ch <= 57) {\n value = value * 10 + (ch - 48);\n hasDigit = true;\n i++;\n\n continue;\n }\n\n return null; // non-digit inside brackets — not a numeric index\n }\n\n return null; // no closing ']' (incl. \"[\" at end) — malformed, fall back\n}\n\n/**\n * A single parsed query chunk: the source string plus the boundary offsets and\n * decoded name that `processParamChunk` computes once. Bundled into one\n * descriptor so the indexed-format collector reuses them without a long\n * parameter list (#856).\n *\n * @internal\n */\ninterface ParsedChunk {\n searchPart: string;\n /** Offset of `[` (bracket notation), or the name terminator. */\n nameEnd: number;\n /** Offset where the raw name ends (`=` for valued chunks, else `end`). */\n nameSourceEnd: number;\n /**\n * The chunk's raw value slice, or `undefined` for a key-only chunk (#1982).\n * Carried instead of a `hasValue` boolean: the boolean was derivable from\n * `eqPos` and `end`, which every consumer already had, so it was the same fact\n * spelled twice — and the comma arm then cut the string a SECOND time to get\n * what this field already holds.\n */\n rawValue: string | undefined;\n decodedName: string;\n}\n\n/**\n * Collects a bracketed chunk into the index-format group, to be sorted by index\n * after the full pass. Returns `false` when the bracket is not a numeric index\n * (`a[]`, `a[x]`, `a[`), so the caller falls back to insertion-order push. (#856)\n *\n * @internal\n */\nfunction collectIndexedChunk(\n chunk: ParsedChunk,\n strategies: ResolvedStrategies,\n indexedGroups: Map<string, [number, unknown][]>,\n): boolean {\n const { searchPart, nameEnd, nameSourceEnd, rawValue, decodedName } = chunk;\n const index = bracketIndex(searchPart, nameEnd, nameSourceEnd);\n\n if (index === null) {\n return false;\n }\n\n const value = decode(rawValue, strategies);\n const group = indexedGroups.get(decodedName);\n\n if (group === undefined) {\n indexedGroups.set(decodedName, [[index, value]]);\n } else {\n group.push([index, value]);\n }\n\n // Stryker disable next-line BooleanLiteral: equivalent — returning false makes the caller ALSO push via insertion order, but indexedGroups was already populated above and parseIntoInternal overwrites the key with the index-sorted result, so the final params are identical (proven by injection).\n return true;\n}\n\n/**\n * Processes a single query parameter chunk and adds to params.\n *\n * `indexedGroups` is supplied only for `arrayFormat: \"index\"`: bracketed chunks\n * with a numeric index are collected there (to be sorted by index after the full\n * pass) instead of pushed in insertion order. (#856)\n *\n * @internal\n */\nfunction processParamChunk(\n searchPart: string,\n start: number,\n end: number,\n params: Record<string, unknown>,\n strategies: ResolvedStrategies,\n eqPos: number,\n indexedGroups?: Map<string, [number, unknown][]>,\n): void {\n // `eqPos` is the position of the next `=` at or after `start`, resolved once by\n // the caller's monotonic cursor (#1316) — never re-scanned here. `eqPos < end`\n // means it falls inside THIS chunk (so the chunk has a value); otherwise the\n // chunk is key-only.\n const rawValue =\n eqPos !== -1 && eqPos < end ? searchPart.slice(eqPos + 1, end) : undefined;\n\n const nameSourceEnd = rawValue === undefined ? end : eqPos;\n let nameEnd = nameSourceEnd;\n let hasBrackets = false;\n\n for (let i = start; i < nameSourceEnd; i++) {\n if (searchPart.codePointAt(i) !== 91) {\n continue;\n }\n\n // '['\n nameEnd = i;\n hasBrackets = true;\n\n break;\n }\n\n const decodedName = decodeValue(searchPart.slice(start, nameEnd));\n\n // Index array format: order by the bracket index, not insertion. A non-numeric\n // bracket (`a[]`, `a[x]`) returns false → falls through to insertion-order push.\n if (\n indexedGroups !== undefined &&\n hasBrackets &&\n collectIndexedChunk(\n { searchPart, nameEnd, nameSourceEnd, rawValue, decodedName },\n strategies,\n indexedGroups,\n )\n ) {\n return;\n }\n\n // Comma array decode: split raw value before individual element decoding\n if (!hasBrackets && rawValue !== undefined && strategies.array.decodeValue) {\n const parts = strategies.array.decodeValue(rawValue);\n\n if (parts) {\n for (const part of parts) {\n addToParams(params, decodedName, decode(part, strategies), true);\n }\n\n return;\n }\n }\n\n const decodedValue = decode(rawValue, strategies);\n\n addToParams(params, decodedName, decodedValue, hasBrackets);\n}\n\n// =============================================================================\n// Parse\n// =============================================================================\n\n/**\n * Parse an ALREADY-EXTRACTED query string (no path prefix, no leading \"?\") into\n * an object of parameters.\n *\n * The input must already be split at the first \"?\" — `SegmentMatcher.#preparePath`\n * does this before the DI call, so route-tree wires `parseQuery` (not a\n * path-accepting wrapper) as its query parser: re-splitting the input here would\n * break at a \"?\" *inside* a query value (legal per RFC 3986), silently dropping\n * the param (and unmatching the whole URL under `strictQueryParams`). (#1292)\n *\n * @example\n * ```typescript\n * parseQuery(\"page=1&sort=name\");\n * // => { page: 1, sort: \"name\" }\n *\n * parseQuery(\"items[]=a&items[]=b\", { arrayFormat: \"brackets\" });\n * // => { items: [\"a\", \"b\"] }\n * ```\n */\nexport const parseQuery = (\n search: string,\n opts?: Options,\n): Record<string, unknown> =>\n // makeOptions(undefined) returns the cached DEFAULT_OPTIONS (auto) — the same\n // defaults `build` uses — so parseQuery(build(x)) === x even without options. (#744)\n parseQueryWith(search, makeOptions(opts));\n\n/**\n * `parseQuery` over ALREADY-RESOLVED options.\n *\n * The split exists so a long-lived consumer can resolve once and keep the result\n * (#1796 follow-up): `resolveStrategies` is what refuses an invalid `queryParams`\n * format. Resolved per call, that refusal arrives from inside `matchPath` — on\n * the parse path, where `SegmentMatcher`'s `#737` catch swallows it and where\n * consumers call from popstate and `navigate`-event handlers that have nobody to\n * catch for them. `createMatcher` resolves at construction instead, so a config\n * error surfaces from `createRouter` and this function cannot raise one.\n *\n * Second effect, measured: resolved per call with a customised format,\n * `makeOptions` re-resolves all four strategies on EVERY parse and allocates a\n * fresh options object each time.\n */\nexport const parseQueryWith = (\n search: string,\n options: OptionsWithStrategies,\n): Record<string, unknown> => {\n // Fast path: empty query string\n if (search === \"\" || search === \"?\") {\n return {};\n }\n\n const params: Record<string, unknown> = {};\n\n parseIntoInternal(search, params, options.strategies);\n\n return params;\n};\n\n/**\n * Internal function to parse a query string into a target object.\n * The shared parse engine behind `parseQuery`.\n *\n * @internal\n */\nfunction parseIntoInternal(\n searchPart: string,\n params: Record<string, unknown>,\n strategies: ResolvedStrategies,\n): void {\n // `index` format orders by the bracket index; collect (index, value) pairs and\n // sort after the pass. `undefined` for every other format (no overhead). (#856)\n const indexedGroups = strategies.array.indexed\n ? new Map<string, [number, unknown][]>()\n : undefined;\n\n let start = 0;\n const length = searchPart.length;\n\n // Monotonic cursor for the next `=`. Its position only ever moves forward with\n // `start`, so the whole parse does a single amortised O(n) scan for `=` —\n // replacing `processParamChunk`'s former per-chunk `indexOf(\"=\", start)`, which\n // scanned to the end of the string on every key-only chunk and made `parse`\n // O(n²) on `\"a&a&…\"` (#1316). `-2` = not yet searched; `-1` = no `=` remains.\n let eqCache = -2;\n\n while (start < length) {\n let end = searchPart.indexOf(\"&\", start);\n\n if (end === -1) {\n end = length;\n }\n\n // Skip empty chunks — a `&&`, a leading `&`, or a trailing `&` produces a\n // zero-length span that carries no name and no value. Processing it would\n // decode the empty name to `\"\"` and the missing value to `null`, injecting a\n // junk `{ \"\": null }` param (and `[null, …]` on repeats) (#1156). An\n // intentional empty-key chunk always carries an `=` (`\"=1\"` → `end > start`),\n // so it is unaffected.\n if (end > start) {\n // Advance the cursor only when the cached `=` is behind the current chunk;\n // once it reports `-1` (no `=` left in the string) it is final.\n if (eqCache !== -1 && eqCache < start) {\n eqCache = searchPart.indexOf(\"=\", start);\n }\n\n processParamChunk(\n searchPart,\n start,\n end,\n params,\n strategies,\n eqCache,\n indexedGroups,\n );\n }\n\n start = end + 1;\n }\n\n if (indexedGroups !== undefined) {\n for (const [name, pairs] of indexedGroups) {\n // Stable sort by index (V8 sort is stable) → equal indices keep arrival order.\n pairs.sort((left, right) => left[0] - right[0]);\n assignParam(\n params,\n name,\n pairs.map((pair) => pair[1]),\n );\n }\n }\n}\n\n// =============================================================================\n// Build\n// =============================================================================\n\n/**\n * Build a querystring from an object of parameters.\n *\n * Note: Empty arrays produce an empty string, so `parseQuery(build({ items: [] }))`\n * will not contain the `items` key. This is expected behavior for all array\n * formats including `comma` — the key is erased uniformly (INVARIANTS Parse/Build #9).\n *\n * @example\n * ```typescript\n * build({ page: 1, sort: \"name\" });\n * // => \"page=1&sort=name\"\n *\n * build({ items: [\"a\", \"b\"] }, { arrayFormat: \"brackets\" });\n * // => \"items[]=a&items[]=b\"\n * ```\n */\nexport const build = (\n params: Record<string, unknown>,\n opts?: Options,\n): string => buildWith(params, makeOptions(opts));\n\n/**\n * Whether the query build prints NO key for `key` holding `value` under the\n * format `opts` — such as an empty array in every `arrayFormat`, or `null`\n * under `nullFormat: \"hidden\"` (#3037). Asked of `build` itself, so the answer\n * is the decision `buildWith` takes for that one key and the rule keeps one\n * home. The key is part of the question: under the default `nullFormat`, `null`\n * prints as the bare key, which for the empty key is no key at all.\n * `undefined`, which the build skips, answers `true` as well. `opts` may be a\n * partial bag, as `PluginApi.getOptions().queryParams` hands it out: `build`\n * resolves the defaults the matcher resolves.\n *\n * A value the build refuses answers `false`: it is refused, not erased. The\n * callers are diagnostics, and a diagnostic must never become the thing that\n * throws (`channels/CLAUDE.md`): `getStaticPaths` asks about an entry's value\n * before the route's `encodeParams` prints it, so a refusal here would replace\n * its report with one about a value the URL never held. The format is resolved\n * outside that catch, so an unknown one still fails fast (#1318).\n */\nexport const printsNoQueryKey = (\n key: string,\n value: unknown,\n opts?: Options,\n): boolean => {\n const options = makeOptions(opts);\n\n try {\n return buildWith({ [key]: value }, options) === \"\";\n } catch {\n return false;\n }\n};\n\n/** `build` over ALREADY-RESOLVED options — see {@link parseQueryWith}. */\nexport const buildWith = (\n params: Record<string, unknown>,\n options: OptionsWithStrategies,\n): string => {\n // Fast path for empty params (common case)\n const keys = objectKeys(params);\n\n if (keys.length === 0) {\n return \"\";\n }\n\n // Optimized: single loop instead of filter().map().filter().join()\n // Avoids creating 3 intermediate arrays\n const parts: string[] = [];\n\n for (const key of keys) {\n const value = params[key];\n\n // Skip undefined values (not serialisable)\n if (value === undefined) {\n continue;\n }\n\n const encoded = encode(key, value, options);\n\n // Skip empty strings (e.g., from nullFormat: \"hidden\")\n if (encoded) {\n parts.push(encoded);\n }\n }\n\n return parts.join(\"&\");\n};\n","/**\n * The route-name rules, one named predicate each — the name-side counterpart to\n * {@link validateRoutePath} in `./routes`.\n *\n * Two layers apply them, and they apply different subsets. Bare-core\n * registration (`namespaces/RoutesNamespace/routesStore.ts`) applies the dotted\n * rule on every door; {@link validateRoute} — which core exports for\n * `@real-router/validation-plugin` and never calls itself — applies all of\n * them.\n *\n * ⚑ One owner per rule is the point of this file: putting a rule on the live\n * path is a CALL, never a second copy of its message (#2035).\n *\n * A `methodName` of `undefined` is why two predicates take `string | undefined`:\n * `createRouter` and `cloneRouter` reach them through the constructor, so neither\n * names a door the caller typed, and the raiser renders the bare head (#2487).\n */\n\n/**\n * Route names are ASCII — a letter or underscore, then letters, digits,\n * underscores or hyphens.\n */\nimport { raiser } from \"../../RouterError\";\n\nconst ROUTE_NAME_PATTERN = /^[A-Z_a-z][\\w-]*$/;\n\n/**\n * Matches when the name carries at least one non-whitespace character.\n */\nconst HAS_NON_WHITESPACE = /\\S/;\n\n/**\n * Maximum route name length, bounding DoS and performance risk.\n */\nconst MAX_ROUTE_NAME_LENGTH = 10_000;\n\n/**\n * Refuses `{ name: \"\" }`.\n */\nexport function assertRouteNameNotEmpty(\n name: string,\n methodName: string | undefined,\n): void {\n if (name === \"\") {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route name cannot be empty`;\n }\n}\n\n/**\n * Refuses a name built only of whitespace.\n */\nexport function assertRouteNameNotWhitespaceOnly(\n name: string,\n methodName: string,\n): void {\n if (!HAS_NON_WHITESPACE.test(name)) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route name cannot contain only whitespace`;\n }\n}\n\n/**\n * Refuses a name longer than {@link MAX_ROUTE_NAME_LENGTH}.\n */\nexport function assertRouteNameWithinLength(\n name: string,\n methodName: string,\n): void {\n if (name.length > MAX_ROUTE_NAME_LENGTH) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route name exceeds maximum length of ${MAX_ROUTE_NAME_LENGTH} characters`;\n }\n}\n\n/**\n * Refuses a BARE route name carrying a dot — `{ name: \"users.view\" }` where the\n * nesting must be spelled with `children` or `{ parent }` (#1763).\n *\n * ⚠ Carries no \"@@\" exemption. {@link validateRoute} returns early on a\n * reserved name before reaching this predicate, and bare-core registration\n * refuses one outright, so neither caller needs one.\n */\nexport function assertNoDottedRouteName(\n name: string,\n methodName: string | undefined,\n): void {\n if (name.includes(\".\")) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route name \"${name}\" cannot contain dots. Use children array or { parent } option in addRoute() instead.`;\n }\n}\n\n/**\n * Refuses a name outside {@link ROUTE_NAME_PATTERN}.\n */\nexport function assertRouteNameMatchesPattern(\n name: string,\n methodName: string,\n): void {\n if (!ROUTE_NAME_PATTERN.test(name)) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Invalid route name \"${name}\". Name must start with a letter or underscore, followed by letters, numbers, underscores, or hyphens.`;\n }\n}\n","import { raiser } from \"../../RouterError\";\nimport {\n buildParamMeta,\n describeRemovedForm,\n findSegmentGrammarError,\n INVALID_QUERY_NAME_RGX,\n} from \"../path-matcher\";\n\nimport type { RemovedForm, SegmentErrorCode } from \"../path-matcher\";\nimport type { RouteTree } from \"../types\";\n\n/**\n * Creates a TypeError with consistent router error message format.\n *\n * @param methodName - Name of the method that triggered the error\n * @param message - Error message\n * @returns TypeError with formatted message\n * @internal\n */\nfunction createRouterError(methodName: string, message: string): TypeError {\n const at = raiser(\"router\", methodName);\n\n return at.type`${message}`;\n}\n\n/**\n * Rejects a param name repeated within one route's own path (`/:id/:id`, a\n * param+splat clash `/:x/*x`, #1151). `buildParamMeta.urlParams` lists every\n * path-binding name — params AND splats — in order, keeping duplicates (`/:x/*x`\n * → `[\"x\", \"x\"]`), so a single pass over it catches both. The trie binds the\n * duplicates at different positions under one name, so match's later capture\n * silently overwrites the earlier and `rewritePathOnMatch` then rewrites the\n * user's URL from the single survivor. The #736 conflict guard only fires on\n * DIFFERENTLY-named params at one position, so this same-name case slips through.\n * path-matcher's `registerTree` backstop additionally catches CROSS-level dups (a\n * parent's param reused by a child), which this per-path gate cannot see. ⚠ With\n * a hole, stated as its CAUSE rather than as a list of shapes, because the list\n * is longer than it looks: that backstop reads the names off `buildParamSlots`,\n * and #1568's finality rule drops a NON-final splat before it becomes a slot.\n * So the rule is about FINALITY, not about levels: **a collision is admitted iff\n * one of the colliding bindings is a NON-final splat.** Measured, 8/8 — admitted:\n * `/p/*x/:x`, `/p/*x/*x`, and the cross-level `*`+`:` and `*`+`*` (an ancestor's\n * marker is never final, since a descendant path follows it); refused:\n * `/p/:x/*x`, `/z/:x/:x`, and the cross-level `:`+`*` and `:`+`:`. The same cause\n * opens a door at the ROOT, which is an ancestor like any other:\n * `setRootPath(\"/app/:x\")` + a route `/:x/e` throws, `setRootPath(\"/app/*x\")` +\n * the same route registers. Nothing is bound twice in any of them (the dropped\n * splat binds nothing), and since #1975 the surviving `:x` takes the param\n * encoder, so they round-trip instead of needing a refusal.\n * Extracted so `validateRoutePath` stays within the cognitive-complexity budget.\n */\nfunction validateUniqueParamNames(\n urlParams: readonly string[],\n routeName: string,\n methodName: string,\n path: string,\n): void {\n const seen = new Set<string>();\n\n for (const name of urlParams) {\n if (seen.has(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": duplicate parameter name ':${name}' in \"${path}\" (a param name must be unique within a route — the second binding would overwrite the first)`,\n );\n }\n\n seen.add(name);\n }\n}\n\n/**\n * #1242 §5.1/§5.3: rejects a malformed query-param declaration — a query name\n * carrying `<`/`>` (`/a?fil<ter` — a `<` in a plain query tail; never round-trips),\n * or one that collides with a path-param name (`/a/:tab?tab`, where buildPath emits\n * the value twice). Narrow to `<>`: a `=` in the declaration (`?tab=1`, §5.2) is\n * tolerated today and left as a separate call. (Under M1 a reverse-order typo\n * `/a/:b?<c>` is caught earlier as optional-removed — the `?<` keeps it in the\n * path, §3.3.) path-matcher's `registerTree` backstops both; this gate adds the\n * route-contextual message.\n */\nfunction validateQueryParamDeclarations(\n queryParams: readonly string[],\n routeName: string,\n methodName: string,\n path: string,\n): void {\n // A path/query name collision (`/a/:tab?tab`) is legal under M2: `tab` lives\n // in both `state.params` and `state.search` as separate channels (RFC-4 M2 /\n // #1548), so the former \"declared as both\" rejection is gone. Only a query\n // name that can never round-trip (contains `<`/`>`) is still rejected.\n for (const name of queryParams) {\n if (INVALID_QUERY_NAME_RGX.test(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": invalid query-param name \"${name}\" in \"${path}\" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`,\n );\n }\n }\n}\n\n/**\n * Reports whether a path has a raw non-ASCII code point (≥ U+0080) in a STATIC\n * segment (`/café`, `/меню`, #1154). match rejects any non-ASCII input byte\n * (`#scanPath`) and compares static trie keys raw, so such a route registers but\n * is unmatchable — `buildPath` emits `/café`, which its own `match` rejects. Only\n * static text is flagged: a marker-led segment (`:café`, a non-ASCII param NAME)\n * is skipped. A `for…of` code-point scan tracking segment start. Runs AFTER the\n * removed-form / grammar rejections, so no `<`/`>` (a former constraint) can\n * reach it — the 3-token grammar has no constraint body to skip (M1, #1516).\n */\nfunction hasNonAsciiStatic(path: string): boolean {\n let atSegmentStart = true;\n let segmentIsMarker = false;\n\n for (const char of path) {\n if (char === \"/\") {\n atSegmentStart = true;\n\n continue;\n }\n\n if (atSegmentStart) {\n segmentIsMarker = char === \":\" || char === \"*\";\n atSegmentStart = false;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- non-empty code point from for-of\n if (!segmentIsMarker && char.codePointAt(0)! >= 0x80) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Maps a SURVIVING per-segment grammar error code (from `findSegmentGrammarError`)\n * to the gate's route-contextual message. The removed-form codes (`optional-removed`\n * / `constraint-removed`) are NOT handled here — they carry a richer replacement\n * recipe built by `removedFormMessage` from `describeRemovedForm`.\n */\nfunction gateGrammarMessage(\n code: Exclude<SegmentErrorCode, \"optional-removed\" | \"constraint-removed\">,\n routeName: string,\n path: string,\n): string {\n switch (code) {\n case \"name-less\":\n case \"trailing-marker\": {\n return `Invalid path for route \"${routeName}\": parameter marker (':' or '*') without a name in \"${path}\"`;\n }\n case \"fused-marker\": {\n return `Invalid path for route \"${routeName}\": parameter marker (':' or '*') must begin a segment, but \"${path}\" fuses one to a static prefix (use a boundary marker like \"/a/:b\")`;\n }\n }\n}\n\n/**\n * Builds the route-contextual replacement recipe for a removed form (M1) — the\n * RICH tier (the matcher backstop uses a shorter, path-free recipe). For an\n * optional it names the offending segment and the two concrete sibling paths that\n * replace it (computed from the actual path by `describeRemovedForm`); for a\n * constraint it names the offending segment and points to a guard.\n */\nfunction removedFormMessage(removed: RemovedForm, routeName: string): string {\n if (removed.code === \"optional-removed\") {\n return `Invalid path for route \"${routeName}\": optional params are not supported — \"${removed.segment}\". Declare two sibling routes instead: \"${removed.withoutSegment}\" and \"${removed.requiredForm}\" (the route hierarchy already expresses optionality)`;\n }\n\n return `Invalid path for route \"${routeName}\": regex constraints are not supported — '<' and '>' are reserved in path segments (\"${removed.segment}\"). Match the segment as a plain string and validate the value in a guard (canActivate) or app code`;\n}\n\n/**\n * Validates route path format.\n * Throws a descriptive error if validation fails.\n *\n * Allows:\n * - Empty string (for grouping/root routes)\n * - Absolute paths: /path, ~path\n * - Query strings: ?query\n * - Relative segments: segment\n *\n * Prevents:\n * - Non-string values\n * - Double slashes (//)\n * - Absolute paths (~) under parameterized parent nodes\n *\n * @param path - Route path to validate\n * @param routeName - Name of route (for error messages)\n * @param methodName - Name of calling method for error messages\n * @param parentNode - Optional parent node for context validation\n * @throws {TypeError} If path is invalid\n *\n * @example\n * // Valid paths\n * validateRoutePath(\"\", \"home\", \"add\"); // ok (empty for grouping)\n * validateRoutePath(\"/users\", \"users\", \"add\"); // ok (absolute)\n * validateRoutePath(\"~dashboard\", \"dash\", \"add\"); // ok (absolute, if no parameterized parent)\n * validateRoutePath(\"?tab=1\", \"home\", \"add\"); // ok (query)\n * validateRoutePath(\"profile\", \"users.profile\", \"add\"); // ok (relative)\n *\n * @example\n * // Invalid paths (throws)\n * validateRoutePath(\"/users//list\", \"users.list\", \"add\"); // throws (double slash)\n * validateRoutePath(\"~dash\", \"dash\", \"add\", paramParent); // throws (~ under parameterized parent)\n */\n// A format-validation gate: a flat sequence of INDEPENDENT guard clauses (type,\n// whitespace, format, double-slash, dup-param, query-decl, the M1 removed-form\n// recipe, surviving grammar markers (name-less / fused / trailing), non-ASCII\n// static, absolute-under-param). Each is a simple early throw; extracting them\n// would only scatter one checklist.\n\nexport function validateRoutePath(\n path: unknown,\n routeName: string,\n methodName: string,\n parentNode?: RouteTree,\n): asserts path is string {\n // Type check\n if (typeof path !== \"string\") {\n // Get type description for error message\n let typeDesc: string;\n\n if (path === null) {\n typeDesc = \"null\";\n } else if (Array.isArray(path)) {\n typeDesc = \"array\";\n } else {\n typeDesc = typeof path;\n }\n\n throw createRouterError(\n methodName,\n `Route path must be a string, got ${typeDesc}`,\n );\n }\n\n // Empty path is valid (for grouping/root)\n if (path === \"\") {\n return;\n }\n\n // No whitespace characters (spaces, tabs, newlines)\n if (/\\s/.test(path)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": whitespace not allowed in \"${path}\"`,\n );\n }\n\n // Valid path pattern\n if (!/^([/?~]|[^/]+$)/.test(path)) {\n throw createRouterError(\n methodName,\n `Route \"${routeName}\" has invalid path format: \"${path}\". Path should start with '/', '~', '?' or be a relative segment.`,\n );\n }\n\n // No double slashes\n if (path.includes(\"//\")) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": double slashes not allowed in \"${path}\"`,\n );\n }\n\n // The grammar checks below scan only the URL-path portion: `buildParamMeta`\n // strips the query the same way the trie does, so a `:`/`*` inside a query\n // declaration is not falsely flagged. (`buildParamMeta` is total — the 3-token\n // grammar has no constraint body to compile, so it never throws — M1, #1516.)\n const { pathPattern, urlParams, queryParams } = buildParamMeta(path);\n\n // Duplicate param name within this route's own path (`/:id/:id`, `/:x/*x`, #1151).\n validateUniqueParamNames(urlParams, routeName, methodName, path);\n\n // Malformed query-param declarations (#1242 §5.1): a query name with `<>`\n // (never round-trips). Name collisions with a path param are legal under M2\n // (separate params/search channels, #1548).\n validateQueryParamDeclarations(queryParams, routeName, methodName, path);\n\n // Removed-form (M1) rejection first — a `:x?` optional or a `<re>` constraint —\n // with the RICH route-contextual replacement recipe (the offending segment plus,\n // for an optional, the two computed sibling paths). Returns undefined when the\n // path's first grammar error is a SURVIVING code, so the fall-through below runs.\n const removed = describeRemovedForm(pathPattern);\n\n if (removed !== undefined) {\n throw createRouterError(methodName, removedFormMessage(removed, routeName));\n }\n\n // Surviving per-segment grammar rejections via the canonical `parseSegment`\n // tokenizer: name-less (#858/#863), fused-marker (#1050), trailing-marker\n // (#1324). `findSegmentGrammarError` runs the same split+parse the matcher uses,\n // so the gate cannot drift. (Only removed-form codes reach `removed` above; the\n // first error here is therefore always a surviving code.)\n const grammarError = findSegmentGrammarError(pathPattern);\n\n if (grammarError !== undefined) {\n throw createRouterError(\n methodName,\n gateGrammarMessage(\n grammarError as Exclude<\n SegmentErrorCode,\n \"optional-removed\" | \"constraint-removed\"\n >,\n routeName,\n path,\n ),\n );\n }\n\n // Raw non-ASCII in a STATIC segment (`/café`, `/меню`, #1154). match rejects\n // non-ASCII input and compares static keys raw, so the route registers but never\n // matches. Reject with the percent-encode workaround (path-matcher backstops at\n // `registerTree`); a non-ASCII param NAME or constraint body is unaffected.\n if (hasNonAsciiStatic(pathPattern)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": non-ASCII static segment in \"${path}\" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`,\n );\n }\n\n // Absolute paths under parameterized parents\n // Check if parent has URL parameters via paramTypeMap\n const hasUrlParams = parentNode && parentNode.paramMeta.urlParams.length > 0;\n\n if (path.startsWith(\"~\") && hasUrlParams) {\n throw createRouterError(\n methodName,\n `Absolute path \"${path}\" cannot be used under parent route with URL parameters`,\n );\n }\n}\n","/**\n * Batch route validation utilities.\n *\n * Provides validation for adding routes with cross-batch duplicate detection.\n * Used by router.addRoute() to ensure atomicity - all routes validated before any modification.\n */\n\nimport {\n assertNoDottedRouteName,\n assertRouteNameMatchesPattern,\n assertRouteNameNotEmpty,\n assertRouteNameNotWhitespaceOnly,\n assertRouteNameWithinLength,\n} from \"./route-name\";\nimport { validateRoutePath } from \"./routes\";\nimport { raiser } from \"../../RouterError\";\n\nimport type { RouteDefinition, RouteTree } from \"../types\";\n\n/**\n * Intrinsics captured at module load: `getOwnPropertyDescriptor`, `objectKeys`, `getPrototypeOf`.\n *\n * ⚑ A guard is only as strong as the intrinsic it reads WHEN IT RUNS, and an\n * application can re-point any of these AFTER boot — which is what this closes.\n * Measured on the uncaptured form: one naive `Object.hasOwn` polyfill walked\n * straight through five sibling readers while the single captured guard held.\n *\n * ⚠ The limit of what capture buys — and the shim order that defeats it — is\n * stated once, in `guards.ts`. Not restated here (#2091).\n */\nconst getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nconst objectKeys = Object.keys;\nconst getPrototypeOf = Object.getPrototypeOf;\n\n/**\n * Gets a human-readable description of a value's type.\n * Used for error messages to provide helpful debugging information.\n */\nfunction getTypeDescription(value: unknown): string {\n // Handle null explicitly (typeof null === \"object\")\n if (value === null) {\n return \"null\";\n }\n\n if (typeof value === \"object\") {\n // Read `constructor`/`.name` defensively: an adversarial own `constructor`\n // (null, a string, a number, …) is not a real constructor and must not crash\n // here nor yield a non-string (#903); a THROWING accessor — a `constructor`\n // getter, a function constructor with a throwing `.name` getter, or a Proxy\n // that throws on [[Get]] — must not crash either (#1052); and a `name` that\n // is not a string describes nothing, because the description lands in a\n // message. All of them fall back to \"object\". (The engine cannot depend on\n // validation-plugin, which keeps its own copy with an `array[N]` branch.)\n try {\n const ctor: unknown = (value as { constructor?: unknown }).constructor;\n\n if (typeof ctor === \"function\") {\n const name: unknown = ctor.name;\n\n // Return constructor name for class instances; an anonymous class has\n // an empty one.\n if (typeof name === \"string\" && name !== \"\" && name !== \"Object\") {\n return name;\n }\n }\n } catch {\n // Throwing constructor/.name getter or Proxy [[Get]] → fall through (#1052).\n }\n\n // Plain object\n return \"object\";\n }\n\n // Primitive types (string, number, boolean, undefined, etc.)\n return typeof value;\n}\n\n/**\n * Checks if an object has getters or setters.\n * Used to detect potentially malicious route objects that could mutate during processing.\n *\n * @param obj - Object to check\n * @returns true if object has getters or setters\n */\nfunction hasGettersOrSetters(obj: Record<string, unknown>): boolean {\n for (const key of objectKeys(obj)) {\n const descriptor = getOwnPropertyDescriptor(obj, key);\n\n if (descriptor && (descriptor.get || descriptor.set)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Validates that route is a plain object without getters/setters.\n * Prevents malicious objects that could mutate during processing.\n *\n * ⚑ Every question here is about the OBJECT — its type, its prototype, its\n * descriptors — never about a value it carries, and that is what decides WHERE\n * it may run (#1911). A snapshot answers all three the same way whatever the\n * caller handed over, because a spread produces a plain, accessor-free object.\n * So this has to see the CALLER's value, which is why `guardRouteStructure`\n * calls it above `snapshotRouteBatch` on every registration door.\n *\n * @param route - Route to validate\n * @param methodName - Calling method for error context\n * @throws {TypeError} If route is not a plain object\n */\nexport function validateRouteType(\n route: unknown,\n methodName: string,\n): asserts route is Record<string, unknown> {\n if (!route || typeof route !== \"object\") {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route must be an object, got ${getTypeDescription(route)}`;\n }\n\n // Check for plain object (prototype must be Object.prototype or null)\n const proto: object | null = getPrototypeOf(route) as object | null;\n\n if (proto !== Object.prototype && proto !== null) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route must be a plain object, got ${getTypeDescription(route)}`;\n }\n\n // Check for getters/setters (could cause mutations during processing)\n if (hasGettersOrSetters(route as Record<string, unknown>)) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route must not have getters or setters`;\n }\n}\n\n/**\n * Refuses a route codec — `encodeParams` / `decodeParams` — that is not a\n * function.\n *\n * Both layers call it, and each decides which values count as absent:\n * {@link validateRoute} passes every value but `undefined`, bare-core\n * registration (`namespaces/RoutesNamespace/routesStore.ts`) only a truthy one,\n * because core drops a falsy structural field (#1797). The message has one\n * owner, as in `./route-name` (#2035).\n */\nexport function assertRouteCodecIsFunction(\n field: \"decodeParams\" | \"encodeParams\",\n codec: unknown,\n routeName: string,\n methodName: string | undefined,\n): void {\n if (typeof codec !== \"function\") {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route \"${routeName}\" ${field} must be a function`;\n }\n}\n\n/** {@link assertRouteCodecIsFunction} on a codec the definition provides. */\nfunction validateCodec(\n field: \"decodeParams\" | \"encodeParams\",\n codec: unknown,\n fullName: string,\n methodName: string,\n): void {\n if (codec !== undefined) {\n assertRouteCodecIsFunction(field, codec, fullName, methodName);\n }\n}\n\n/**\n * Validates that route name is a valid string matching the expected format.\n *\n * Route name rules:\n * - Must be a string\n * - Cannot be empty or whitespace-only\n * - Cannot contain dots (use children array or { parent } option instead)\n * - Must match [a-zA-Z_][a-zA-Z0-9_-]*\n *\n * ⚠ The string check stays inline rather than joining `./route-name`: core\n * carries two wordings for it — this one reports `getTypeDescription`, and\n * `assertNoInternalRouteName` reports bare `typeof` to mirror the plugin — so\n * sharing one predicate would change a message rather than move it.\n *\n * @param route - Route configuration\n * @param methodName - Calling method for error context\n * @throws {TypeError} If name is missing, not a string, or invalid format\n */\nfunction validateRouteName(\n route: Record<string, unknown>,\n methodName: string,\n): asserts route is Record<string, unknown> & { name: string } {\n if (typeof route.name !== \"string\") {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route name must be a string, got ${getTypeDescription(route.name)}`;\n }\n\n const name = route.name;\n\n assertRouteNameNotEmpty(name, methodName);\n assertRouteNameNotWhitespaceOnly(name, methodName);\n assertRouteNameWithinLength(name, methodName);\n\n // System routes bypass the spelling rules (e.g., @@router/UNKNOWN_ROUTE).\n if (name.startsWith(\"@@\")) {\n return;\n }\n\n assertNoDottedRouteName(name, methodName);\n assertRouteNameMatchesPattern(name, methodName);\n}\n\n/**\n * Finds a node by its fullName in the tree.\n * Even though user-provided route names cannot contain dots,\n * fullName is computed during validation (e.g., \"parent.child\").\n *\n * @param rootNode - Root node to start from\n * @param fullName - Full route name (e.g., \"users.profile\")\n * @returns The resolved node, or undefined if not found\n */\nfunction findNodeByFullName(\n rootNode: RouteTree,\n fullName: string,\n): RouteTree | undefined {\n // Fast path: single-segment names don't need splitting\n // Stryker disable next-line ConditionalExpression,StringLiteral,BlockStatement: equivalent — the fast path is a pure optimization; for a dotless name the general path below yields the identical result (`name.split(\".\")` → `[name]`, a one-iteration `children.get(name)`). (BooleanLiteral stays live: dropping the `!` runs the fast path for a dotted name → `children.get(\"a.b\")` is undefined = killed.)\n if (!fullName.includes(\".\")) {\n return rootNode.children.get(fullName);\n }\n\n let current: RouteTree | undefined = rootNode;\n\n for (const segment of fullName.split(\".\")) {\n current = current.children.get(segment);\n\n if (!current) {\n return undefined;\n }\n }\n\n return current;\n}\n\n/**\n * Checks for duplicate route name in existing tree.\n *\n * @param rootNode - Root node to search in\n * @param fullName - Full route name (dot-notation)\n * @param methodName - Calling method for error context\n * @throws {Error} If route name already exists\n */\nfunction checkTreeNameDuplicate(\n rootNode: RouteTree,\n fullName: string,\n methodName: string,\n): void {\n if (findNodeByFullName(rootNode, fullName)) {\n const at = raiser(\"router\", methodName);\n\n throw at.plain`Route \"${fullName}\" already exists`;\n }\n}\n\n/**\n * Checks for duplicate route name in current batch.\n *\n * @param seenNames - Set of names already seen in batch\n * @param fullName - Full route name to check\n * @param methodName - Calling method for error context\n * @throws {Error} If duplicate name in batch\n */\nfunction checkBatchNameDuplicate(\n seenNames: Set<string>,\n fullName: string,\n methodName: string,\n): void {\n if (seenNames.has(fullName)) {\n const at = raiser(\"router\", methodName);\n\n throw at.plain`Duplicate route \"${fullName}\" in batch`;\n }\n\n seenNames.add(fullName);\n}\n\n/**\n * Checks for duplicate path in existing tree at same parent level.\n *\n * @param rootNode - Root node to search in\n * @param parentName - Parent route name (empty string for root level)\n * @param routePath - Path to check for duplicates\n * @throws {Error} If path already exists at this level\n */\nfunction checkTreePathDuplicate(\n rootNode: RouteTree,\n parentName: string,\n routePath: string,\n methodName: string,\n): void {\n const parentNode =\n parentName === \"\" ? rootNode : findNodeByFullName(rootNode, parentName);\n\n if (!parentNode) {\n return; // Parent doesn't exist, so no duplicate\n }\n\n for (const child of parentNode.children.values()) {\n if (child.path === routePath) {\n const at = raiser(\"router\", methodName);\n\n throw at.plain`Path \"${routePath}\" is already defined`;\n }\n }\n}\n\n/**\n * Checks for duplicate path in current batch at same parent level.\n *\n * @param seenPathsByParent - Map of paths by parent name\n * @param parentName - Parent route name (empty string for root level)\n * @param routePath - Path to check for duplicates\n * @throws {Error} If path already exists at this level in batch\n */\nfunction checkBatchPathDuplicate(\n seenPathsByParent: Map<string, Set<string>>,\n parentName: string,\n routePath: string,\n methodName: string,\n): void {\n const pathsAtLevel = seenPathsByParent.get(parentName);\n\n if (pathsAtLevel?.has(routePath)) {\n const at = raiser(\"router\", methodName);\n\n throw at.plain`Path \"${routePath}\" is already defined`;\n }\n\n if (pathsAtLevel) {\n pathsAtLevel.add(routePath);\n } else {\n seenPathsByParent.set(parentName, new Set([routePath]));\n }\n}\n\n/**\n * Validates route structure for add operations.\n *\n * Performs comprehensive validation including:\n * - Type check (must be object)\n * - Name validation\n * - Path validation\n * - Duplicate name detection (in tree and batch)\n * - Duplicate path detection (in tree and batch)\n * - Recursive children validation\n *\n * @param route - Route to validate\n * @param methodName - Calling method for error context\n * @param rootNode - Optional root node for duplicate checking\n * @param parentName - Parent route name for building full path (used in recursion)\n * @param seenNames - Set of names already seen in this batch\n * @param seenPathsByParent - Map of paths by parent for path duplicate detection\n * @throws {TypeError} If route structure is invalid\n * @throws {Error} If route already exists (duplicate)\n * @throws {Error} If path already defined (duplicate)\n *\n * @example\n * ```typescript\n * const seenNames = new Set<string>();\n * const seenPaths = new Map<string, Set<string>>();\n *\n * // Validate routes before adding\n * for (const route of routes) {\n * validateRoute(route, \"add\", rootNode, \"\", seenNames, seenPaths);\n * }\n * ```\n */\nexport function validateRoute(\n route: unknown,\n methodName: string,\n rootNode?: RouteTree,\n parentName = \"\",\n seenNames?: Set<string>,\n seenPathsByParent?: Map<string, Set<string>>,\n): asserts route is RouteDefinition {\n validateRouteType(route, methodName);\n\n const routeDef = route;\n\n // Validate that name is a non-empty string\n validateRouteName(routeDef, methodName);\n\n // Validate path structure\n validateRoutePath(routeDef.path, routeDef.name, methodName, rootNode);\n\n const routeName = routeDef.name;\n const fullName = parentName ? `${parentName}.${routeName}` : routeName;\n\n // Validate optional function properties, naming the route in full as core does\n validateCodec(\"encodeParams\", routeDef.encodeParams, fullName, methodName);\n validateCodec(\"decodeParams\", routeDef.decodeParams, fullName, methodName);\n\n // Check for duplicate name in existing tree\n if (rootNode && fullName) {\n checkTreeNameDuplicate(rootNode, fullName, methodName);\n }\n\n // Check for duplicate name in current batch\n if (seenNames) {\n checkBatchNameDuplicate(seenNames, fullName, methodName);\n }\n\n const routePath = routeDef.path;\n const pathCheckParent = parentName;\n\n // Check for duplicate path in existing tree\n if (rootNode) {\n checkTreePathDuplicate(rootNode, pathCheckParent, routePath, methodName);\n }\n\n // Check for duplicate path in current batch\n if (seenPathsByParent) {\n checkBatchPathDuplicate(\n seenPathsByParent,\n pathCheckParent,\n routePath,\n methodName,\n );\n }\n\n // Validate children recursively\n if (routeDef.children !== undefined) {\n if (!Array.isArray(routeDef.children)) {\n const at = raiser(\"router\", methodName);\n\n throw at.type`Route \"${routeName}\" children must be an array, got ${getTypeDescription(routeDef.children)}`;\n }\n\n for (const child of routeDef.children) {\n validateRoute(\n child,\n methodName,\n rootNode,\n fullName,\n seenNames,\n seenPathsByParent,\n );\n }\n }\n}\n"],"mappings":"A,gEAiBA,MAAMA,EAAS,OAAO,OAwBtB,SAAgBc,EACdC,EACAC,EACoB,CAWpB,GAAIA,EAAW,SAAW,GAAKD,GAAU,KAIzC,IAAK,IAAME,KAAOD,EAAY,CAC5B,GAAI,CAAChB,E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cA,EAG7DuK,EAAc,eAAgBiB,EAAS,aAAchB,EAAUpC,CAAU,EACzEmC,EAAc,eAAgBiB,EAAS,aAAchB,EAAUpC,CAAU,EAGrEuC,GAAYH,GACdK,GAAuBF,EAAUH,EAAUpC,CAAU,EAInD2C,GACFD,GAAwBC,EAAWP,EAAUpC,CAAU,EAGzD,IAAM8C,EAAYM,EAAS,KACrBC,EAAkBR,EAkBxB,GAfIN,GACFK,GAAuBL,EAAUc,EAAiBP,EAAW9C,CAAU,EAIrEiD,GACFD,GACEC,EACAI,EACAP,EACA9C,CACF,EAIEoD,EAAS,WAAa,IAAA,GAAW,CACnC,GAAI,CAAC,MAAM,QAAQA,EAAS,QAAQ,EAGlC,KAFWpM,GAAO,SAAUgJ,CAErB,CAAC,CAAC,IAAI,UAAUpI,EAAU,mCAAmC6J,EAAmB2B,EAAS,QAAQ,IAG1G,IAAK,IAAML,KAASK,EAAS,SAC3BD,EACEJ,EACA/C,EACAuC,EACAH,EACAO,EACAM,CACF,CAEJ,CACF,C"}
@@ -1 +1 @@
1
- import{c as e,n as t,p as n,v as r}from"./route-batch-BHxxucx6.mjs";import{a as i}from"./helpers-LeSZEDaV.mjs";export{i as areParamValuesEqual,n as buildParamMeta,r as findMisChanneledKey,e as printsNoQueryKey,t as validateRoute};
1
+ import{c as e,n as t,p as n,v as r}from"./route-batch-LdEAJqGb.mjs";import{a as i}from"./helpers-LeSZEDaV.mjs";export{i as areParamValuesEqual,n as buildParamMeta,r as findMisChanneledKey,e as printsNoQueryKey,t as validateRoute};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/core",
3
- "version": "0.173.0",
3
+ "version": "0.173.1",
4
4
  "type": "commonjs",
5
5
  "description": "A simple, powerful, view-agnostic, modular and extensible router",
6
6
  "main": "./dist/cjs/index.js",