@real-router/core 0.111.2 → 0.111.4
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/cjs/Router-CUtRu_zV.js +2 -0
- package/dist/cjs/Router-CUtRu_zV.js.map +1 -0
- package/dist/cjs/Router.d.ts.map +1 -1
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/buildParamMeta-C9Hfrxr9.js +2 -0
- package/dist/cjs/{buildParamMeta-CG-WYPDp.js.map → buildParamMeta-C9Hfrxr9.js.map} +1 -1
- package/dist/cjs/constants.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/ingest-DxGcWzr6.js.map +1 -1
- package/dist/cjs/validation.js +1 -1
- package/dist/esm/Router-CGE4ZJm6.mjs +2 -0
- package/dist/esm/Router-CGE4ZJm6.mjs.map +1 -0
- package/dist/esm/Router.d.mts.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/buildParamMeta-Bm3gpEuW.mjs +2 -0
- package/dist/esm/{buildParamMeta-BCzlczgt.mjs.map → buildParamMeta-Bm3gpEuW.mjs.map} +1 -1
- package/dist/esm/constants.d.mts.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/ingest-Wemkuwfp.mjs.map +1 -1
- package/dist/esm/validation.mjs +1 -1
- package/package.json +1 -1
- package/dist/cjs/Router-CXthrgGA.js +0 -2
- package/dist/cjs/Router-CXthrgGA.js.map +0 -1
- package/dist/cjs/buildParamMeta-CG-WYPDp.js +0 -2
- package/dist/esm/Router-iEz9SYH6.mjs +0 -2
- package/dist/esm/Router-iEz9SYH6.mjs.map +0 -1
- package/dist/esm/buildParamMeta-BCzlczgt.mjs +0 -2
package/dist/cjs/Router.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Router.d.ts","names":[],"sources":["../../src/Router.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;cAkFa,OACX,qBAAqB,sBAAsB,gCAChC,SAAgB;;GAC1B;;;;;;EA4CC,YAAA,SAAQ,MAAM,iBACd,UAAS,QAAQ,QAAQ,gBACzB,eAAc;
|
|
1
|
+
{"version":3,"file":"Router.d.ts","names":[],"sources":["../../src/Router.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;cAkFa,OACX,qBAAqB,sBAAsB,gCAChC,SAAgB;;GAC1B;;;;;;EA4CC,YAAA,SAAQ,MAAM,iBACd,UAAS,QAAQ,QAAQ,gBACzB,eAAc;EAggBhB,cACE,cACA,SAAS,QACT,SAAS,cACT,0BACA;EAmCF,UAAU,eAAe,SAAS,QAAQ,SAAS;EA6BnD,SAAS,UAAU,SAAS,WAAW,MAAM;EAI7C,oBAAoB;EAIpB,eACE,QAAQ,mBACR,QAAQ,mBACR;EAWF,iBACE,oBACE,SAAS,OAAO,YAAY;EAYhC;;;;;;;;;;;;;;EAiBA,MAAM,oBAAoB,QAAQ;EAQlC;EAyBA;EAoDA,cAAc,cAAc,SAAS,QAAQ,SAAS;EAoItD,aACK,UAAU,cAAc,8CAC1B;EAyCH,UAAU,UAAU,cAAc;EAMlC,eAAe,UAAU,UAAU;EAMnC;EAQA,SACE,QAAQ,kBACR,UAAU,oBACT,QAAQ;EACX,SACE,mBACA,cAAc,QACd,cAAc,cACd,UAAU,oBACT,QAAQ;EAqDX,kBAAkB,UAAU,oBAAoB,QAAQ;EAiBxD,mBAAmB,gBAAgB"}
|
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./buildParamMeta-CG-WYPDp.js"),t=require("./ingest-DxGcWzr6.js"),n=require("./Router-CXthrgGA.js");function r(e){if(e())throw n.r(new n.n(t.m.ROUTER_DISPOSED))}function i(e){if(e())throw n.r(new n.n(t.m.REENTRANT_TREE_MUTATION,{message:`[router] 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.`}))}function a(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 o(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. The rejected navigate() promise carries "CANCELLED" while the guard walk is synchronous and "ROUTE_NOT_FOUND" once it has gone async; onTransitionError always reports "ROUTE_NOT_FOUND", and onTransitionCancel never fires. The committed state is not affected either way.`)}function s(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function c(e,t,n,r){return n&&s(e)!==s(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}function l(e,t){return e?(t.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const u=Object.keys,d=new WeakMap;function f(a){let o=d.get(a);if(o)return o;let s=e.u(a),l={makeState:(t,n,r,i)=>(e.f(s,`makeState`,t,n),s.validator?.state.validateMakeStateArgs(t,n,i),s.makeState(t,n,r,i)),forwardState:(e,t,n)=>(s.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),s.forwardState(e,t,n)),matchPath:e=>(s.validator?.routes.validateMatchPathArgs(e),s.matchPath(e,s.getOptions())),navigateToState:(e,t)=>(r(s.isDisposed),s.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&s.validator?.navigation.validateNavigationOptions(t,`navigateToState`),s.navigateToState(e,t)),setRootPath:e=>(r(s.isDisposed),i(s.treeChanged.isEmitting),s.validator?.routes.validateSetRootPathArgs(e),c(s.getRootPath(),e,s.isTransitioning(),s.logger)?(s.setRootPath(e),!0):!1),getRootPath:s.getRootPath,addEventListener:(e,t)=>(r(s.isDisposed),s.validator?.eventBus.validateListenerArgs(e,t),s.addEventListener(e,t)),buildNavigationState:(t,r={},i={})=>{e.f(s,`buildNavigationState`,t,r),s.validator?.routes.validateStateBuilderArgs(t,r,`buildNavigationState`);let a=n.D(s.port(),t,r,i,{diagnoseUndeclared:!0});if(s.buildStateResolved(a.name,a.path))return e.m(`buildNavigationState`,a.name,a.path,s.port().queryNames(a.name)),n.T(a,n.E(a,s.port()))},getOptions:s.getOptions,getTree:s.getTree,addInterceptor:(e,t)=>{r(s.isDisposed),s.validator?.plugins.validateAddInterceptorArgs(e,t);let n=s.interceptors.get(e);n||(n=[],s.interceptors.set(e,n)),n.push(t);let i=!1;return()=>{i||(i=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=s.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:e=>{r(s.isDisposed);let i=u(e);for(let e of i)if(e in a)throw n.r(new n.n(t.m.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${e}" already exists`}));for(let t of i)a[t]=e[t];let o={keys:i};s.routerExtensions.push(o);let c=!1;return()=>{if(c)return;c=!0;for(let e of o.keys)delete a[e];let e=s.routerExtensions.indexOf(o);e!==-1&&s.routerExtensions.splice(e,1)}},emitTransitionError:e=>{r(s.isDisposed),s.emitTransitionError(e)},claimContextNamespace:e=>{if(r(s.isDisposed),typeof e!=`string`||e===``)throw TypeError(`[claimContextNamespace] namespace must be a non-empty string, got ${typeof e==`string`?`an empty string`:typeof e}`);if(s.contextClaimRecords.has(e))throw n.r(new n.n(t.m.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${e}" is already claimed by another plugin`}));return s.contextClaimRecords.add(e),{write(n,r){t.a(n.context,e,r)},release(){s.contextClaimRecords.delete(e)}}}};return d.set(a,l),l}const p=Object.keys,m=Object.freeze({replace:!0,revalidate:!0}),h=Object.freeze([]);function g(e,t,r,i){let a=t=>e.has(t);n.C(t.decoders,a),n.C(t.encoders,a),n.C(t.defaultParams,a),n.C(t.defaultSearch,a),n.C(t.forwardMap,a),n.C(t.forwardFnMap,a),n.C(r,a),n.C(t.forwardMap,e=>a(t.forwardMap[e]));let[o,s]=i.getFactories();for(let e of p(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of p(o))a(e)&&i.clearCanDeactivate(e,`both`)}function _(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 v(e,t,n,r){let i={name:e.name,path:e.path};return _(i,t,n,r),e.children&&(i.children=e.children.map(e=>v(e,`${t}.${e.name}`,n,r))),i}function y(e,t,n,r){let i={name:e,path:t};return _(i,e,n,r),Object.freeze(i)}function b(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,y(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function x(e,t){let n=b(e,e=>t.has(e));return Object.freeze([...n.values()])}function S(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(y(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function C(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:Object.freeze(n),added:Object.freeze(r)}}function w(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),Object.freeze(t)}function T(e,t,r,i){let a=n.y(t);n.s(e,a,r);let o=n.p(e,a,r,i);n.x(o.matcher,o.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!1),n.o(e,o)}function E(e,t){return e.matcher.match(t)?.segments.at(-1)?.fullName}function D(e,t,n,r,i){if(E(e,r.path)!==i){t.revalidateToNotFound(r.path);return}t.systemCommit(n,r,m)}function O(e,t,r,i,a){let o=n.y(t);n.d(o,`addRoute`),n.c(o,`addRoute`),n.l(o,``,`addRoute`),n.u(o,``,`addRoute`);let s=n.m(o,e.rootPath,e.matcherOptions,r.logger);n.x(s.matcher,s.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(s.pendingCanActivate.keys(),s.pendingCanDeactivate.keys(),!0);let c=n._(s,e.depsStore);if(e.lifecycleNamespace.clearDefinitionGuards(),n.o(e,s,c),a?.(),i!==void 0){let t=E(e,i.path),a=r.matchPath(i.path,r.getOptions());if(a)if(a.name===i.name)D(e,r,{...a,context:i.context,transition:i.transition},i,t);else{let{toActivate:o}=n.i(a,i,r.getMetaForState);e.lifecycleNamespace.canNavigateTo([],o,a,i)?D(e,r,{...a,transition:i.transition},i,t):r.revalidateToNotFound(i.path)}else r.revalidateToNotFound(i.path)}}function k(e,t,r){let i=e.definitions,a=n.w(i,t);if(a===void 0)return;let o=r?x(e,a):h;return g(a,e.config,e.routeCustomFields,e.lifecycleNamespace),n.g(e,i),o}function A(e,t){let r=e.matcher.getSegmentsByName(t);if(!r)return;let i=n.O(r.at(-1)),a=e.lifecycleNamespace.getFactories();return v(i,t,e.config,a)}const j=new WeakMap;function M(s){let c=j.get(s);if(c)return c;let u=e.u(s),d=u.routeGetStore(),f=e=>{u.treeChanged.emit(e)},m=Object.freeze({add:(e,t)=>{r(u.isDisposed),i(u.treeChanged.isEmitting);let a=Array.isArray(e)?e:[e],o=t?.parent;if(n.j(a,u.validator),o!==void 0&&u.validator?.routes.validateParentOption(o,d.tree),u.validator?.routes.throwIfInternalRouteInArray(a,`addRoute`),u.validator?.routes.validateAddRouteArgs(a),u.validator?.routes.validateRoutes(a,d,o),T(d,a,o,u.logger),u.treeChanged.listenerCount()>0){let e=S(a,o,d);f(o===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:o})}},remove:e=>{if(r(u.isDisposed),i(u.treeChanged.isEmitting),u.validator?.routes.validateRemoveRouteArgs(e),u.validator?.routes.throwIfInternalRoute(e,`removeRoute`),n.f(e,`removeRoute`),!a(e,u.getStateName(),u.logger))return;let t=u.treeChanged.listenerCount()>0,s=k(d,e,t);if(s===void 0){u.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`);return}u.isTransitioning()&&o(e,u.logger),t&&f({op:`remove`,name:e,removedSubtree:s})},update:(e,t)=>{if(r(u.isDisposed),i(u.treeChanged.isEmitting),u.validator?.routes.validateUpdateRouteBasicArgs(e,t),u.validator?.routes.throwIfInternalRoute(e,`updateRoute`),n.f(e,`updateRoute`),u.validator?.routes.validateUpdateRoutePropertyTypes(e,t),u.validator?.routes.validateUpdateRoute(e,t,d),!d.matcher.hasRoute(e))return;u.isTransitioning()&&u.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`);let a=d.lifecycleNamespace,o=n.h(d,a,e,t);if(u.treeChanged.listenerCount()>0){let t=w(o);p(t).length>0&&f({op:`update`,name:e,patch:t})}},clear:()=>{if(r(u.isDisposed),i(u.treeChanged.isEmitting),u.getStateName()!==void 0)throw n.r(new n.n(t.m.ROUTER_NOT_STOPPED,{message:`[router.clear] Cannot clear routes while a state is committed. Use replace(routes) to swap the tree on a running router, or stop() first.`}));if(!l(u.isTransitioning(),u.logger))return;let e=u.treeChanged.listenerCount()>0?Object.freeze([...b(d,()=>!0).values()]):void 0;n.v(d),d.lifecycleNamespace.clearAll(),e!==void 0&&f({op:`clear`,removed:e})},has:e=>(u.validator?.routes.validateRouteName(e,`hasRoute`),d.matcher.hasRoute(e)),get:e=>(u.validator?.routes.validateRouteName(e,`getRoute`),A(d,e)),replace:e=>{r(u.isDisposed),i(u.treeChanged.isEmitting);let t=Array.isArray(e)?e:[e];if(!l(u.isTransitioning(),u.logger))return;n.j(t,u.validator),u.validator?.routes.throwIfInternalRouteInArray(t,`replaceRoutes`),u.validator?.routes.validateAddRouteArgs(t),u.validator?.routes.validateRoutes(t,d);let a=s.getState(),o=u.treeChanged.listenerCount()>0?b(d,()=>!0):void 0;O(d,t,u,a,o===void 0?void 0:()=>{let e=b(d,()=>!0),{removed:t,added:n}=C(o,e);f({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>u.treeChanged.subscribe(e)});return j.set(s,m),m}const N=Object.hasOwn,P=e=>typeof e==`symbol`?e:String(e);function F(e,t,n,r){if(n===void 0)return;let i=e.dependencies,a=P(t);if(!N(i,a))r?.dependencies.validateDependencyCount(e,`setDependency`);else{let e=i[a];e!==n&&!(Number.isNaN(e)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(String(a),`setDependency`)}i[a]=n}function I(e,t,r){let i=[],a=e.dependencies;n.M(t,(t,n)=>{N(a,t)?i.push(t):r?.dependencies.validateDependencyCount(e,`setDependencies`),a[t]=n}),i.length>0&&r?.dependencies.warnBatchOverwrite(i,`setDependencies`)}function L(t){let i=e.u(t);return{get:e=>{i.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=i.dependenciesGetStore(),n=t.dependencies[e];return i.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>{let e=i.dependenciesGetStore().dependencies;return n.A({...e})},set:(e,t)=>{r(i.isDisposed),i.validator?.dependencies.validateSetDependencyArgs(e,t,`setDependency`),F(i.dependenciesGetStore(),e,t,i.validator),r(i.isDisposed)},setAll:e=>{r(i.isDisposed);let t=i.dependenciesGetStore();i.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),I(t,e,i.validator),r(i.isDisposed)},remove:e=>{r(i.isDisposed),i.validator?.dependencies.validateDependencyName(e,`removeDependency`);let t=i.dependenciesGetStore(),n=P(e);N(t.dependencies,n)||i.validator?.dependencies.warnRemoveNonExistent(String(n)),delete t.dependencies[n]},reset:()=>{r(i.isDisposed);let e=i.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(i.validator?.dependencies.validateDependencyName(e,`hasDependency`),N(i.dependenciesGetStore().dependencies,e))}}function R(t){let n=e.u(t),i=n.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`addActivateGuard`),n.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t,!1)},addDeactivateGuard(e,t){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`addDeactivateGuard`),n.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t,!1)},removeActivateGuard(e){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}const z=Object.entries,B=Object.hasOwn,V=Object.keys;function H(r,i,a){let o=e.u(r);if(o.isDisposed())throw n.r(new n.n(t.m.ROUTER_DISPOSED));o.validator?.dependencies.validateCloneArgs(i);let s=o.routeGetStore(),c=n.k(s.tree),l=s.config,u=s.resolvedForwardMap,d=s.routeCustomFields,{options:f,dependencies:p,pluginFactories:m,loggerConfig:h,limits:g}=o.getCloneState(),{definition:_,external:v}=s.lifecycleNamespace.getFactoriesByOrigin(),y={...p};i!==void 0&&n.M(i,(e,n)=>{t.a(y,e,n)});let b=a?.logger?{...h,...a.logger}:h,x=new n.t(c,{...f,logger:b,...f.limits!=null&&{limits:Object.fromEntries(V(f.limits).filter(e=>B(g,e)).map(e=>[e,g[e]]))},...s.matcherOptions?.urlParamsEncoding!==void 0&&{urlParamsEncoding:s.matcherOptions.urlParamsEncoding}},y),S=e.u(x),C=S.routeGetStore(),w=C.lifecycleNamespace;n.S(C.config,l),n.a(C,Object.assign(C.resolvedForwardMap,u)),Object.assign(C.routeCustomFields,d),s.rootPath!==``&&S.setRootPath(s.rootPath);let[T,E]=_,[D,O]=v;for(let[e,t]of z(T))w.addCanDeactivate(e,t,!0);for(let[e,t]of z(E))w.addCanActivate(e,t,!0);let k=R(x);for(let[e,t]of z(D))k.addDeactivateGuard(e,t);for(let[e,t]of z(O))k.addActivateGuard(e,t);let A=new Set(S.getCloneState().pluginFactories),j=m.filter(e=>!A.has(e));return j.length>0&&x.usePlugin(...j),x}exports.cloneRouter=H,exports.getDependenciesApi=L,exports.getLifecycleApi=R,exports.getPluginApi=f,exports.getRoutesApi=M;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./buildParamMeta-C9Hfrxr9.js"),t=require("./ingest-DxGcWzr6.js"),n=require("./Router-CUtRu_zV.js");function r(e){if(e())throw n.r(new n.n(t.m.ROUTER_DISPOSED))}function i(e){if(e())throw n.r(new n.n(t.m.REENTRANT_TREE_MUTATION,{message:`[router] 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.`}))}function a(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 o(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. The rejected navigate() promise carries "CANCELLED" while the guard walk is synchronous and "ROUTE_NOT_FOUND" once it has gone async; onTransitionError always reports "ROUTE_NOT_FOUND", and onTransitionCancel never fires. The committed state is not affected either way.`)}function s(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function c(e,t,n,r){return n&&s(e)!==s(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}function l(e,t){return e?(t.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const u=Object.keys,d=new WeakMap;function f(a){let o=d.get(a);if(o)return o;let s=e.u(a),l={makeState:(t,n,r,i)=>(e.f(s,`makeState`,t,n),s.validator?.state.validateMakeStateArgs(t,n,i),s.makeState(t,n,r,i)),forwardState:(e,t,n)=>(s.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),s.forwardState(e,t,n)),matchPath:e=>(s.validator?.routes.validateMatchPathArgs(e),s.matchPath(e,s.getOptions())),navigateToState:(e,t)=>(r(s.isDisposed),s.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&s.validator?.navigation.validateNavigationOptions(t,`navigateToState`),s.navigateToState(e,t)),setRootPath:e=>(r(s.isDisposed),i(s.treeChanged.isEmitting),s.validator?.routes.validateSetRootPathArgs(e),c(s.getRootPath(),e,s.isTransitioning(),s.logger)?(s.setRootPath(e),!0):!1),getRootPath:s.getRootPath,addEventListener:(e,t)=>(r(s.isDisposed),s.validator?.eventBus.validateListenerArgs(e,t),s.addEventListener(e,t)),buildNavigationState:(t,r={},i={})=>{e.f(s,`buildNavigationState`,t,r),s.validator?.routes.validateStateBuilderArgs(t,r,`buildNavigationState`);let a=n.D(s.port(),t,r,i,{diagnoseUndeclared:!0});if(s.buildStateResolved(a.name,a.path))return e.m(`buildNavigationState`,a.name,a.path,s.port().queryNames(a.name)),n.T(a,n.E(a,s.port()))},getOptions:s.getOptions,getTree:s.getTree,addInterceptor:(e,t)=>{r(s.isDisposed),s.validator?.plugins.validateAddInterceptorArgs(e,t);let n=s.interceptors.get(e);n||(n=[],s.interceptors.set(e,n)),n.push(t);let i=!1;return()=>{i||(i=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=s.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:e=>{r(s.isDisposed);let i=u(e);for(let e of i)if(e in a)throw n.r(new n.n(t.m.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${e}" already exists`}));for(let t of i)a[t]=e[t];let o={keys:i};s.routerExtensions.push(o);let c=!1;return()=>{if(c)return;c=!0;for(let e of o.keys)delete a[e];let e=s.routerExtensions.indexOf(o);e!==-1&&s.routerExtensions.splice(e,1)}},emitTransitionError:e=>{r(s.isDisposed),s.emitTransitionError(e)},claimContextNamespace:e=>{if(r(s.isDisposed),typeof e!=`string`||e===``)throw TypeError(`[claimContextNamespace] namespace must be a non-empty string, got ${typeof e==`string`?`an empty string`:typeof e}`);if(s.contextClaimRecords.has(e))throw n.r(new n.n(t.m.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${e}" is already claimed by another plugin`}));return s.contextClaimRecords.add(e),{write(n,r){t.a(n.context,e,r)},release(){s.contextClaimRecords.delete(e)}}}};return d.set(a,l),l}const p=Object.keys,m=Object.freeze({replace:!0,revalidate:!0}),h=Object.freeze([]);function g(e,t,r,i){let a=t=>e.has(t);n.C(t.decoders,a),n.C(t.encoders,a),n.C(t.defaultParams,a),n.C(t.defaultSearch,a),n.C(t.forwardMap,a),n.C(t.forwardFnMap,a),n.C(r,a),n.C(t.forwardMap,e=>a(t.forwardMap[e]));let[o,s]=i.getFactories();for(let e of p(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of p(o))a(e)&&i.clearCanDeactivate(e,`both`)}function _(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 v(e,t,n,r){let i={name:e.name,path:e.path};return _(i,t,n,r),e.children&&(i.children=e.children.map(e=>v(e,`${t}.${e.name}`,n,r))),i}function y(e,t,n,r){let i={name:e,path:t};return _(i,e,n,r),Object.freeze(i)}function b(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,y(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function x(e,t){let n=b(e,e=>t.has(e));return Object.freeze([...n.values()])}function S(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(y(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function C(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:Object.freeze(n),added:Object.freeze(r)}}function w(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),Object.freeze(t)}function T(e,t,r,i){let a=n.y(t);n.s(e,a,r);let o=n.p(e,a,r,i);n.x(o.matcher,o.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!1),n.o(e,o)}function E(e,t){return e.matcher.match(t)?.segments.at(-1)?.fullName}function D(e,t,n,r,i){if(E(e,r.path)!==i){t.revalidateToNotFound(r.path);return}t.systemCommit(n,r,m)}function O(e,t,r,i,a){let o=n.y(t);n.d(o,`addRoute`),n.c(o,`addRoute`),n.l(o,``,`addRoute`),n.u(o,``,`addRoute`);let s=n.m(o,e.rootPath,e.matcherOptions,r.logger);n.x(s.matcher,s.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(s.pendingCanActivate.keys(),s.pendingCanDeactivate.keys(),!0);let c=n._(s,e.depsStore);if(e.lifecycleNamespace.clearDefinitionGuards(),n.o(e,s,c),a?.(),i!==void 0){let t=E(e,i.path),a=r.matchPath(i.path,r.getOptions());if(a)if(a.name===i.name)D(e,r,{...a,context:i.context,transition:i.transition},i,t);else{let{toActivate:o}=n.i(a,i,r.getMetaForState);e.lifecycleNamespace.canNavigateTo([],o,a,i)?D(e,r,{...a,transition:i.transition},i,t):r.revalidateToNotFound(i.path)}else r.revalidateToNotFound(i.path)}}function k(e,t,r){let i=e.definitions,a=n.w(i,t);if(a===void 0)return;let o=r?x(e,a):h;return g(a,e.config,e.routeCustomFields,e.lifecycleNamespace),n.g(e,i),o}function A(e,t){let r=e.matcher.getSegmentsByName(t);if(!r)return;let i=n.O(r.at(-1)),a=e.lifecycleNamespace.getFactories();return v(i,t,e.config,a)}const j=new WeakMap;function M(s){let c=j.get(s);if(c)return c;let u=e.u(s),d=u.routeGetStore(),f=e=>{u.treeChanged.emit(e)},m=Object.freeze({add:(e,t)=>{r(u.isDisposed),i(u.treeChanged.isEmitting);let a=Array.isArray(e)?e:[e],o=t?.parent;if(n.j(a,u.validator),o!==void 0&&u.validator?.routes.validateParentOption(o,d.tree),u.validator?.routes.throwIfInternalRouteInArray(a,`addRoute`),u.validator?.routes.validateAddRouteArgs(a),u.validator?.routes.validateRoutes(a,d,o),T(d,a,o,u.logger),u.treeChanged.listenerCount()>0){let e=S(a,o,d);f(o===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:o})}},remove:e=>{if(r(u.isDisposed),i(u.treeChanged.isEmitting),u.validator?.routes.validateRemoveRouteArgs(e),u.validator?.routes.throwIfInternalRoute(e,`removeRoute`),n.f(e,`removeRoute`),!a(e,u.getStateName(),u.logger))return;let t=u.treeChanged.listenerCount()>0,s=k(d,e,t);if(s===void 0){u.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`);return}u.isTransitioning()&&o(e,u.logger),t&&f({op:`remove`,name:e,removedSubtree:s})},update:(e,t)=>{if(r(u.isDisposed),i(u.treeChanged.isEmitting),u.validator?.routes.validateUpdateRouteBasicArgs(e,t),u.validator?.routes.throwIfInternalRoute(e,`updateRoute`),n.f(e,`updateRoute`),u.validator?.routes.validateUpdateRoutePropertyTypes(e,t),u.validator?.routes.validateUpdateRoute(e,t,d),!d.matcher.hasRoute(e))return;u.isTransitioning()&&u.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`);let a=d.lifecycleNamespace,o=n.h(d,a,e,t);if(u.treeChanged.listenerCount()>0){let t=w(o);p(t).length>0&&f({op:`update`,name:e,patch:t})}},clear:()=>{if(r(u.isDisposed),i(u.treeChanged.isEmitting),u.getStateName()!==void 0)throw n.r(new n.n(t.m.ROUTER_NOT_STOPPED,{message:`[router.clear] Cannot clear routes while a state is committed. Use replace(routes) to swap the tree on a running router, or stop() first.`}));if(!l(u.isTransitioning(),u.logger))return;let e=u.treeChanged.listenerCount()>0?Object.freeze([...b(d,()=>!0).values()]):void 0;n.v(d),d.lifecycleNamespace.clearAll(),e!==void 0&&f({op:`clear`,removed:e})},has:e=>(u.validator?.routes.validateRouteName(e,`hasRoute`),d.matcher.hasRoute(e)),get:e=>(u.validator?.routes.validateRouteName(e,`getRoute`),A(d,e)),replace:e=>{r(u.isDisposed),i(u.treeChanged.isEmitting);let t=Array.isArray(e)?e:[e];if(!l(u.isTransitioning(),u.logger))return;n.j(t,u.validator),u.validator?.routes.throwIfInternalRouteInArray(t,`replaceRoutes`),u.validator?.routes.validateAddRouteArgs(t),u.validator?.routes.validateRoutes(t,d);let a=s.getState(),o=u.treeChanged.listenerCount()>0?b(d,()=>!0):void 0;O(d,t,u,a,o===void 0?void 0:()=>{let e=b(d,()=>!0),{removed:t,added:n}=C(o,e);f({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>u.treeChanged.subscribe(e)});return j.set(s,m),m}const N=Object.hasOwn,P=e=>typeof e==`symbol`?e:String(e);function F(e,t,n,r){if(n===void 0)return;let i=e.dependencies,a=P(t);if(!N(i,a))r?.dependencies.validateDependencyCount(e,`setDependency`);else{let e=i[a];e!==n&&!(Number.isNaN(e)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(String(a),`setDependency`)}i[a]=n}function I(e,t,r){let i=[],a=e.dependencies;n.M(t,(t,n)=>{N(a,t)?i.push(t):r?.dependencies.validateDependencyCount(e,`setDependencies`),a[t]=n}),i.length>0&&r?.dependencies.warnBatchOverwrite(i,`setDependencies`)}function L(t){let i=e.u(t);return{get:e=>{i.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=i.dependenciesGetStore(),n=t.dependencies[e];return i.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>{let e=i.dependenciesGetStore().dependencies;return n.A({...e})},set:(e,t)=>{r(i.isDisposed),i.validator?.dependencies.validateSetDependencyArgs(e,t,`setDependency`),F(i.dependenciesGetStore(),e,t,i.validator),r(i.isDisposed)},setAll:e=>{r(i.isDisposed);let t=i.dependenciesGetStore();i.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),I(t,e,i.validator),r(i.isDisposed)},remove:e=>{r(i.isDisposed),i.validator?.dependencies.validateDependencyName(e,`removeDependency`);let t=i.dependenciesGetStore(),n=P(e);N(t.dependencies,n)||i.validator?.dependencies.warnRemoveNonExistent(String(n)),delete t.dependencies[n]},reset:()=>{r(i.isDisposed);let e=i.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(i.validator?.dependencies.validateDependencyName(e,`hasDependency`),N(i.dependenciesGetStore().dependencies,e))}}function R(t){let n=e.u(t),i=n.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`addActivateGuard`),n.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t,!1)},addDeactivateGuard(e,t){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`addDeactivateGuard`),n.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t,!1)},removeActivateGuard(e){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){r(n.isDisposed),n.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}const z=Object.entries,B=Object.hasOwn,V=Object.keys;function H(r,i,a){let o=e.u(r);if(o.isDisposed())throw n.r(new n.n(t.m.ROUTER_DISPOSED));o.validator?.dependencies.validateCloneArgs(i);let s=o.routeGetStore(),c=n.k(s.tree),l=s.config,u=s.resolvedForwardMap,d=s.routeCustomFields,{options:f,dependencies:p,pluginFactories:m,loggerConfig:h,limits:g}=o.getCloneState(),{definition:_,external:v}=s.lifecycleNamespace.getFactoriesByOrigin(),y={...p};i!==void 0&&n.M(i,(e,n)=>{t.a(y,e,n)});let b=a?.logger?{...h,...a.logger}:h,x=new n.t(c,{...f,logger:b,...f.limits!=null&&{limits:Object.fromEntries(V(f.limits).filter(e=>B(g,e)).map(e=>[e,g[e]]))},...s.matcherOptions?.urlParamsEncoding!==void 0&&{urlParamsEncoding:s.matcherOptions.urlParamsEncoding}},y),S=e.u(x),C=S.routeGetStore(),w=C.lifecycleNamespace;n.S(C.config,l),n.a(C,Object.assign(C.resolvedForwardMap,u)),Object.assign(C.routeCustomFields,d),s.rootPath!==``&&S.setRootPath(s.rootPath);let[T,E]=_,[D,O]=v;for(let[e,t]of z(T))w.addCanDeactivate(e,t,!0);for(let[e,t]of z(E))w.addCanActivate(e,t,!0);let k=R(x);for(let[e,t]of z(D))k.addDeactivateGuard(e,t);for(let[e,t]of z(O))k.addActivateGuard(e,t);let A=new Set(S.getCloneState().pluginFactories),j=m.filter(e=>!A.has(e));return j.length>0&&x.usePlugin(...j),x}exports.cloneRouter=H,exports.getDependenciesApi=L,exports.getLifecycleApi=R,exports.getPluginApi=f,exports.getRoutesApi=M;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./ingest-DxGcWzr6.js"),t=Object.hasOwn;function n(e,n){if(n.length!==0&&e!==void 0)for(let r of n){if(!t(e,r))continue;let n;try{n=e[r]}catch{return}if(n!==void 0)return r}}function r(e,t,r,i,o,s){let c=n(r,i);if(c!==void 0)throw TypeError(`[router.${e}] ${a(t,c,typeof o==`function`?o():o,s)}`)}function i(e,t,n,i){r(e,t,n,i,"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 a(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 o=new WeakMap;function s(e){let t=o.get(e);if(!t)throw TypeError(`[real-router] Invalid router instance — not found in internals registry`);return t}function c(e,t,n,i){r(t,n,i,e.getQueryParams(n))}function l(e,t){o.set(e,t)}function u(e,t,n,r){let i=t;for(let t of e){let e=i,n=r===void 0?e:(...t)=>r(e(...t));i=(...e)=>t(n,...e)}return i(...n)}function d(e,t,n){return((...r)=>{let i=n.get(e);return!i||i.length===0?t(...r):u(i,t,r)})}function f(e,t,n,r){return(i,a,o)=>{let s=n.get(e);return!s||s.length===0?t(i,a,o):u(s,t,[i,a,o],r)}}const p=e=>e===58||e===42;function m(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 h(e){let t=e.length;if(t===0)return{kind:`static`,text:``};if(!p(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(p(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`}:p(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 g(e){for(let t of m(e)){let e=h(t);if(`error`in e)return e.error}}function _(e){let t=m(e);for(let e=0;e<t.length;e+=1){let n=h(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 v=/[<>]/u;function y(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(n!==-1&&n!==47&&n!==63&&n!==60)return t}return-1}const b=Object.freeze([]),x=Object.freeze({}),S=Object.freeze({urlParams:b,queryParams:b,spatParams:b,paramTypeMap:x,pathPattern:``});function C(e,t,n,r){for(let i of m(e)){if(i.length===0)continue;let e=h(i);`error`in e||e.kind===`static`||(t.push(e.name),r[e.name]=`url`,e.kind===`splat`&&n.push(e.name))}}function w(t){let n=[],r=[],i=[],a=e.r(),o=y(t);if(o!==-1){let e=t.slice(o+1).split(`&`);for(let t of e){let e=t.trim();e.length>0&&(r.push(e),a[e]=`query`)}t=t.slice(0,o)}return C(t,n,i,a),T(n,r,i,e.i(a),t)}function T(e,t,n,r,i){return{urlParams:e.length===0?b:e,queryParams:t.length===0?b:t,spatParams:n.length===0?b:n,paramTypeMap:e.length===0&&t.length===0?x:r,pathPattern:i}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return s}});
|
|
2
|
+
//# sourceMappingURL=buildParamMeta-C9Hfrxr9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildParamMeta-CG-WYPDp.js","names":["LT","QUESTION","SLASH","emptyRecord","publishRecord"],"sources":["../../src/channels/guard.ts","../../src/internals.ts","../../src/engine/path-matcher/parseSegment.ts","../../src/engine/path-matcher/buildParamMeta.ts"],"sourcesContent":["// packages/core/src/channels/guard.ts\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 * ⚠ It does NOT close a shim evaluated BEFORE this module — the ordinary\n * polyfill order. Measured: a naive `Object.hasOwn` imported ahead of core\n * reproduces #1798 verbatim (`buildPath` prints the native method into the\n * URL). Two earlier revisions of this header said \"before any application\n * code can run\", which is the sentence a future reader would have trusted.\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. Moving it is what\n * `separateChannels` (stage ②) used to do — a function that no longer exists.\n * Channel-correctness is the producer's contract now, not a repair the pipeline\n * 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 if (queryNames.length === 0 || params === undefined) {\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 * Replaces the repair `separateChannels` (stage ②, since deleted) used to\n * perform at the `forwardState` seam. A key the route declares with `?`, sitting in the PATH\n * bag, is a producer's mistake — the producer named the route, so it knows the\n * declaration — and the router now says so instead of quietly moving the field\n * into the other object. Moving it was invisible: the caller kept believing\n * their bag was the one that shipped, and two producers of the SAME intent\n * could disagree about which 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 throw new TypeError(\n `[router.${method}] ${misChanneledKeyMessage(\n routeName,\n key,\n typeof source === \"function\" ? source() : source,\n remedy,\n )}`,\n );\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 */\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. Measured before this existed: `makeState` read the bag twice and\n * `navigate` three times, and a bag answering `undefined` while the guards\n * looked — the documented removal marker, correctly waved through — committed a\n * declared query name into `state.params` while `state.path` printed without it.\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\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","import { assertChannelCorrect } from \"./channels\";\n\nimport type { RouteTree } from \"./engine\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { RouteResolver } from \"./pipeline\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type {\n AnyOptions,\n DefaultDependencies,\n EventName,\n LoggerConfig,\n NavigationOptions,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouterLogger,\n RouteTreeState,\n SearchParams,\n SerializedRouterState,\n SimpleState,\n State,\n TreeChangedEvent,\n Unsubscribe,\n EventMethodMap,\n PluginFactory,\n} from \"./types\";\nimport type { Limits } from \"./types/internal\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n name: string,\n params?: P,\n search?: S,\n path?: string,\n ) => State<P, S>;\n\n /**\n * Per-segment param-source map for a route name (`{ segment: { param: \"url\" |\n * \"query\" } }`), read from the live matcher — the ownership channel for\n * `getTransitionPath` (RFC-4 M2 / #1548, replaced the removed per-State\n * `stateMetaStore` WeakMap). `undefined` when the name is not in the tree.\n */\n readonly getMetaForState: (\n name: string,\n ) => Record<string, Record<string, \"url\" | \"query\">> | undefined;\n\n /**\n * The route's DECLARED query-param names — the same registry the URL build\n * prints from (#1556), minus path slots. Feeds the always-on channel guard\n * (#1572); read here rather than re-derived, so classification cannot drift.\n */\n readonly getQueryParams: (name: string) => readonly string[];\n\n readonly forwardState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n routeName: string,\n routeParams: P,\n routeSearch?: S,\n ) => SimpleState<P, S>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params>(\n path: string,\n options?: AnyOptions,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options<D>;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n /**\n * Route-tree mutation channel — internal access for the `getRoutesApi`\n * wrapper. A dedicated bridge is required because the public\n * `addEventListener<E extends EventName>` structurally rejects\n * `\"TREE_CHANGED\"` (it is not in the public `EventName` union), is strict on\n * duplicates, and exposes neither `emit` nor `listenerCount`.\n */\n readonly treeChanged: {\n readonly emit: (event: TreeChangedEvent) => void;\n readonly subscribe: (\n handler: (event: TreeChangedEvent) => void,\n ) => Unsubscribe;\n readonly listenerCount: () => number;\n /**\n * True while a `TREE_CHANGED` emit is on the stack — `getRoutesApi` reads it\n * to reject reentrant route-CRUD from a `subscribeChanges` handler (#1032).\n */\n readonly isEmitting: () => boolean;\n };\n\n readonly buildPath: (\n route: string,\n params?: Params,\n search?: SearchParams,\n ) => string;\n\n /**\n * The navigation pipeline's read-model, for entry points that live on this\n * plugin-facing surface rather than in a namespace. Resolved LAZILY: the port\n * is created during wiring, and `registerInternals` runs before that, so the\n * accessor is a closure rather than a value — the same shape the interceptable\n * methods above already use.\n */\n readonly port: () => RouteResolver;\n\n readonly emitTransitionError: (error: Error) => void;\n\n /**\n * Commits the not-found (`UNKNOWN_ROUTE`) state for `path` and emits\n * `TRANSITION_SUCCESS` — the `NavigationNamespace.navigateToNotFound`\n * primitive. `replace()` uses it when a structural replace drops the active\n * route, so subscribers are notified instead of the state silently clearing\n * (#950).\n */\n readonly navigateToNotFound: (path: string) => State;\n\n /**\n * The `replace()` revalidation's twin of the above: commits `UNKNOWN_ROUTE`\n * WITHOUT consulting the departing route's `canDeactivate` (#1652, #1981).\n * A tree swap is not a departure the user chose.\n */\n readonly revalidateToNotFound: (path: string) => State;\n\n readonly start: (path: string) => Promise<State>;\n\n /**\n * Plugin-only navigation entry point — delegates to\n * `NavigationNamespace.navigateToState` (`getPluginApi(router).navigateToState`).\n * Hidden from `Router`/`Navigator` to keep the userland surface minimal;\n * see `core-types/src/api.ts` for usage docs.\n */\n readonly navigateToState: (\n state: State,\n options?: NavigationOptions,\n ) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Per-router logger instance (built from `options.logger` in the Router\n // constructor). The facade reads it as `getInternals(this).logger`; namespaces\n // receive it via their deps at wiring; plugins reach it through\n // `getPluginApi(router).logger`. Replaces the former process-global singleton\n // from the standalone `@real-router/logger` package (now folded into\n // `utils/logger`), whose `configure()` leaked across routers (#724).\n readonly logger: RouterLogger;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173, consolidated #964). One accessor for the\n // source-side snapshot a clone carries over besides the route store, so a new\n // clone-relevant subsystem is wired in a single place instead of being spread\n // across separate methods.\n readonly getCloneState: () => {\n options: Options<D>;\n dependencies: Record<string, unknown>;\n pluginFactories: PluginFactory<D>[];\n // Resolved logger config of the base router, so a clone can build its OWN\n // logger inheriting the base's level/callback. Frozen `options` do NOT carry\n // `logger` (stripped in the constructor), so `options` above can't convey it;\n // cloneRouter merges a per-request override (traceId) over this snapshot.\n loggerConfig: LoggerConfig;\n // Resolved limits of the base router (#1880). Same reason as `loggerConfig`\n // one line up: `options.limits` is the caller's own bag, so a clone built\n // from it re-invokes an accessor there and can end up with a different cap\n // than its base. The base already resolved them to numbers; the clone\n // inherits that rather than re-reading.\n limits: Limits;\n };\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n /**\n * Commit a state that is NOT the product of a navigation — the 404 bypass and\n * `replace()`'s revalidation. Writes AND announces through the FSM\n * `SYSTEM_COMMIT` action, so neither half happens outside the table.\n *\n * THROWS when the machine has no edge to take. The throw is NOT redundant\n * with the table: a refusal there is silent (a `send` from a state without an\n * edge is a no-op), and the contract these callers already had promises an\n * error, not a quietly skipped commit (#1186).\n *\n * Two codes, and the split is #1644's: `ROUTER_DISPOSED` only for a router\n * that IS disposed, `ROUTER_NOT_STARTED` for every other refusal — stopped,\n * never started, still STARTING, or mid-transition — because `SYSTEM_COMMIT`\n * is declared on `READY` alone and therefore also refuses routers that are\n * very much alive. The phase rides the message rather than the code.\n */\n readonly systemCommit: (\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n ) => State;\n readonly routerExtensions: { keys: string[] }[];\n readonly contextClaimRecords: Set<string>;\n\n /**\n * One-shot hydration scratchpad populated by `hydrateRouter` immediately\n * before delegating to `router.start(parsed.path)` and cleared in the\n * matching `finally`. SSR loader plugins read this slot directly via\n * `getInternals(router).hydrationState` to short-circuit their own loader\n * call when the server-resolved namespace value is already present in the\n * parsed state (#596). `null` outside of an active `hydrateRouter`\n * invocation.\n */\n hydrationState: SerializedRouterState | null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\n/**\n * Channel guard, position P1 (#1572) — the caller's RAW `params` argument, at\n * the API boundary and BEFORE any interceptor runs, so what it reports is what\n * the CALLER wrote (a plugin's later injection is P2's population, not this one).\n *\n * THROWS. The warn-first step (#1572) announced the contract so every call site\n * could identify itself in the logs; this is the promotion it announced.\n *\n * A `TypeError`, synchronous, rather than a `RouterError` on a rejected promise:\n * this is an ARGUMENT-shape defect at the API boundary, caught before any\n * interceptor or transition exists — the same class as the `subscribe` /\n * `navigateToNotFound` / `start` guards beside it. Rejecting instead would let a\n * `.catch()` written for navigation failures swallow a programming error.\n *\n * P3 (`navigateToState`) keeps REJECTING — deliberately asymmetric, because it\n * takes a ready-made `State` from a popstate handler, where a new synchronous\n * throw would change an existing method's failure shape.\n *\n * The predicates (`buildPath` / `isActiveRoute` / `canNavigateTo`) are still NOT\n * instrumented: they run on every `<Link>` render, an answer there is read\n * immediately and corrupts nothing, and throwing inside a render in six adapters\n * is not a trade this guard is worth.\n *\n * ⚠ Not instrumented ≠ blind. `canNavigateTo` answers whether `navigate` WOULD\n * work, so it consults {@link findMisChanneledKey} directly and returns `false`\n * for a shape this function would have thrown on (#1576) — an answer, not a\n * throw, so the render-path trade above is untouched. `buildPath` /\n * `isActiveRoute` ask a different question and are unchanged.\n *\n * @internal\n */\nexport function throwOnMisChanneledKey<D extends DefaultDependencies>(\n ctx: RouterInternals<D>,\n method: string,\n routeName: string,\n params: Params | undefined,\n): void {\n assertChannelCorrect(\n method,\n routeName,\n params,\n ctx.getQueryParams(routeName),\n );\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n\n chain = (...chainArgs: any[]) => interceptor(prev, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\n/**\n * Variadic interceptor wrapper — wraps a function of any arity, returning the\n * same callable type `T`. Use {@link createTernaryInterceptable} instead when\n * the wrapped method takes exactly three args and the caller needs the precise\n * `(a, b, c) => r` signature preserved (the variadic form widens args to\n * `any[]`).\n */\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\n/**\n * Three-argument interceptor wrapper — preserves the exact\n * `(a: A, b: B, c: C) => R` signature that the variadic\n * {@link createInterceptable} widens to `any[]`. Backs both search-aware\n * interceptables — `buildPath(route, params, search)` and\n * `forwardState(name, params, search)` (RFC-4 M2 / #1548). Every first-party\n * plugin registers the full three-argument form; a shorter-arity interceptor\n * from a third party remains type-valid (TS allows fewer params, and `next(a,\n * b)` leaves the third arg `undefined`).\n */\nexport function createTernaryInterceptable<A, B, C, R>(\n name: string,\n original: (a: A, b: B, c: C) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B, c: C) => R {\n return (arg1: A, arg2: B, arg3: C) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2, arg3);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2, arg3]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\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 // В1.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 `<`/`>` — В1.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/spatParams.\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 — the former separate\n // `next !== undefined` conjunct was dead (the ternary bounds the index, so\n // `codePointAt` never returns `undefined`; the `!` is a type assertion, not a\n // runtime branch, so it keeps the scan at 100% coverage). Mirrors `#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 (next !== -1 && next !== SLASH && next !== QUESTION && next !== LT) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Builds parameter metadata from a route path pattern.\n *\n * Extracts URL parameters, query parameters, and splat parameters\n * from the path pattern string.\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: [], spatParams: [], paramTypeMap: { id: \"url\" } }\n *\n * buildParamMeta(\"/search?q&page\")\n * // → { urlParams: [], queryParams: [\"q\", \"page\"], spatParams: [],\n * // paramTypeMap: { q: \"query\", page: \"query\" } }\n *\n * buildParamMeta(\"/files/*path\")\n * // → { urlParams: [\"path\"], queryParams: [], spatParams: [\"path\"],\n * // paramTypeMap: { path: \"url\" } }\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 spatParams: EMPTY_PARAM_NAMES,\n paramTypeMap: EMPTY_PARAM_TYPE_MAP,\n pathPattern: \"\",\n});\n\n/**\n * Extracts URL/splat params 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 spatParams: 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 if (token.kind === \"splat\") {\n spatParams.push(token.name);\n }\n }\n}\n\nexport function buildParamMeta(path: string): ParamMeta {\n const urlParams: string[] = [];\n const queryParams: string[] = [];\n const spatParams: 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, spatParams, paramTypeMap);\n\n return shareEmptyCollections(\n urlParams,\n queryParams,\n spatParams,\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 spatParams: 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 spatParams: spatParams.length === 0 ? EMPTY_PARAM_NAMES : spatParams,\n paramTypeMap:\n urlParams.length === 0 && queryParams.length === 0\n ? EMPTY_PARAM_TYPE_MAP\n : paramTypeMap,\n pathPattern,\n };\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"buildParamMeta-C9Hfrxr9.js","names":["LT","QUESTION","SLASH","emptyRecord","publishRecord"],"sources":["../../src/channels/guard.ts","../../src/internals.ts","../../src/engine/path-matcher/parseSegment.ts","../../src/engine/path-matcher/buildParamMeta.ts"],"sourcesContent":["// packages/core/src/channels/guard.ts\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 * ⚠ It does NOT close a shim evaluated BEFORE this module — the ordinary\n * polyfill order. Measured: a naive `Object.hasOwn` imported ahead of core\n * reproduces #1798 verbatim (`buildPath` prints the native method into the\n * URL). Two earlier revisions of this header said \"before any application\n * code can run\", which is the sentence a future reader would have trusted.\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. Moving it is what\n * `separateChannels` (stage ②) used to do — a function that no longer exists.\n * Channel-correctness is the producer's contract now, not a repair the pipeline\n * 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 if (queryNames.length === 0 || params === undefined) {\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 * Replaces the repair `separateChannels` (stage ②, since deleted) used to\n * perform at the `forwardState` seam. A key the route declares with `?`, sitting in the PATH\n * bag, is a producer's mistake — the producer named the route, so it knows the\n * declaration — and the router now says so instead of quietly moving the field\n * into the other object. Moving it was invisible: the caller kept believing\n * their bag was the one that shipped, and two producers of the SAME intent\n * could disagree about which 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 throw new TypeError(\n `[router.${method}] ${misChanneledKeyMessage(\n routeName,\n key,\n typeof source === \"function\" ? source() : source,\n remedy,\n )}`,\n );\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 */\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. Measured before this existed: `makeState` read the bag twice and\n * `navigate` three times, and a bag answering `undefined` while the guards\n * looked — the documented removal marker, correctly waved through — committed a\n * declared query name into `state.params` while `state.path` printed without it.\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\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","import { assertChannelCorrect } from \"./channels\";\n\nimport type { RouteTree } from \"./engine\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { RouteResolver } from \"./pipeline\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type {\n AnyOptions,\n DefaultDependencies,\n EventName,\n LoggerConfig,\n NavigationOptions,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouterLogger,\n RouteTreeState,\n SearchParams,\n SerializedRouterState,\n SimpleState,\n State,\n TreeChangedEvent,\n Unsubscribe,\n EventMethodMap,\n PluginFactory,\n} from \"./types\";\nimport type { Limits } from \"./types/internal\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n name: string,\n params?: P,\n search?: S,\n path?: string,\n ) => State<P, S>;\n\n /**\n * Per-segment param-source map for a route name (`{ segment: { param: \"url\" |\n * \"query\" } }`), read from the live matcher — the ownership channel for\n * `getTransitionPath` (RFC-4 M2 / #1548, replaced the removed per-State\n * `stateMetaStore` WeakMap). `undefined` when the name is not in the tree.\n */\n readonly getMetaForState: (\n name: string,\n ) => Record<string, Record<string, \"url\" | \"query\">> | undefined;\n\n /**\n * The route's DECLARED query-param names — the same registry the URL build\n * prints from (#1556), minus path slots. Feeds the always-on channel guard\n * (#1572); read here rather than re-derived, so classification cannot drift.\n */\n readonly getQueryParams: (name: string) => readonly string[];\n\n readonly forwardState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n routeName: string,\n routeParams: P,\n routeSearch?: S,\n ) => SimpleState<P, S>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params>(\n path: string,\n options?: AnyOptions,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options<D>;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n /**\n * Route-tree mutation channel — internal access for the `getRoutesApi`\n * wrapper. A dedicated bridge is required because the public\n * `addEventListener<E extends EventName>` structurally rejects\n * `\"TREE_CHANGED\"` (it is not in the public `EventName` union), is strict on\n * duplicates, and exposes neither `emit` nor `listenerCount`.\n */\n readonly treeChanged: {\n readonly emit: (event: TreeChangedEvent) => void;\n readonly subscribe: (\n handler: (event: TreeChangedEvent) => void,\n ) => Unsubscribe;\n readonly listenerCount: () => number;\n /**\n * True while a `TREE_CHANGED` emit is on the stack — `getRoutesApi` reads it\n * to reject reentrant route-CRUD from a `subscribeChanges` handler (#1032).\n */\n readonly isEmitting: () => boolean;\n };\n\n readonly buildPath: (\n route: string,\n params?: Params,\n search?: SearchParams,\n ) => string;\n\n /**\n * The navigation pipeline's read-model, for entry points that live on this\n * plugin-facing surface rather than in a namespace. Resolved LAZILY: the port\n * is created during wiring, and `registerInternals` runs before that, so the\n * accessor is a closure rather than a value — the same shape the interceptable\n * methods above already use.\n */\n readonly port: () => RouteResolver;\n\n readonly emitTransitionError: (error: Error) => void;\n\n /**\n * Commits the not-found (`UNKNOWN_ROUTE`) state for `path` and emits\n * `TRANSITION_SUCCESS` — the `NavigationNamespace.navigateToNotFound`\n * primitive. `replace()` uses it when a structural replace drops the active\n * route, so subscribers are notified instead of the state silently clearing\n * (#950).\n */\n readonly navigateToNotFound: (path: string) => State;\n\n /**\n * The `replace()` revalidation's twin of the above: commits `UNKNOWN_ROUTE`\n * WITHOUT consulting the departing route's `canDeactivate` (#1652, #1981).\n * A tree swap is not a departure the user chose.\n */\n readonly revalidateToNotFound: (path: string) => State;\n\n readonly start: (path: string) => Promise<State>;\n\n /**\n * Plugin-only navigation entry point — delegates to\n * `NavigationNamespace.navigateToState` (`getPluginApi(router).navigateToState`).\n * Hidden from `Router`/`Navigator` to keep the userland surface minimal;\n * see `core-types/src/api.ts` for usage docs.\n */\n readonly navigateToState: (\n state: State,\n options?: NavigationOptions,\n ) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Per-router logger instance (built from `options.logger` in the Router\n // constructor). The facade reads it as `getInternals(this).logger`; namespaces\n // receive it via their deps at wiring; plugins reach it through\n // `getPluginApi(router).logger`. Replaces the former process-global singleton\n // from the standalone `@real-router/logger` package (now folded into\n // `utils/logger`), whose `configure()` leaked across routers (#724).\n readonly logger: RouterLogger;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173, consolidated #964). One accessor for the\n // source-side snapshot a clone carries over besides the route store, so a new\n // clone-relevant subsystem is wired in a single place instead of being spread\n // across separate methods.\n readonly getCloneState: () => {\n options: Options<D>;\n dependencies: Record<string, unknown>;\n pluginFactories: PluginFactory<D>[];\n // Resolved logger config of the base router, so a clone can build its OWN\n // logger inheriting the base's level/callback. Frozen `options` do NOT carry\n // `logger` (stripped in the constructor), so `options` above can't convey it;\n // cloneRouter merges a per-request override (traceId) over this snapshot.\n loggerConfig: LoggerConfig;\n // Resolved limits of the base router (#1880). Same reason as `loggerConfig`\n // one line up: `options.limits` is the caller's own bag, so a clone built\n // from it re-invokes an accessor there and can end up with a different cap\n // than its base. The base already resolved them to numbers; the clone\n // inherits that rather than re-reading.\n limits: Limits;\n };\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n /**\n * Commit a state that is NOT the product of a navigation — the 404 bypass and\n * `replace()`'s revalidation. Writes AND announces through the FSM\n * `SYSTEM_COMMIT` action, so neither half happens outside the table.\n *\n * THROWS when the machine has no edge to take. The throw is NOT redundant\n * with the table: a refusal there is silent (a `send` from a state without an\n * edge is a no-op), and the contract these callers already had promises an\n * error, not a quietly skipped commit (#1186).\n *\n * Two codes, and the split is #1644's: `ROUTER_DISPOSED` only for a router\n * that IS disposed, `ROUTER_NOT_STARTED` for every other refusal — stopped,\n * never started, still STARTING, or mid-transition — because `SYSTEM_COMMIT`\n * is declared on `READY` alone and therefore also refuses routers that are\n * very much alive. The phase rides the message rather than the code.\n */\n readonly systemCommit: (\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n ) => State;\n readonly routerExtensions: { keys: string[] }[];\n readonly contextClaimRecords: Set<string>;\n\n /**\n * One-shot hydration scratchpad populated by `hydrateRouter` immediately\n * before delegating to `router.start(parsed.path)` and cleared in the\n * matching `finally`. SSR loader plugins read this slot directly via\n * `getInternals(router).hydrationState` to short-circuit their own loader\n * call when the server-resolved namespace value is already present in the\n * parsed state (#596). `null` outside of an active `hydrateRouter`\n * invocation.\n */\n hydrationState: SerializedRouterState | null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\n/**\n * Channel guard, position P1 (#1572) — the caller's RAW `params` argument, at\n * the API boundary and BEFORE any interceptor runs, so what it reports is what\n * the CALLER wrote (a plugin's later injection is P2's population, not this one).\n *\n * THROWS. The warn-first step (#1572) announced the contract so every call site\n * could identify itself in the logs; this is the promotion it announced.\n *\n * A `TypeError`, synchronous, rather than a `RouterError` on a rejected promise:\n * this is an ARGUMENT-shape defect at the API boundary, caught before any\n * interceptor or transition exists — the same class as the `subscribe` /\n * `navigateToNotFound` / `start` guards beside it. Rejecting instead would let a\n * `.catch()` written for navigation failures swallow a programming error.\n *\n * P3 (`navigateToState`) keeps REJECTING — deliberately asymmetric, because it\n * takes a ready-made `State` from a popstate handler, where a new synchronous\n * throw would change an existing method's failure shape.\n *\n * The predicates (`buildPath` / `isActiveRoute` / `canNavigateTo`) are still NOT\n * instrumented: they run on every `<Link>` render, an answer there is read\n * immediately and corrupts nothing, and throwing inside a render in six adapters\n * is not a trade this guard is worth.\n *\n * ⚠ Not instrumented ≠ blind. `canNavigateTo` answers whether `navigate` WOULD\n * work, so it consults {@link findMisChanneledKey} directly and returns `false`\n * for a shape this function would have thrown on (#1576) — an answer, not a\n * throw, so the render-path trade above is untouched. `buildPath` /\n * `isActiveRoute` ask a different question and are unchanged.\n *\n * @internal\n */\nexport function throwOnMisChanneledKey<D extends DefaultDependencies>(\n ctx: RouterInternals<D>,\n method: string,\n routeName: string,\n params: Params | undefined,\n): void {\n assertChannelCorrect(\n method,\n routeName,\n params,\n ctx.getQueryParams(routeName),\n );\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n sanitiseNext?: (result: T) => T,\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n // ⚑ The `next` an interceptor RECEIVES is wrapped, not the value it returns\n // (#1986). This covers exactly the boundaries nothing else does — `original`\n // into the first interceptor, and each interceptor into the one outside it —\n // and leaves the outermost hop's result to the seam's own exit copy.\n //\n // ⚠ The alternative, wrapping the RETURN, was built and measured rather\n // than argued about. It puts two mechanisms on that last boundary, and one\n // cell stops discriminating: \"an interceptor's OWN poison does not leave the\n // door either\". It does NOT make the exit copy redundant — the\n // no-interceptor fast path skips this chain entirely, so two other cells\n // still red that copy's removal either way.\n const next =\n sanitiseNext === undefined\n ? prev\n : (...nextArgs: any[]) => sanitiseNext(prev(...nextArgs) as T);\n\n chain = (...chainArgs: any[]) => interceptor(next, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\n/**\n * Variadic interceptor wrapper — wraps a function of any arity, returning the\n * same callable type `T`. Use {@link createTernaryInterceptable} instead when\n * the wrapped method takes exactly three args and the caller needs the precise\n * `(a, b, c) => r` signature preserved (the variadic form widens args to\n * `any[]`).\n */\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\n/**\n * Three-argument interceptor wrapper — preserves the exact\n * `(a: A, b: B, c: C) => R` signature that the variadic\n * {@link createInterceptable} widens to `any[]`. Backs both search-aware\n * interceptables — `buildPath(route, params, search)` and\n * `forwardState(name, params, search)` (RFC-4 M2 / #1548). Every first-party\n * plugin registers the full three-argument form; a shorter-arity interceptor\n * from a third party remains type-valid (TS allows fewer params, and `next(a,\n * b)` leaves the third arg `undefined`).\n *\n * ⚑ `sanitiseNext` is applied to whatever `next` hands an interceptor, at every\n * hop (#1986). It exists because `forwardState` returns CONTAINERS a plugin is\n * documented to merge, so what one interceptor hands the next is a hand-out in\n * the #1957 sense; `buildPath` returns a string and passes nothing. The seam\n * that needs it owns the function — this module only applies it.\n *\n * ⚠ It does NOT reach the chain's own return value. That one goes to the caller,\n * which is the seam's own business and already has an exit copy.\n */\nexport function createTernaryInterceptable<A, B, C, R>(\n name: string,\n original: (a: A, b: B, c: C) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n sanitiseNext?: (result: R) => R,\n): (a: A, b: B, c: C) => R {\n return (arg1: A, arg2: B, arg3: C) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2, arg3);\n }\n\n return executeInterceptorChain(\n chain,\n original,\n [arg1, arg2, arg3],\n sanitiseNext,\n );\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\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 // В1.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 `<`/`>` — В1.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/spatParams.\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 — the former separate\n // `next !== undefined` conjunct was dead (the ternary bounds the index, so\n // `codePointAt` never returns `undefined`; the `!` is a type assertion, not a\n // runtime branch, so it keeps the scan at 100% coverage). Mirrors `#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 (next !== -1 && next !== SLASH && next !== QUESTION && next !== LT) {\n return i;\n }\n }\n\n return -1;\n}\n\n/**\n * Builds parameter metadata from a route path pattern.\n *\n * Extracts URL parameters, query parameters, and splat parameters\n * from the path pattern string.\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: [], spatParams: [], paramTypeMap: { id: \"url\" } }\n *\n * buildParamMeta(\"/search?q&page\")\n * // → { urlParams: [], queryParams: [\"q\", \"page\"], spatParams: [],\n * // paramTypeMap: { q: \"query\", page: \"query\" } }\n *\n * buildParamMeta(\"/files/*path\")\n * // → { urlParams: [\"path\"], queryParams: [], spatParams: [\"path\"],\n * // paramTypeMap: { path: \"url\" } }\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 spatParams: EMPTY_PARAM_NAMES,\n paramTypeMap: EMPTY_PARAM_TYPE_MAP,\n pathPattern: \"\",\n});\n\n/**\n * Extracts URL/splat params 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 spatParams: 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 if (token.kind === \"splat\") {\n spatParams.push(token.name);\n }\n }\n}\n\nexport function buildParamMeta(path: string): ParamMeta {\n const urlParams: string[] = [];\n const queryParams: string[] = [];\n const spatParams: 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, spatParams, paramTypeMap);\n\n return shareEmptyCollections(\n urlParams,\n queryParams,\n spatParams,\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 spatParams: 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 spatParams: spatParams.length === 0 ? EMPTY_PARAM_NAMES : spatParams,\n paramTypeMap:\n urlParams.length === 0 && queryParams.length === 0\n ? EMPTY_PARAM_TYPE_MAP\n : paramTypeMap,\n pathPattern,\n };\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","names":[],"sources":["../../src/constants.ts"],"mappings":";;KAWY;KAEA,YAAY,SAAS,OAAO;KAM5B,aAAa,OAAO,eAAe;;;;;;cAOlC,YAAY;;;;;cAuBZ;
|
|
1
|
+
{"version":3,"file":"constants.d.ts","names":[],"sources":["../../src/constants.ts"],"mappings":";;KAWY;KAEA,YAAY,SAAS,OAAO;KAM5B,aAAa,OAAO,eAAe;;;;;;cAOlC,YAAY;;;;;cAuBZ;cAwIA,WAAW;;;;;cAsBX,QAAQ"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./ingest-DxGcWzr6.js"),t=require("./Router-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./ingest-DxGcWzr6.js"),t=require("./Router-CUtRu_zV.js"),n=(e=[],n={},r={})=>new t.t(e,n,r),r=new WeakMap,i=e=>{let t=r.get(e);return t||(t=Object.freeze({navigate:e.navigate,getState:e.getState,isActiveRoute:e.isActiveRoute,canNavigateTo:e.canNavigateTo,subscribe:e.subscribe,subscribeLeave:e.subscribeLeave,isLeaveApproved:e.isLeaveApproved}),r.set(e,t)),t};exports.Router=t.t,exports.RouterError=t.n,exports.UNKNOWN_ROUTE=e.d,exports.constants=e.p,exports.createRouter=n,exports.errorCodes=e.m,exports.events=e.h,exports.getNavigator=i,exports.resolveForwardChain=t.b;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ingest-DxGcWzr6.js","names":[],"sources":["../../src/constants.ts","../../src/utils/ingest.ts"],"sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n TransitionMeta,\n} from \"./types\";\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Readonly<Record<ConstantsKeys, string>>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n CONTEXT_NAMESPACE_ALREADY_CLAIMED: \"CONTEXT_NAMESPACE_ALREADY_CLAIMED\", // Plugin tried to claim a context namespace already owned by another plugin\n REENTRANT_NAVIGATION: \"REENTRANT_NAVIGATION\", // navigate() called synchronously from inside a transition-event listener (banned — use await/async listener)\n REENTRANT_TREE_MUTATION: \"REENTRANT_TREE_MUTATION\", // a tree mutator — route-CRUD or setRootPath (#1751) — called synchronously from inside a subscribeChanges handler (banned — use await/async/queueMicrotask)\n ROUTER_NOT_STOPPED: \"NOT_STOPPED\", // clear() called while a state is committed — tear down with stop() first, or swap the tree with replace() (#1612)\n WRONG_CHANNEL: \"WRONG_CHANNEL\", // a declared query key was supplied in the path channel (`params`) instead of `search` (#1572)\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\n/**\n * The one key the router will not copy into a state channel (#1792), and — at\n * `getDependenciesApi.getAll` — will not hand back out of a container either.\n *\n * ⚠ It does not REFUSE it — nothing throws, at any door or at registration; the\n * key is dropped where core copies into a CHANNEL, and kept everywhere else.\n * `claim.write` (#1191) and the route-record merge (#1788) keep it on purpose:\n * a plugin's context namespace and a route's custom fields are not containers a\n * consumer merges. ⚠ Neither of those spells the literal any more — both go\n * through `putField` (#1852), which keeps every name — so a `grep` for this\n * constant no longer finds the sites that carry the opposite contract.\n *\n * `__proto__` is the only ACCESSOR among `Object.prototype`'s twelve own\n * members, so `target[key] = value` for that one name reaches the inherited\n * setter: no own key is created, the value vanishes with no error and no log,\n * and an OBJECT value replaces the target's prototype instead.\n *\n * ⚠ That last sentence used to continue \"…therefore every idiom in core that\n * copies a foreign bag has to NAME it\", and that is no longer the mechanism.\n * `putField` (#1852) defines rather than assigns, so no copy loses the key by\n * accident any more; the five sites that still name it in `helpers.ts` do so to\n * DROP it deliberately, which is a different decision made for a different\n * reason — see below.\n *\n * ⚑ **What is guaranteed, precisely.** A bag that is ORDINARY — plain data that\n * does not change while the router is reading it — cannot put this key among the\n * OWN KEYS of `state.params` or `state.search`. The guarantee is one level deep,\n * and deliberately so: every copy here is `copy[key] = value`, so a value that is\n * itself an object is carried by REFERENCE. Put a bag inside a bag and the inner\n * one is still yours — unfrozen, and with whatever keys you gave it. That means\n * `Object.assign({}, state.search.inner)` can still swap a prototype and\n * `JSON.stringify(getState())` can still carry the name, one level down. Copying\n * deeper would put an unbounded walk on every commit, and the router does not\n * know which of your values are structures and which are opaque handles. That covers the case the rule exists for: a\n * bag from `JSON.parse`, from `history.state`, from a query string an app parsed\n * itself. Entry-point checks cannot deliver even that much, because they read a\n * bag the router does not own and the copy happens later.\n *\n * ⚑ **What is NOT guaranteed, deliberately.** Nothing about a bag that CHANGES\n * while the router reads it — an accessor that rewrites its own object, a Proxy\n * answering differently per trap call. A router cannot defend an application\n * against its own code, and pretending otherwise buys discipline at a dozen\n * sites for a case only the caller can create. That one belongs to whoever\n * handed the bag over, and it is written down rather than defended against.\n *\n * ⚠ The guards below are written WITHOUT reachability arguments: \"it cannot get\n * here\" is a claim about an object the router does not own, and two such claims\n * have already been wrong. OWNERSHIP is a sound reason to omit a guard;\n * reachability is not.\n *\n * ⚑ **Why the CHANNELS drop it while everything else keeps it.** A bag core\n * hands back with an own `\"__proto__\"` is a prototype-swap primitive for any\n * consumer that merges it with `Object.assign` or a `for…in` copy — measured\n * from a bare URL, `?__proto__` parses to `null` and `?__proto__=1&__proto__=2`\n * to an array, and the inherited setter accepts both. `state.params` /\n * `state.search` are the most-merged containers the router publishes, so they\n * follow `getAll`'s rule rather than `claim.write`'s. ⚠ The data-preservation\n * argument for carrying it does not survive contact with a consumer either:\n * `Object.assign` drops the key even in the safe string case, so \"the user's\n * `?__proto__=1` is kept\" holds for exactly one hop.\n *\n * ⚠ The former \"two copies in core do NOT name it\" note is retired: both\n * `channels/modeGate.ts` and `channels/defaults.ts` name it now, and the\n * open exception recorded against the second is closed. It was recorded as an\n * exception rather than a justification precisely so it could not be forgotten,\n * and that worked.\n *\n * ⚑ A THIRD sound exemption, and the only one besides ownership: the TARGET is\n * `Object.create(null)`. There is no inherited setter to dispatch into, so the\n * key lands as an ordinary own property and no guard is needed on the way in.\n * The dependency store is the live case (`dependenciesStore.ts`,\n * `getDependenciesApi.setAll`) — both copy a caller-owned bag and neither names\n * `UNSAFE_KEY`, deliberately. It is also why `getAll` is this constant's other\n * consumer: the key is admitted on the way IN and withheld on the way OUT,\n * because that door hands back a normal object someone will merge.\n *\n * ⚑ **That last sentence is a RULE, and `getAll` is no longer its only case\n * (#1957).** Every door that hands back a container core built withholds the key\n * — router options (and with them the clone transport, one object), the\n * dependency clone transport, and the two `NavigationOptions` a plugin hook\n * receives that core MINTS. `dropUnsafeKey` (`helpers.ts`) is the one primitive;\n * the derived table is\n * `tests/functional/handed-out-containers-1957.test.ts`.\n *\n * ⚠ There is a SECOND shape, for the one container core hands out AND reads\n * back by key: the route-meta record is withheld from ENUMERATION instead\n * (`concealUnsafeKey`, `utils/ingest.ts`), because deleting the entry sends\n * core's own read to the inherited accessor and a route named `__proto__` stops\n * re-activating on a param change — measured.\n *\n * ⚠ Five doors stay EXEMPT, each with a measured reason in that table: the two\n * prior owner decisions (`state.context` #1191, a route's custom fields #1788),\n * the two PASS-THROUGHS where the container is the caller's own object\n * (`forwardState`'s bags, and the un-forced `NavigationOptions` arc), and the\n * internals handle, which exists to hand out the live stores.\n */\nexport const UNSAFE_KEY = \"__proto__\";\n\nexport const constants: Constants = Object.freeze({\n UNKNOWN_ROUTE,\n});\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = Object.freeze({\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_LEAVE_APPROVE: \"onTransitionLeaveApprove\", // Plugin method called when deactivation guards pass\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n});\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = Object.freeze({\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_LEAVE_APPROVE: \"$$leaveApprove\", // Emitted when deactivation guards pass\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n});\n\nexport const DEFAULT_LIMITS = Object.freeze({\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxLifecycleHandlers: 200,\n} as const);\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty query bag reused for `State.search` when a navigation\n * carries no query params — the search-channel twin of {@link EMPTY_PARAMS}\n * (RFC-4 M2 / #1548). Lets `makeState` reuse one frozen `{}` (zero transient\n * allocation, #1027) instead of minting an object per query-less state.\n */\nexport const EMPTY_SEARCH: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty `NavigationOptions`, substituted by the facade when a\n * caller passes none — the options-channel twin of {@link EMPTY_PARAMS}.\n *\n * ⚑ It lives here rather than in `Router.ts` so the entry door can recognise it\n * by IDENTITY (#1962). `navigate(\"b\")` is the commonest call in the library, and\n * matching this singleton is what keeps the door's cost on it to one comparison\n * instead of a copy nobody asked for.\n */\nexport const EMPTY_OPTS: Readonly<Record<string, never>> = Object.freeze({});\n\nconst FROZEN_EMPTY_SEGMENTS = Object.freeze({\n deactivated: Object.freeze([]) as unknown as string[],\n activated: Object.freeze([]) as unknown as string[],\n intersection: \"\",\n});\n\nexport const DEFAULT_TRANSITION = Object.freeze({\n phase: \"activating\",\n reason: \"success\",\n segments: FROZEN_EMPTY_SEGMENTS,\n}) as TransitionMeta;\n","// packages/core/src/utils/ingest.ts\n//\n// One discipline for the records core BUILDS under a key it did not CHOOSE.\n//\n// Two halves, and they answer different questions — a reader who takes them for\n// one primitive will draw the wrong conclusion from either:\n//\n// `emptyRecord` / `publishRecord` (#1825) — a record with no prototype for the\n// BUILD, handed out plain. Used where the record is core's alone:\n// `buildParamMeta`, the segment-meta walk.\n// `putField` / `copyFields` (#1852) — a guarded WRITE for the records that\n// cannot be prototype-less because they are published, read on every render,\n// or belong to someone else. Used across core and, through\n// `@real-router/core/utils`, by four plugins.\n// ⚠ The site COUNTS deliberately do not live here. This comment carried\n// \"twenty-one in core, fourteen across four plugins\" and both halves were\n// wrong (22 and 13, measured) — a second copy of a number `CLAUDE.md`\n// already calls descriptive-not-contract. The count lives in `CLAUDE.md`\n// (\"The WRITE side of the same rule\"); the CONTRACT is the derived set in\n// `tests/functional/computed-key-write-authority-1852.test.ts`.\n//\n// ⚠ Neither decides whether a key is PUBLISHED. `__proto__` stays out of\n// `state.params` / `state.search` by a separate skip at the channel copy sites\n// in `helpers.ts`, and stays IN a route's custom fields and a plugin's context\n// namespace, because those are not containers a consumer merges. See `putField`'s\n// docblock for that split.\n//\n// `concealUnsafeKey` (#1957) is the one member of this file that DOES decide\n// that — for exactly one record, `buildMeta`'s, which core both hands out\n// and reads back by key. It withholds the name from ENUMERATION rather than\n// removing it, because removing it is a measured behaviour loss there. The\n// doors that only hand a container OUT drop the key instead\n// (`dropUnsafeKey`, `helpers.ts`).\n//\n// ⚠ The rest are WRITE-side primitives only, and the boundary is deliberate. A\n// READ-side primitive that walks a caller's prototype chain was written here,\n// wired, measured — and removed: `CLAUDE.md` \"Supported Input Shapes\" settles\n// that axis already (\"own enumerable properties only\", owner decision\n// 2026-08-18), and core is the layer that DEGRADES on a violation while\n// `@real-router/validation-plugin` is the layer that reports it. A primitive\n// that honoured inherited keys would have made core contradict its own canon,\n// and it additionally admitted the ambient `Object.prototype` — the #1840\n// class, introduced by the fix.\n//\n// So what is left is the half the canon does not cover: what happens when core\n// writes into a record of its own under a key it did not choose.\n\nimport { UNSAFE_KEY } from \"../constants\";\n\nconst objectEntries = Object.entries;\n\n/**\n * The target discipline: a record with NO prototype.\n *\n * ⚑ This one line closes two axes at once, which is why it is a primitive and\n * not an idiom. #1856 tabulates them as a structural trade — a key-by-key copy\n * fixes `\"__proto__\"` but turns a `[[DefineOwnProperty]]` into a `[[Set]]`, so\n * an ambient accessor starts throwing — and calls the conflict unavoidable. It\n * is unavoidable only while the target inherits from `Object.prototype`:\n *\n * - `\"__proto__\"` (#1825, #1794, #1809) is an ordinary key here, because the\n * magic accessor lives on `Object.prototype` and this object has none.\n * - an ambient accessor named `id` / `page` / `tab` (#1852) cannot hijack the\n * write for the same reason. #1852 notes the key's provenance is\n * irrelevant — `SegmentMatcher` writes a name from the ROUTE TABLE and\n * throws just the same — so a name-based skip cannot close it and this can.\n */\nexport function emptyRecord<V>(): Record<string, V> {\n return Object.create(null) as Record<string, V>;\n}\n\n/**\n * Hand a privately-built record out with the ORDINARY prototype, keeping every\n * own key — including a literal `\"__proto__\"`.\n *\n * Discovered by measurement, not designed: wiring `emptyRecord` into\n * `buildParamMeta` alone reds **21** existing tests, all of the shape\n * `expected { id: 'url' } to strictly equal { id: 'url' }` — identical content,\n * different prototype, because `toStrictEqual` compares prototypes and\n * `paramTypeMap` is published through `getPluginApi(router).getTree()`. A\n * prototype-less record is not a drop-in at a published surface.\n *\n * The spread is what makes this work rather than undo it: it\n * `[[DefineOwnProperty]]`s, so an own `\"__proto__\"` carried on the private\n * record lands as an ordinary own key here (measured: own keys\n * `[\"__proto__\",\"keep\"]`, value intact, prototype back to `Object.prototype`).\n * Writing that same key into a fresh `{}` with `[[Set]]` loses it entirely\n * (measured: own keys `[]`) — which is the defect the private record exists to\n * avoid.\n *\n * So the rule is: **build private, publish plain.** The window in which the\n * ambient-accessor hazard (#1852) could bite is the build, and the build never\n * touches `Object.prototype`.\n */\nexport function publishRecord<V>(source: Record<string, V>): Record<string, V> {\n return { ...source };\n}\n\n/**\n * Captured at module load for the reason `helpers.ts` gives for `freeze` /\n * `hasOwn` / `objectKeys`: this is the operation {@link putField} writes\n * through, so a guard reading it late would be reading whatever an application\n * had re-pointed it to.\n */\nconst defineProperty = Object.defineProperty;\nconst hasOwn = Object.hasOwn;\n\n/**\n * Withhold `UNSAFE_KEY` from ENUMERATION on a record core hands out AND reads\n * back by key (#1957).\n *\n * ⚑ The hazard is the CONSUMER's merge, not core's own write. `Object.assign`\n * and a `for…in` copy `[[Set]]` each own ENUMERABLE key on the TARGET, where\n * `Object.prototype`'s `\"__proto__\"` accessor replaces that target's prototype\n * instead of adding an entry.\n *\n * ⚠ A SPREAD is not in that list, and an earlier revision of this docblock said\n * it was. `{ ...source }` performs `CreateDataProperty`, i.e.\n * `[[DefineOwnProperty]]`, which never reaches an inherited accessor — measured\n * on the poisoned bag, on a null-prototype carrier and through a pass-through\n * Proxy, a spread swaps in none of the three. #1823 had the list right\n * (\"`Object.assign` or a `for…in` copy\") and this widened it by mistake. The\n * hazard is real and narrower than that sentence claimed.\n *\n * So the SOURCE's own prototype decides nothing either — measured, an\n * `Object.create(null)` source swaps the target exactly the same — and the only\n * two fixes are removing the key or removing it from enumeration.\n *\n * ⚠ **Dropping is not a milder fix here, it is a WRONG one.** The route-meta\n * record is core's working table: `segmentParamsEqual` reads `meta[segmentName]`\n * on every navigation, so with the entry gone the read reaches the INHERITED\n * accessor and answers `Object.prototype` — an object, whose `Object.keys` is\n * `[]`, so the segment reports \"params unchanged\". Measured end to end on a\n * route named `__proto__`: `/p/1` → `/p/2` activates `[\"__proto__\"]` today and\n * `[]` with the entry deleted. Core accepts that name (#1801), so the loss is\n * real and silent.\n *\n * Non-enumerable keeps the read exact for core AND for a consumer asking by\n * key, while `Object.assign` / a spread / `for…in` skip it — measured, all\n * three.\n *\n * ⚠ NOT applied by {@link publishRecord} itself. Its other caller is\n * `buildParamMeta`, whose map core ENUMERATES (`Object.keys` in\n * `segmentParamsEqual`, `for…in` in `hasAnyParam`) and which is not a swap\n * primitive anyway: a param's value is the string `\"url\"` / `\"query\"`, and the\n * inherited setter ignores primitives.\n *\n * Returns the input untouched, with no descriptor write, when the key is absent\n * — which is every ordinary route.\n */\nexport function concealUnsafeKey<V>(\n record: Record<string, V>,\n): Record<string, V> {\n if (!hasOwn(record, UNSAFE_KEY)) {\n return record;\n }\n\n defineProperty(record, UNSAFE_KEY, {\n value: record[UNSAFE_KEY],\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n return record;\n}\n\n/**\n * Write one field of a record core BUILDS under a key it did not choose.\n *\n * ⚑ The rule this exists to enforce: **a caller's object contributes DATA, and\n * nothing else.** No trap, no accessor, no inherited member of a bag handed to\n * the router may change what the router ends up holding — which is what\n * \"treat it as a pure dictionary\" means on the WRITE side. `Object.keys` and\n * the one-read-per-key discipline (#1854 / #1899) already say it on the read\n * side; this is the other half.\n *\n * Plain `target[key] = value` cannot say it. `[[Set]]` walks the prototype\n * chain first, so a key that resolves to an accessor or a non-writable data\n * property up there is HIJACKED — the write dispatches into application code\n * (or is silently dropped in sloppy mode, and throws in a module). The key's\n * provenance is irrelevant: `SegmentMatcher` writes a name straight off the\n * ROUTE TABLE, so `id` / `tab` / `page` are as exposed as `__proto__` (#1852),\n * and a name-based skip therefore cannot close it.\n *\n * `Object.defineProperty` CAN say it — it ignores the chain entirely — but it\n * measures ~100 ns per field against ~0 for a store, which is why #1852 priced\n * it as unaffordable on a path that runs per navigation and per `<Link>`\n * render.\n *\n * So the write is guarded rather than replaced: **ask the chain first, and pay\n * only where it answers.** In a pristine environment `in` answers `false` for\n * every name an application routes under, so the store is taken and nothing is\n * paid. It covers both halves of the hazard, which a `__proto__` name test does\n * not: an accessor (getter-only THROWS, getter+setter silently diverts the\n * value) and a **non-writable** data property. Verified on all four shapes plus\n * the overwrite cases.\n *\n * ⚠ It asks `key in target`, NOT `key in Object.prototype`, and the difference\n * is the whole robustness of the primitive rather than a style choice. The\n * cheaper form is right only while every target is a fresh `{}`, i.e. while its\n * chain IS `Object.prototype` — measured, a target inheriting the accessor from\n * anywhere else walks straight past that predicate and throws. Asking the\n * object\n * being written to cannot be wrong for any target. Measured cost of the\n * difference, measured when the two forms were compared directly: a wash on\n * every arc, bought for a predicate with no precondition. ⚠ Those figures\n * predate both the `!hasOwn` term and the restored channel skips, and the\n * number\n * that supersedes them is below — the whole guard sits under the noise floor,\n * so\n * the choice between the two predicates cannot be visible in it.\n *\n * ⚑ **`&& !hasOwn`, and that second term is not an optimisation — it is what\n * keeps this a guarded WRITE instead of a redefinition.** When the key is\n * already an OWN property of the target, `[[Set]]` finds it and never consults\n * the chain, so a plain store is both safe AND semantically right there.\n * `defineProperty` is not: it replaces the whole DESCRIPTOR with this\n * function's\n * fixed one, and three consequences of that were measured before the term was\n * added.\n *\n * - It **throws where a plain store works**: a `configurable: false` own key\n * (a sealed target, an array's `length`) refuses `defineProperty` while\n * accepting an assignment.\n * - It **silently unlocks**: an own `writable: false` key was overwritten and\n * came back writable, and an own `enumerable: false` key came back\n * enumerable — a \"guarded write\" that also removes the guard.\n * - It **changed a shipped shape**, which is how this was caught rather than\n * reasoned about. `RouterError`'s own `stack` is a non-enumerable accessor;\n * `wrapSyncError` passes `stack` through here, so every error built from a\n * thrown one gained an own enumerable `stack`. `Object.keys(err)` changed,\n * and two errors differing only in stack stopped comparing equal under\n * `isDeepStrictEqual` / `toEqual`. The two arms of `rethrowAsRouterError`\n * disagreed with each other, because one of them assigns.\n *\n * `in` answers `false` for a fresh bag's new key and short-circuits, so\n * `hasOwn`\n * runs only on the rare branch it disambiguates. ⚠ That short-circuit is why an\n * earlier revision called the hot path \"untouched\"; it is not — one dictionary\n * lookup per written field is the price, and it is measured below.\n *\n * ⚠ The alternative that looks equivalent and is not: a prototype-less target.\n * It also closes the axis, and it costs far MORE, because the price is not on\n * the write at all — V8 puts such an object in dictionary mode, so every later\n * READ of the bag pays. Re-measured on the SHIPPED tree rather than carried\n * over from an earlier one: `buildPath` goes **+65.4 %** (one path slot) and\n * **+36.2 %** (slot + query). `{ __proto__: null }` as a literal is no better\n * (76 ns vs 70 ns for `Object.create(null)`, against 7.5 ns plain).\n *\n * ⚑ **The guard costs, and two earlier revisions of this docblock denied it.**\n * The last one said \"NOT MEASURABLE\" on medians-of-five whose A/A floors were\n * 5-6 %; on a quiet machine this harness floors at 0.1-1.7 %, and at that\n * resolution the cost is plain. Same-session A/B, ALTERNATING PROCESSES (two\n * copies of the module in one process is not a valid A/B), medians of 20 pairs,\n * against the SHIPPED bundle rather than `src`, each arc's own A/A floor in\n * brackets:\n *\n * buildPath, splat param 232.4 -> 260.3 ns +12.0 % (0.7 %)\n * isActiveRoute, exact 117.5 -> 125.4 ns +6.8 % (0.1 %)\n * matchPath, path params 664.0 -> 693.8 ns +4.5 % (0.8 %)\n * buildPath, static 97.5 -> 99.2 ns +1.7 % (1.7 %)\n * buildPath, one path slot 145.0 -> 140.5 ns -3.1 % (1.0 %)\n * isActiveRoute, sibling 38.4 -> 38.3 ns -0.3 % (0.3 %)\n *\n * Isolated by building the tree with the predicate replaced by `false`: it is\n * worth -6.1 % on the splat arc and -7.5 % on the exact one, i.e. the whole of\n * the regression there; the rest of `matchPath`'s is `withoutUnsafeKey`\n * (#1904), -2.1 %.\n *\n * ⚠ The old claim was less a bad measurement than a measurement of the WRONG\n * ARCS. `warm-params` and the sibling arm genuinely do not move — those are the\n * two it sampled — while the splat and exact arms do. Sampling what does not\n * move and generalising to \"not measurable\" is the same trap the reachability\n * arguments elsewhere in this file are written against.\n *\n * The price is ACCEPTED, deliberately, and three cheaper forms were measured\n * and rejected before accepting it:\n *\n * - asking a captured `Object.prototype` instead of the target, so the `in`\n * receiver is monomorphic: every arc inside the A/A floor. The cost is the\n * dictionary lookup, not who is asked.\n * - a prototype-less accumulator in `normalizeChannel` published through\n * `publishRecord`: **+134 % … +284 %** — the dictionary-mode price above,\n * now measured end to end rather than argued.\n * - an optimistic plain store repaired afterwards (`hasOwn` + `try`/`catch`):\n * -3.5 % and -2.8 % on two arcs but **+8.3 %** on a third, and it re-opens\n * the descriptor question `&& !hasOwn(target, key)` exists to close.\n *\n * ⚠ **CodSpeed reports this change at -13.83 %, and that is not the shipped\n * cost.** The gap is measured, not assumed. The suite runs\n * `tsx tests/benchmarks/run.ts` — against `src`, unbundled — so its flamegraph\n * carries ESM module-namespace getter frames (`get (ingest.ts)`, 2.67 % of one\n * arc) that the bundle does not have: `grep -c 'get: ()' dist/esm/index.mjs` is\n * 0. `Simulation` mode additionally over-counts instructions a superscalar CPU\n * hides. On the worst-reported arc the sign inverts — -17.25 % simulated,\n * -3.1 % (i.e. FASTER) in the bundle.\n *\n * A prototype-less channel additionally changes a PUBLISHED shape:\n * `state.params` would stop inheriting from `Object.prototype`, which reds\n * **352 tests in 17 packages**, none of them for a behavioural reason.\n *\n * ⚠ That count was published as \"263 in 15\" and is a RE-MEASUREMENT, not a\n * drift: the first figure came from running the affected packages one at a time\n * partway through the change, and both halves of it were low. A full-monorepo\n * run (10 553 tests) gives 352/17 for a prototype-less channel including the\n * `EMPTY_PARAMS` / `EMPTY_SEARCH` singletons, and 286/17 for the accumulators\n * alone — the package count is 17 either way, so it was never a question of\n * which sites to mutate.\n *\n * The qualitative half held up and is the load-bearing one: all 352 are\n * `AssertionError`, zero are thrown; 336 are `toStrictEqual` and 16 are\n * explicit\n * prototype pins; and NO `toEqual` / `toMatchObject` cell moved, which is the\n * internal control that only the prototype axis shifted.\n *\n * ⚑ `defineProperty` also makes `__proto__` an ordinary own key rather than a\n * write that swaps the target's prototype — which is why the `claim.write`\n * (#1191), `assignParam` (#855) and custom-field (#1788) special cases could be\n * replaced by this one primitive instead of kept beside it.\n *\n * ⚠ **It does NOT decide whether that key is PUBLISHED, and the two questions\n * were briefly conflated here.** The channel copy sites in `helpers.ts` still\n * drop `__proto__` before it reaches `state.params` / `state.search`, and that\n * skip is orthogonal to this primitive: a bag core hands BACK carrying the key\n * is a prototype-swap primitive for any consumer that merges it with\n * `Object.assign` — measured, `?__proto__` alone yields `null` and\n * `?__proto__=1&__proto__=2` an array, and the inherited setter accepts both.\n * `getDependenciesApi.getAll()` deletes the same key for the same reason and in\n * those words. Where the record does NOT escape to a merging consumer — a\n * route's custom fields, a plugin's context namespace — the key stays as data,\n * which is what #1788 and #1191 are about.\n */\nexport function putField<V>(\n target: Record<string, V>,\n key: string,\n value: V,\n): void {\n if (key in target && !hasOwn(target, key)) {\n defineProperty(target, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n target[key] = value;\n }\n}\n\n/**\n * {@link putField} for a whole source record — what `Object.assign` would do,\n * without the hazard.\n *\n * ⚑ It exists because `Object.assign` IS the hazard, written in a form a census\n * keyed on `dst[key] = value` cannot see. It copies with `[[Set]]`, one key at\n * a\n * time, so every argument in {@link putField}'s docblock applies to it verbatim\n * — and it is the reason this class needed a second look after the obvious\n * sweep: the matcher's junction walk builds `childParams` with a computed-key\n * literal (safe: that DEFINES) and then commits it with `Object.assign` (not).\n * Measured with an ambient setter under a route's own param name, the route\n * still MATCHED and `state.params` came back empty — the URL's parameter gone,\n * with no error anywhere.\n *\n * `Object.entries` for the walk: it hands back the value it already read, so\n * there is exactly ONE read per key and no window for a drifting accessor\n * between the test and the use (#1899). It is also the idiom the sibling copy\n * loops use.\n *\n * ⚠ **Two things it does NOT buy, both measured after an earlier revision of\n * this docblock claimed them.**\n *\n * - It is **not** a filter against a lying Proxy source. `ownKeys` is asked\n * first, so a key that list does not contain cannot appear — but a source\n * whose `ownKeys` DOES name a phantom and whose descriptor trap calls it\n * enumerable gets that phantom copied, identically to `Object.assign`. The\n * #1854 protection is narrower than \"the trap is never consulted\".\n * - It is **not** a drop-in for `Object.assign`. `Object.entries` is\n * string-keyed, so own enumerable SYMBOL entries are dropped where\n * `Object.assign` copies them. That matches core's stated policy for the\n * channels (\"symbols are dropped, always\") and is a real behaviour change at\n * the one call site that used to be an `Object.assign`\n * (`persistent-params`' factory). ⚠ It also disagrees with `publishRecord`\n * two functions up, which spreads and therefore keeps symbols — the same\n * internal split `helpers.ts` records as the #1792 defect.\n */\nexport function copyFields<V>(\n target: Record<string, V>,\n source: Record<string, V>,\n): void {\n for (const [key, value] of objectEntries(source)) {\n putField(target, key, value);\n }\n}\n"],"mappings":"AA0BA,MAAa,EAAkC,OAAO,OAAO,CAC3D,mBAAoB,cACpB,uBAAwB,yBACxB,uBAAwB,kBACxB,gBAAiB,kBACjB,YAAa,cACb,kBAAmB,oBACnB,gBAAiB,kBACjB,eAAgB,iBAChB,qBAAsB,YACtB,gBAAiB,WACjB,gBAAiB,kBACjB,kCAAmC,oCACnC,qBAAsB,uBACtB,wBAAyB,0BACzB,mBAAoB,cACpB,cAAe,eACjB,CAAC,EAMY,EAAgB,yBAkGhB,EAAa,YAEb,EAAuB,OAAO,OAAO,CAChD,eACF,CAAC,EAMY,EAA4B,OAAO,OAAO,CACrD,aAAc,UACd,YAAa,SACb,iBAAkB,oBAClB,yBAA0B,2BAC1B,kBAAmB,qBACnB,mBAAoB,sBACpB,iBAAkB,mBACpB,CAAC,EAMY,EAAyB,OAAO,OAAO,CAClD,aAAc,SACd,YAAa,QACb,iBAAkB,UAClB,yBAA0B,iBAC1B,kBAAmB,WACnB,mBAAoB,YACpB,iBAAkB,SACpB,CAAC,EAEY,EAAiB,OAAO,OAAO,CAC1C,gBAAiB,IACjB,WAAY,GACZ,aAAc,IACd,cAAe,IACf,qBAAsB,GACxB,CAAU,EAEG,EAAgD,OAAO,OAAO,CAAC,CAAC,EAQhE,EAAgD,OAAO,OAAO,CAAC,CAAC,EAWhE,EAA8C,OAAO,OAAO,CAAC,CAAC,EAErE,EAAwB,OAAO,OAAO,CAC1C,YAAa,OAAO,OAAO,CAAC,CAAC,EAC7B,UAAW,OAAO,OAAO,CAAC,CAAC,EAC3B,aAAc,EAChB,CAAC,EAEY,EAAqB,OAAO,OAAO,CAC9C,MAAO,aACP,OAAQ,UACR,SAAU,CACZ,CAAC,EC3KK,EAAgB,OAAO,QAkB7B,SAAgB,GAAoC,CAClD,OAAO,OAAO,OAAO,IAAI,CAC3B,CAyBA,SAAgB,EAAiB,EAA8C,CAC7E,MAAO,CAAE,GAAG,CAAO,CACrB,CAQA,MAAM,EAAiB,OAAO,eACxB,EAAS,OAAO,OA6CtB,SAAgB,EACd,EACmB,CAYnB,OAXK,EAAO,EAAA,WAAkB,GAI9B,EAAe,EAAQ,EAAY,CACjC,MAAO,EAAO,GACd,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EARQ,CAWX,CAwKA,SAAgB,EACd,EACA,EACA,EACM,CACF,KAAO,GAAU,CAAC,EAAO,EAAQ,CAAG,EACtC,EAAe,EAAQ,EAAK,CAC1B,QACA,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAED,EAAO,GAAO,CAElB,CAuCA,SAAgB,EACd,EACA,EACM,CACN,IAAK,GAAM,CAAC,EAAK,KAAU,EAAc,CAAM,EAC7C,EAAS,EAAQ,EAAK,CAAK,CAE/B"}
|
|
1
|
+
{"version":3,"file":"ingest-DxGcWzr6.js","names":[],"sources":["../../src/constants.ts","../../src/utils/ingest.ts"],"sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n TransitionMeta,\n} from \"./types\";\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Readonly<Record<ConstantsKeys, string>>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n CONTEXT_NAMESPACE_ALREADY_CLAIMED: \"CONTEXT_NAMESPACE_ALREADY_CLAIMED\", // Plugin tried to claim a context namespace already owned by another plugin\n REENTRANT_NAVIGATION: \"REENTRANT_NAVIGATION\", // navigate() called synchronously from inside a transition-event listener (banned — use await/async listener)\n REENTRANT_TREE_MUTATION: \"REENTRANT_TREE_MUTATION\", // a tree mutator — route-CRUD or setRootPath (#1751) — called synchronously from inside a subscribeChanges handler (banned — use await/async/queueMicrotask)\n ROUTER_NOT_STOPPED: \"NOT_STOPPED\", // clear() called while a state is committed — tear down with stop() first, or swap the tree with replace() (#1612)\n WRONG_CHANNEL: \"WRONG_CHANNEL\", // a declared query key was supplied in the path channel (`params`) instead of `search` (#1572)\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\n/**\n * The one key the router will not copy into a state channel (#1792), and — at\n * `getDependenciesApi.getAll` — will not hand back out of a container either.\n *\n * ⚠ It does not REFUSE it — nothing throws, at any door or at registration; the\n * key is dropped where core copies into a CHANNEL, and kept everywhere else.\n * `claim.write` (#1191) and the route-record merge (#1788) keep it on purpose:\n * a plugin's context namespace and a route's custom fields are not containers a\n * consumer merges. ⚠ Neither of those spells the literal any more — both go\n * through `putField` (#1852), which keeps every name — so a `grep` for this\n * constant no longer finds the sites that carry the opposite contract.\n *\n * `__proto__` is the only ACCESSOR among `Object.prototype`'s twelve own\n * members, so `target[key] = value` for that one name reaches the inherited\n * setter: no own key is created, the value vanishes with no error and no log,\n * and an OBJECT value replaces the target's prototype instead.\n *\n * ⚠ That last sentence used to continue \"…therefore every idiom in core that\n * copies a foreign bag has to NAME it\", and that is no longer the mechanism.\n * `putField` (#1852) defines rather than assigns, so no copy loses the key by\n * accident any more; the five sites that still name it in `helpers.ts` do so to\n * DROP it deliberately, which is a different decision made for a different\n * reason — see below.\n *\n * ⚑ **What is guaranteed, precisely.** A bag that is ORDINARY — plain data that\n * does not change while the router is reading it — cannot put this key among the\n * OWN KEYS of `state.params` or `state.search`. The guarantee is one level deep,\n * and deliberately so: every copy here is `copy[key] = value`, so a value that is\n * itself an object is carried by REFERENCE. Put a bag inside a bag and the inner\n * one is still yours — unfrozen, and with whatever keys you gave it. That means\n * `Object.assign({}, state.search.inner)` can still swap a prototype and\n * `JSON.stringify(getState())` can still carry the name, one level down. Copying\n * deeper would put an unbounded walk on every commit, and the router does not\n * know which of your values are structures and which are opaque handles. That covers the case the rule exists for: a\n * bag from `JSON.parse`, from `history.state`, from a query string an app parsed\n * itself. Entry-point checks cannot deliver even that much, because they read a\n * bag the router does not own and the copy happens later.\n *\n * ⚑ **What is NOT guaranteed, deliberately.** Nothing about a bag that CHANGES\n * while the router reads it — an accessor that rewrites its own object, a Proxy\n * answering differently per trap call. A router cannot defend an application\n * against its own code, and pretending otherwise buys discipline at a dozen\n * sites for a case only the caller can create. That one belongs to whoever\n * handed the bag over, and it is written down rather than defended against.\n *\n * ⚠ The guards below are written WITHOUT reachability arguments: \"it cannot get\n * here\" is a claim about an object the router does not own, and two such claims\n * have already been wrong. OWNERSHIP is a sound reason to omit a guard;\n * reachability is not.\n *\n * ⚑ **Why the CHANNELS drop it while everything else keeps it.** A bag core\n * hands back with an own `\"__proto__\"` is a prototype-swap primitive for any\n * consumer that merges it with `Object.assign` or a `for…in` copy — measured\n * from a bare URL, `?__proto__` parses to `null` and `?__proto__=1&__proto__=2`\n * to an array, and the inherited setter accepts both. `state.params` /\n * `state.search` are the most-merged containers the router publishes, so they\n * follow `getAll`'s rule rather than `claim.write`'s. ⚠ The data-preservation\n * argument for carrying it does not survive contact with a consumer either:\n * `Object.assign` drops the key even in the safe string case, so \"the user's\n * `?__proto__=1` is kept\" holds for exactly one hop.\n *\n * ⚠ The former \"two copies in core do NOT name it\" note is retired: both\n * `channels/modeGate.ts` and `channels/defaults.ts` name it now, and the\n * open exception recorded against the second is closed. It was recorded as an\n * exception rather than a justification precisely so it could not be forgotten,\n * and that worked.\n *\n * ⚑ A THIRD sound exemption, and the only one besides ownership: the TARGET is\n * `Object.create(null)`. There is no inherited setter to dispatch into, so the\n * key lands as an ordinary own property and no guard is needed on the way in.\n * The dependency store is the live case (`dependenciesStore.ts`,\n * `getDependenciesApi.setAll`) — both copy a caller-owned bag and neither names\n * `UNSAFE_KEY`, deliberately. It is also why `getAll` is this constant's other\n * consumer: the key is admitted on the way IN and withheld on the way OUT,\n * because that door hands back a normal object someone will merge.\n *\n * ⚑ **That last sentence is a RULE, and `getAll` is no longer its only case\n * (#1957).** Every door that hands back a container core built withholds the key\n * — router options (and with them the clone transport, one object), the\n * dependency clone transport, and the two `NavigationOptions` a plugin hook\n * receives that core MINTS. `dropUnsafeKey` (`helpers.ts`) is the one primitive;\n * the derived table is\n * `tests/functional/handed-out-containers-1957.test.ts`.\n *\n * ⚠ There is a SECOND shape, for the one container core hands out AND reads\n * back by key: the route-meta record is withheld from ENUMERATION instead\n * (`concealUnsafeKey`, `utils/ingest.ts`), because deleting the entry sends\n * core's own read to the inherited accessor and a route named `__proto__` stops\n * re-activating on a param change — measured.\n *\n * ⚠ Four doors stay EXEMPT, each with a measured reason in that table: the two\n * prior owner decisions (`state.context` #1191, a route's custom fields #1788),\n * the PASS-THROUGH where the container is the caller's own object (the un-forced\n * `NavigationOptions` arc), and the internals handle.\n *\n * ⚑ **A PASS-THROUGH is exempt by default and loses that when the door is\n * INTERCEPTABLE (#1986).** Core mints nothing there — on its no-default fast\n * path `forwardState` hands back the caller's own bags, identity intact — so the\n * rule above does not reach it. It is sanitised anyway, because the door is an\n * extension seam whose documented idiom merges the result: core would be handing\n * a swap primitive to a plugin author who followed the instructions. Every LINK\n * of the chain counts as such a hand-out, not only the door — what one\n * interceptor returns is what the next one merges — so the `next` each hop\n * receives is wrapped as well.\n * `withoutUnsafeKey`'s `hasOwn` gate is what makes it affordable — a clean bag\n * comes back by identity, no allocation.\n *\n * ⚠ The sibling arc is NOT sanitised, and the asymmetry is measured rather than\n * stylistic: copying the plain `NavigationOptions` bag reads `reload` and\n * `replace` a SECOND time, below the read that already decided, and\n * `opts-read-once-1817.test.ts` counts exactly those and pins them at one.\n *\n * ⚑ **The internals handle is out of the rule's scope permanently, and it is a\n * fourth sound exemption rather than an unfixed door (#1986).** The rule governs\n * a container core builds TO HAND OUT; that handle hands out core's LIVE stores,\n * which exist for core's own use and would be there with no consumer at all.\n * Three independent reasons, any one sufficient:\n *\n * - Withholding would take the key from the ROUTER, not from a consumer.\n * `set(\"__proto__\", v)` is a supported call whose `has` / `get` answer, and\n * `routeCustomFields` is keyed by ROUTE NAME, where core accepts a route named\n * `__proto__` (#1801) — so the \"poison\" is that route's real config.\n * - The pairing already exists and is the shape the rule prescribes: the key is\n * admitted on the way IN (the destination is `Object.create(null)`, the third\n * sound exemption above) and withheld on the way OUT, by `getAll`. The handle\n * is not a way out.\n * - A holder of the handle writes into that live state directly, so protecting\n * them from a prototype swap on merge is not a coherent goal.\n *\n * Closing it would take a NEW door (a copying `snapshot()`, leaving the handle\n * for core) — new public surface for one key — rather than a withholding.\n */\nexport const UNSAFE_KEY = \"__proto__\";\n\nexport const constants: Constants = Object.freeze({\n UNKNOWN_ROUTE,\n});\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = Object.freeze({\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_LEAVE_APPROVE: \"onTransitionLeaveApprove\", // Plugin method called when deactivation guards pass\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n});\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = Object.freeze({\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_LEAVE_APPROVE: \"$$leaveApprove\", // Emitted when deactivation guards pass\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n});\n\nexport const DEFAULT_LIMITS = Object.freeze({\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxLifecycleHandlers: 200,\n} as const);\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty query bag reused for `State.search` when a navigation\n * carries no query params — the search-channel twin of {@link EMPTY_PARAMS}\n * (RFC-4 M2 / #1548). Lets `makeState` reuse one frozen `{}` (zero transient\n * allocation, #1027) instead of minting an object per query-less state.\n */\nexport const EMPTY_SEARCH: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty `NavigationOptions`, substituted by the facade when a\n * caller passes none — the options-channel twin of {@link EMPTY_PARAMS}.\n *\n * ⚑ It lives here rather than in `Router.ts` so the entry door can recognise it\n * by IDENTITY (#1962). `navigate(\"b\")` is the commonest call in the library, and\n * matching this singleton is what keeps the door's cost on it to one comparison\n * instead of a copy nobody asked for.\n */\nexport const EMPTY_OPTS: Readonly<Record<string, never>> = Object.freeze({});\n\nconst FROZEN_EMPTY_SEGMENTS = Object.freeze({\n deactivated: Object.freeze([]) as unknown as string[],\n activated: Object.freeze([]) as unknown as string[],\n intersection: \"\",\n});\n\nexport const DEFAULT_TRANSITION = Object.freeze({\n phase: \"activating\",\n reason: \"success\",\n segments: FROZEN_EMPTY_SEGMENTS,\n}) as TransitionMeta;\n","// packages/core/src/utils/ingest.ts\n//\n// One discipline for the records core BUILDS under a key it did not CHOOSE.\n//\n// Two halves, and they answer different questions — a reader who takes them for\n// one primitive will draw the wrong conclusion from either:\n//\n// `emptyRecord` / `publishRecord` (#1825) — a record with no prototype for the\n// BUILD, handed out plain. Used where the record is core's alone:\n// `buildParamMeta`, the segment-meta walk.\n// `putField` / `copyFields` (#1852) — a guarded WRITE for the records that\n// cannot be prototype-less because they are published, read on every render,\n// or belong to someone else. Used across core and, through\n// `@real-router/core/utils`, by four plugins.\n// ⚠ The site COUNTS deliberately do not live here. This comment carried\n// \"twenty-one in core, fourteen across four plugins\" and both halves were\n// wrong (22 and 13, measured) — a second copy of a number `CLAUDE.md`\n// already calls descriptive-not-contract. The count lives in `CLAUDE.md`\n// (\"The WRITE side of the same rule\"); the CONTRACT is the derived set in\n// `tests/functional/computed-key-write-authority-1852.test.ts`.\n//\n// ⚠ Neither decides whether a key is PUBLISHED. `__proto__` stays out of\n// `state.params` / `state.search` by a separate skip at the channel copy sites\n// in `helpers.ts`, and stays IN a route's custom fields and a plugin's context\n// namespace, because those are not containers a consumer merges. See `putField`'s\n// docblock for that split.\n//\n// `concealUnsafeKey` (#1957) is the one member of this file that DOES decide\n// that — for exactly one record, `buildMeta`'s, which core both hands out\n// and reads back by key. It withholds the name from ENUMERATION rather than\n// removing it, because removing it is a measured behaviour loss there. The\n// doors that only hand a container OUT drop the key instead\n// (`dropUnsafeKey`, `helpers.ts`).\n//\n// ⚠ The rest are WRITE-side primitives only, and the boundary is deliberate. A\n// READ-side primitive that walks a caller's prototype chain was written here,\n// wired, measured — and removed: `CLAUDE.md` \"Supported Input Shapes\" settles\n// that axis already (\"own enumerable properties only\", owner decision\n// 2026-08-18), and core is the layer that DEGRADES on a violation while\n// `@real-router/validation-plugin` is the layer that reports it. A primitive\n// that honoured inherited keys would have made core contradict its own canon,\n// and it additionally admitted the ambient `Object.prototype` — the #1840\n// class, introduced by the fix.\n//\n// So what is left is the half the canon does not cover: what happens when core\n// writes into a record of its own under a key it did not choose.\n\nimport { UNSAFE_KEY } from \"../constants\";\n\nconst objectEntries = Object.entries;\n\n/**\n * The target discipline: a record with NO prototype.\n *\n * ⚑ This one line closes two axes at once, which is why it is a primitive and\n * not an idiom. #1856 tabulates them as a structural trade — a key-by-key copy\n * fixes `\"__proto__\"` but turns a `[[DefineOwnProperty]]` into a `[[Set]]`, so\n * an ambient accessor starts throwing — and calls the conflict unavoidable. It\n * is unavoidable only while the target inherits from `Object.prototype`:\n *\n * - `\"__proto__\"` (#1825, #1794, #1809) is an ordinary key here, because the\n * magic accessor lives on `Object.prototype` and this object has none.\n * - an ambient accessor named `id` / `page` / `tab` (#1852) cannot hijack the\n * write for the same reason. #1852 notes the key's provenance is\n * irrelevant — `SegmentMatcher` writes a name from the ROUTE TABLE and\n * throws just the same — so a name-based skip cannot close it and this can.\n */\nexport function emptyRecord<V>(): Record<string, V> {\n return Object.create(null) as Record<string, V>;\n}\n\n/**\n * Hand a privately-built record out with the ORDINARY prototype, keeping every\n * own key — including a literal `\"__proto__\"`.\n *\n * Discovered by measurement, not designed: wiring `emptyRecord` into\n * `buildParamMeta` alone reds **21** existing tests, all of the shape\n * `expected { id: 'url' } to strictly equal { id: 'url' }` — identical content,\n * different prototype, because `toStrictEqual` compares prototypes and\n * `paramTypeMap` is published through `getPluginApi(router).getTree()`. A\n * prototype-less record is not a drop-in at a published surface.\n *\n * The spread is what makes this work rather than undo it: it\n * `[[DefineOwnProperty]]`s, so an own `\"__proto__\"` carried on the private\n * record lands as an ordinary own key here (measured: own keys\n * `[\"__proto__\",\"keep\"]`, value intact, prototype back to `Object.prototype`).\n * Writing that same key into a fresh `{}` with `[[Set]]` loses it entirely\n * (measured: own keys `[]`) — which is the defect the private record exists to\n * avoid.\n *\n * So the rule is: **build private, publish plain.** The window in which the\n * ambient-accessor hazard (#1852) could bite is the build, and the build never\n * touches `Object.prototype`.\n */\nexport function publishRecord<V>(source: Record<string, V>): Record<string, V> {\n return { ...source };\n}\n\n/**\n * Captured at module load for the reason `helpers.ts` gives for `freeze` /\n * `hasOwn` / `objectKeys`: this is the operation {@link putField} writes\n * through, so a guard reading it late would be reading whatever an application\n * had re-pointed it to.\n */\nconst defineProperty = Object.defineProperty;\nconst hasOwn = Object.hasOwn;\n\n/**\n * Withhold `UNSAFE_KEY` from ENUMERATION on a record core hands out AND reads\n * back by key (#1957).\n *\n * ⚑ The hazard is the CONSUMER's merge, not core's own write. `Object.assign`\n * and a `for…in` copy `[[Set]]` each own ENUMERABLE key on the TARGET, where\n * `Object.prototype`'s `\"__proto__\"` accessor replaces that target's prototype\n * instead of adding an entry.\n *\n * ⚠ A SPREAD is not in that list, and an earlier revision of this docblock said\n * it was. `{ ...source }` performs `CreateDataProperty`, i.e.\n * `[[DefineOwnProperty]]`, which never reaches an inherited accessor — measured\n * on the poisoned bag, on a null-prototype carrier and through a pass-through\n * Proxy, a spread swaps in none of the three. #1823 had the list right\n * (\"`Object.assign` or a `for…in` copy\") and this widened it by mistake. The\n * hazard is real and narrower than that sentence claimed.\n *\n * So the SOURCE's own prototype decides nothing either — measured, an\n * `Object.create(null)` source swaps the target exactly the same — and the only\n * two fixes are removing the key or removing it from enumeration.\n *\n * ⚠ **Dropping is not a milder fix here, it is a WRONG one.** The route-meta\n * record is core's working table: `segmentParamsEqual` reads `meta[segmentName]`\n * on every navigation, so with the entry gone the read reaches the INHERITED\n * accessor and answers `Object.prototype` — an object, whose `Object.keys` is\n * `[]`, so the segment reports \"params unchanged\". Measured end to end on a\n * route named `__proto__`: `/p/1` → `/p/2` activates `[\"__proto__\"]` today and\n * `[]` with the entry deleted. Core accepts that name (#1801), so the loss is\n * real and silent.\n *\n * Non-enumerable keeps the read exact for core AND for a consumer asking by\n * key, while `Object.assign` / a spread / `for…in` skip it — measured, all\n * three.\n *\n * ⚠ NOT applied by {@link publishRecord} itself. Its other caller is\n * `buildParamMeta`, whose map core ENUMERATES (`Object.keys` in\n * `segmentParamsEqual`, `for…in` in `hasAnyParam`) and which is not a swap\n * primitive anyway: a param's value is the string `\"url\"` / `\"query\"`, and the\n * inherited setter ignores primitives.\n *\n * Returns the input untouched, with no descriptor write, when the key is absent\n * — which is every ordinary route.\n */\nexport function concealUnsafeKey<V>(\n record: Record<string, V>,\n): Record<string, V> {\n if (!hasOwn(record, UNSAFE_KEY)) {\n return record;\n }\n\n defineProperty(record, UNSAFE_KEY, {\n value: record[UNSAFE_KEY],\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n return record;\n}\n\n/**\n * Write one field of a record core BUILDS under a key it did not choose.\n *\n * ⚑ The rule this exists to enforce: **a caller's object contributes DATA, and\n * nothing else.** No trap, no accessor, no inherited member of a bag handed to\n * the router may change what the router ends up holding — which is what\n * \"treat it as a pure dictionary\" means on the WRITE side. `Object.keys` and\n * the one-read-per-key discipline (#1854 / #1899) already say it on the read\n * side; this is the other half.\n *\n * Plain `target[key] = value` cannot say it. `[[Set]]` walks the prototype\n * chain first, so a key that resolves to an accessor or a non-writable data\n * property up there is HIJACKED — the write dispatches into application code\n * (or is silently dropped in sloppy mode, and throws in a module). The key's\n * provenance is irrelevant: `SegmentMatcher` writes a name straight off the\n * ROUTE TABLE, so `id` / `tab` / `page` are as exposed as `__proto__` (#1852),\n * and a name-based skip therefore cannot close it.\n *\n * `Object.defineProperty` CAN say it — it ignores the chain entirely — but it\n * measures ~100 ns per field against ~0 for a store, which is why #1852 priced\n * it as unaffordable on a path that runs per navigation and per `<Link>`\n * render.\n *\n * So the write is guarded rather than replaced: **ask the chain first, and pay\n * only where it answers.** In a pristine environment `in` answers `false` for\n * every name an application routes under, so the store is taken and nothing is\n * paid. It covers both halves of the hazard, which a `__proto__` name test does\n * not: an accessor (getter-only THROWS, getter+setter silently diverts the\n * value) and a **non-writable** data property. Verified on all four shapes plus\n * the overwrite cases.\n *\n * ⚠ It asks `key in target`, NOT `key in Object.prototype`, and the difference\n * is the whole robustness of the primitive rather than a style choice. The\n * cheaper form is right only while every target is a fresh `{}`, i.e. while its\n * chain IS `Object.prototype` — measured, a target inheriting the accessor from\n * anywhere else walks straight past that predicate and throws. Asking the\n * object\n * being written to cannot be wrong for any target. Measured cost of the\n * difference, measured when the two forms were compared directly: a wash on\n * every arc, bought for a predicate with no precondition. ⚠ Those figures\n * predate both the `!hasOwn` term and the restored channel skips, and the\n * number\n * that supersedes them is below — the whole guard sits under the noise floor,\n * so\n * the choice between the two predicates cannot be visible in it.\n *\n * ⚑ **`&& !hasOwn`, and that second term is not an optimisation — it is what\n * keeps this a guarded WRITE instead of a redefinition.** When the key is\n * already an OWN property of the target, `[[Set]]` finds it and never consults\n * the chain, so a plain store is both safe AND semantically right there.\n * `defineProperty` is not: it replaces the whole DESCRIPTOR with this\n * function's\n * fixed one, and three consequences of that were measured before the term was\n * added.\n *\n * - It **throws where a plain store works**: a `configurable: false` own key\n * (a sealed target, an array's `length`) refuses `defineProperty` while\n * accepting an assignment.\n * - It **silently unlocks**: an own `writable: false` key was overwritten and\n * came back writable, and an own `enumerable: false` key came back\n * enumerable — a \"guarded write\" that also removes the guard.\n * - It **changed a shipped shape**, which is how this was caught rather than\n * reasoned about. `RouterError`'s own `stack` is a non-enumerable accessor;\n * `wrapSyncError` passes `stack` through here, so every error built from a\n * thrown one gained an own enumerable `stack`. `Object.keys(err)` changed,\n * and two errors differing only in stack stopped comparing equal under\n * `isDeepStrictEqual` / `toEqual`. The two arms of `rethrowAsRouterError`\n * disagreed with each other, because one of them assigns.\n *\n * `in` answers `false` for a fresh bag's new key and short-circuits, so\n * `hasOwn`\n * runs only on the rare branch it disambiguates. ⚠ That short-circuit is why an\n * earlier revision called the hot path \"untouched\"; it is not — one dictionary\n * lookup per written field is the price, and it is measured below.\n *\n * ⚠ The alternative that looks equivalent and is not: a prototype-less target.\n * It also closes the axis, and it costs far MORE, because the price is not on\n * the write at all — V8 puts such an object in dictionary mode, so every later\n * READ of the bag pays. Re-measured on the SHIPPED tree rather than carried\n * over from an earlier one: `buildPath` goes **+65.4 %** (one path slot) and\n * **+36.2 %** (slot + query). `{ __proto__: null }` as a literal is no better\n * (76 ns vs 70 ns for `Object.create(null)`, against 7.5 ns plain).\n *\n * ⚑ **The guard costs, and two earlier revisions of this docblock denied it.**\n * The last one said \"NOT MEASURABLE\" on medians-of-five whose A/A floors were\n * 5-6 %; on a quiet machine this harness floors at 0.1-1.7 %, and at that\n * resolution the cost is plain. Same-session A/B, ALTERNATING PROCESSES (two\n * copies of the module in one process is not a valid A/B), medians of 20 pairs,\n * against the SHIPPED bundle rather than `src`, each arc's own A/A floor in\n * brackets:\n *\n * buildPath, splat param 232.4 -> 260.3 ns +12.0 % (0.7 %)\n * isActiveRoute, exact 117.5 -> 125.4 ns +6.8 % (0.1 %)\n * matchPath, path params 664.0 -> 693.8 ns +4.5 % (0.8 %)\n * buildPath, static 97.5 -> 99.2 ns +1.7 % (1.7 %)\n * buildPath, one path slot 145.0 -> 140.5 ns -3.1 % (1.0 %)\n * isActiveRoute, sibling 38.4 -> 38.3 ns -0.3 % (0.3 %)\n *\n * Isolated by building the tree with the predicate replaced by `false`: it is\n * worth -6.1 % on the splat arc and -7.5 % on the exact one, i.e. the whole of\n * the regression there; the rest of `matchPath`'s is `withoutUnsafeKey`\n * (#1904), -2.1 %.\n *\n * ⚠ The old claim was less a bad measurement than a measurement of the WRONG\n * ARCS. `warm-params` and the sibling arm genuinely do not move — those are the\n * two it sampled — while the splat and exact arms do. Sampling what does not\n * move and generalising to \"not measurable\" is the same trap the reachability\n * arguments elsewhere in this file are written against.\n *\n * The price is ACCEPTED, deliberately, and three cheaper forms were measured\n * and rejected before accepting it:\n *\n * - asking a captured `Object.prototype` instead of the target, so the `in`\n * receiver is monomorphic: every arc inside the A/A floor. The cost is the\n * dictionary lookup, not who is asked.\n * - a prototype-less accumulator in `normalizeChannel` published through\n * `publishRecord`: **+134 % … +284 %** — the dictionary-mode price above,\n * now measured end to end rather than argued.\n * - an optimistic plain store repaired afterwards (`hasOwn` + `try`/`catch`):\n * -3.5 % and -2.8 % on two arcs but **+8.3 %** on a third, and it re-opens\n * the descriptor question `&& !hasOwn(target, key)` exists to close.\n *\n * ⚠ **CodSpeed reports this change at -13.83 %, and that is not the shipped\n * cost.** The gap is measured, not assumed. The suite runs\n * `tsx tests/benchmarks/run.ts` — against `src`, unbundled — so its flamegraph\n * carries ESM module-namespace getter frames (`get (ingest.ts)`, 2.67 % of one\n * arc) that the bundle does not have: `grep -c 'get: ()' dist/esm/index.mjs` is\n * 0. `Simulation` mode additionally over-counts instructions a superscalar CPU\n * hides. On the worst-reported arc the sign inverts — -17.25 % simulated,\n * -3.1 % (i.e. FASTER) in the bundle.\n *\n * A prototype-less channel additionally changes a PUBLISHED shape:\n * `state.params` would stop inheriting from `Object.prototype`, which reds\n * **352 tests in 17 packages**, none of them for a behavioural reason.\n *\n * ⚠ That count was published as \"263 in 15\" and is a RE-MEASUREMENT, not a\n * drift: the first figure came from running the affected packages one at a time\n * partway through the change, and both halves of it were low. A full-monorepo\n * run (10 553 tests) gives 352/17 for a prototype-less channel including the\n * `EMPTY_PARAMS` / `EMPTY_SEARCH` singletons, and 286/17 for the accumulators\n * alone — the package count is 17 either way, so it was never a question of\n * which sites to mutate.\n *\n * The qualitative half held up and is the load-bearing one: all 352 are\n * `AssertionError`, zero are thrown; 336 are `toStrictEqual` and 16 are\n * explicit\n * prototype pins; and NO `toEqual` / `toMatchObject` cell moved, which is the\n * internal control that only the prototype axis shifted.\n *\n * ⚑ `defineProperty` also makes `__proto__` an ordinary own key rather than a\n * write that swaps the target's prototype — which is why the `claim.write`\n * (#1191), `assignParam` (#855) and custom-field (#1788) special cases could be\n * replaced by this one primitive instead of kept beside it.\n *\n * ⚠ **It does NOT decide whether that key is PUBLISHED, and the two questions\n * were briefly conflated here.** The channel copy sites in `helpers.ts` still\n * drop `__proto__` before it reaches `state.params` / `state.search`, and that\n * skip is orthogonal to this primitive: a bag core hands BACK carrying the key\n * is a prototype-swap primitive for any consumer that merges it with\n * `Object.assign` — measured, `?__proto__` alone yields `null` and\n * `?__proto__=1&__proto__=2` an array, and the inherited setter accepts both.\n * `getDependenciesApi.getAll()` deletes the same key for the same reason and in\n * those words. Where the record does NOT escape to a merging consumer — a\n * route's custom fields, a plugin's context namespace — the key stays as data,\n * which is what #1788 and #1191 are about.\n */\nexport function putField<V>(\n target: Record<string, V>,\n key: string,\n value: V,\n): void {\n if (key in target && !hasOwn(target, key)) {\n defineProperty(target, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n target[key] = value;\n }\n}\n\n/**\n * {@link putField} for a whole source record — what `Object.assign` would do,\n * without the hazard.\n *\n * ⚑ It exists because `Object.assign` IS the hazard, written in a form a census\n * keyed on `dst[key] = value` cannot see. It copies with `[[Set]]`, one key at\n * a\n * time, so every argument in {@link putField}'s docblock applies to it verbatim\n * — and it is the reason this class needed a second look after the obvious\n * sweep: the matcher's junction walk builds `childParams` with a computed-key\n * literal (safe: that DEFINES) and then commits it with `Object.assign` (not).\n * Measured with an ambient setter under a route's own param name, the route\n * still MATCHED and `state.params` came back empty — the URL's parameter gone,\n * with no error anywhere.\n *\n * `Object.entries` for the walk: it hands back the value it already read, so\n * there is exactly ONE read per key and no window for a drifting accessor\n * between the test and the use (#1899). It is also the idiom the sibling copy\n * loops use.\n *\n * ⚠ **Two things it does NOT buy, both measured after an earlier revision of\n * this docblock claimed them.**\n *\n * - It is **not** a filter against a lying Proxy source. `ownKeys` is asked\n * first, so a key that list does not contain cannot appear — but a source\n * whose `ownKeys` DOES name a phantom and whose descriptor trap calls it\n * enumerable gets that phantom copied, identically to `Object.assign`. The\n * #1854 protection is narrower than \"the trap is never consulted\".\n * - It is **not** a drop-in for `Object.assign`. `Object.entries` is\n * string-keyed, so own enumerable SYMBOL entries are dropped where\n * `Object.assign` copies them. That matches core's stated policy for the\n * channels (\"symbols are dropped, always\") and is a real behaviour change at\n * the one call site that used to be an `Object.assign`\n * (`persistent-params`' factory). ⚠ It also disagrees with `publishRecord`\n * two functions up, which spreads and therefore keeps symbols — the same\n * internal split `helpers.ts` records as the #1792 defect.\n */\nexport function copyFields<V>(\n target: Record<string, V>,\n source: Record<string, V>,\n): void {\n for (const [key, value] of objectEntries(source)) {\n putField(target, key, value);\n }\n}\n"],"mappings":"AA0BA,MAAa,EAAkC,OAAO,OAAO,CAC3D,mBAAoB,cACpB,uBAAwB,yBACxB,uBAAwB,kBACxB,gBAAiB,kBACjB,YAAa,cACb,kBAAmB,oBACnB,gBAAiB,kBACjB,eAAgB,iBAChB,qBAAsB,YACtB,gBAAiB,WACjB,gBAAiB,kBACjB,kCAAmC,oCACnC,qBAAsB,uBACtB,wBAAyB,0BACzB,mBAAoB,cACpB,cAAe,eACjB,CAAC,EAMY,EAAgB,yBAsIhB,EAAa,YAEb,EAAuB,OAAO,OAAO,CAChD,eACF,CAAC,EAMY,EAA4B,OAAO,OAAO,CACrD,aAAc,UACd,YAAa,SACb,iBAAkB,oBAClB,yBAA0B,2BAC1B,kBAAmB,qBACnB,mBAAoB,sBACpB,iBAAkB,mBACpB,CAAC,EAMY,EAAyB,OAAO,OAAO,CAClD,aAAc,SACd,YAAa,QACb,iBAAkB,UAClB,yBAA0B,iBAC1B,kBAAmB,WACnB,mBAAoB,YACpB,iBAAkB,SACpB,CAAC,EAEY,EAAiB,OAAO,OAAO,CAC1C,gBAAiB,IACjB,WAAY,GACZ,aAAc,IACd,cAAe,IACf,qBAAsB,GACxB,CAAU,EAEG,EAAgD,OAAO,OAAO,CAAC,CAAC,EAQhE,EAAgD,OAAO,OAAO,CAAC,CAAC,EAWhE,EAA8C,OAAO,OAAO,CAAC,CAAC,EAErE,EAAwB,OAAO,OAAO,CAC1C,YAAa,OAAO,OAAO,CAAC,CAAC,EAC7B,UAAW,OAAO,OAAO,CAAC,CAAC,EAC3B,aAAc,EAChB,CAAC,EAEY,EAAqB,OAAO,OAAO,CAC9C,MAAO,aACP,OAAQ,UACR,SAAU,CACZ,CAAC,EC/MK,EAAgB,OAAO,QAkB7B,SAAgB,GAAoC,CAClD,OAAO,OAAO,OAAO,IAAI,CAC3B,CAyBA,SAAgB,EAAiB,EAA8C,CAC7E,MAAO,CAAE,GAAG,CAAO,CACrB,CAQA,MAAM,EAAiB,OAAO,eACxB,EAAS,OAAO,OA6CtB,SAAgB,EACd,EACmB,CAYnB,OAXK,EAAO,EAAA,WAAkB,GAI9B,EAAe,EAAQ,EAAY,CACjC,MAAO,EAAO,GACd,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EARQ,CAWX,CAwKA,SAAgB,EACd,EACA,EACA,EACM,CACF,KAAO,GAAU,CAAC,EAAO,EAAQ,CAAG,EACtC,EAAe,EAAQ,EAAK,CAC1B,QACA,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAED,EAAO,GAAO,CAElB,CAuCA,SAAgB,EACd,EACA,EACM,CACN,IAAK,GAAM,CAAC,EAAK,KAAU,EAAc,CAAM,EAC7C,EAAS,EAAQ,EAAK,CAAK,CAE/B"}
|
package/dist/cjs/validation.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./buildParamMeta-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./buildParamMeta-C9Hfrxr9.js");function t(e,t){return TypeError(`[router.${e}] ${t}`)}function n(e,n,r,i){let a=new Set;for(let o of e){if(a.has(o))throw t(r,`Invalid path for route "${n}": duplicate parameter name ':${o}' in "${i}" (a param name must be unique within a route — the second binding would overwrite the first)`);a.add(o)}}function r(n,r,i,a){for(let o of n)if(e.n.test(o))throw t(i,`Invalid path for route "${r}": invalid query-param name "${o}" in "${a}" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`)}function i(e){let t=!0,n=!1;for(let r of e){if(r===`/`){t=!0;continue}if(t&&=(n=r===`:`||r===`*`,!1),!n&&r.codePointAt(0)>=128)return!0}return!1}function a(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 o(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 s(s,c,l,u){if(typeof s!=`string`){let e;throw e=s===null?`null`:Array.isArray(s)?`array`:typeof s,t(l,`Route path must be a string, got ${e}`)}if(s===``)return;if(/\s/.test(s))throw t(l,`Invalid path for route "${c}": whitespace not allowed in "${s}"`);if(!/^([/?~]|[^/]+$)/.test(s))throw t(l,`Route "${c}" has invalid path format: "${s}". Path should start with '/', '~', '?' or be a relative segment.`);if(s.includes(`//`))throw t(l,`Invalid path for route "${c}": double slashes not allowed in "${s}"`);let{pathPattern:d,urlParams:f,queryParams:p}=e.r(s);n(f,c,l,s),r(p,c,l,s);let m=e.i(d);if(m!==void 0)throw t(l,o(m,c));let h=e.a(d);if(h!==void 0)throw t(l,a(h,c,s));if(i(d))throw t(l,`Invalid path for route "${c}": non-ASCII static segment in "${s}" — 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 g=u&&u.paramMeta.urlParams.length>0;if(s.startsWith(`~`)&&g)throw t(l,`Absolute path "${s}" cannot be used under parent route with URL parameters`)}const c=Object.getOwnPropertyDescriptor,l=Object.keys,u=Object.getPrototypeOf,d=/^[A-Z_a-z][\w-]*$/,f=/\S/,p=1e4;function m(e){if(e===null)return`null`;if(typeof e==`object`){try{let t=e.constructor;if(typeof t==`function`&&t.name!==`Object`)return t.name||`object`}catch{}return`object`}return typeof e}function h(e){for(let t of l(e)){let n=c(e,t);if(n&&(n.get||n.set))return!0}return!1}function g(e,t){if(!e||typeof e!=`object`)throw TypeError(`[router.${t}] Route must be an object, got ${m(e)}`);let n=u(e);if(n!==Object.prototype&&n!==null)throw TypeError(`[router.${t}] Route must be a plain object, got ${m(e)}`);if(h(e))throw TypeError(`[router.${t}] Route must not have getters or setters`)}function _(e,t){if(e.encodeParams!==void 0&&typeof e.encodeParams!=`function`)throw TypeError(`[router.${t}] Route "${String(e.name)}" encodeParams must be a function`)}function v(e,t){if(e.decodeParams!==void 0&&typeof e.decodeParams!=`function`)throw TypeError(`[router.${t}] Route "${String(e.name)}" decodeParams must be a function`)}function y(e,t){if(typeof e.name!=`string`)throw TypeError(`[router.${t}] Route name must be a string, got ${m(e.name)}`);let n=e.name;if(n===``)throw TypeError(`[router.${t}] Route name cannot be empty`);if(!f.test(n))throw TypeError(`[router.${t}] Route name cannot contain only whitespace`);if(n.length>p)throw TypeError(`[router.${t}] Route name exceeds maximum length of ${p} characters`);if(!n.startsWith(`@@`)){if(n.includes(`.`))throw TypeError(`[router.${t}] Route name "${n}" cannot contain dots. Use children array or { parent } option in addRoute() instead.`);if(!d.test(n))throw TypeError(`[router.${t}] Invalid route name "${n}". Name must start with a letter or underscore, followed by letters, numbers, underscores, or hyphens.`)}}function b(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 x(e,t,n){if(b(e,t))throw Error(`[router.${n}] Route "${t}" already exists`)}function S(e,t,n){if(e.has(t))throw Error(`[router.${n}] Duplicate route "${t}" in batch`);e.add(t)}function C(e,t,n,r){let i=t===``?e:b(e,t);if(i){for(let e of i.children.values())if(e.path===n)throw Error(`[router.${r}] Path "${n}" is already defined`)}}function w(e,t,n,r){let i=e.get(t);if(i?.has(n))throw Error(`[router.${r}] Path "${n}" is already defined`);i?i.add(n):e.set(t,new Set([n]))}function T(e,t,n,r=``,i,a){g(e,t);let o=e;y(o,t),s(o.path,o.name,t,n),_(o,t),v(o,t);let c=o.name,l=r?`${r}.${c}`:c;n&&l&&x(n,l,t),i&&S(i,l,t);let u=o.path,d=r;if(n&&C(n,d,u,t),a&&w(a,d,u,t),o.children!==void 0){if(!Array.isArray(o.children))throw TypeError(`[router.${t}] Route "${c}" children must be an array, got ${m(o.children)}`);for(let e of o.children)T(e,t,n,l,i,a)}}exports.getInternals=e.u,exports.validateRoute=T;
|
|
2
2
|
//# sourceMappingURL=validation.js.map
|