@real-router/core 0.77.3 → 0.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/{Router-Bm2qafJA.d.ts → Router-BG5yNYUG.d.ts} +4 -10
- package/dist/cjs/Router-BG5yNYUG.d.ts.map +1 -0
- package/dist/cjs/Router-D6NzRxBA.js +2 -0
- package/dist/cjs/Router-D6NzRxBA.js.map +1 -0
- package/dist/cjs/RouterValidator-CZ8kPkrI.d.ts +107 -0
- package/dist/cjs/RouterValidator-CZ8kPkrI.d.ts.map +1 -0
- package/dist/cjs/api.d.ts +20 -4
- package/dist/cjs/api.d.ts.map +1 -1
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/api.js.map +1 -1
- package/dist/cjs/buildParamMeta-CkG6cUIl.js +2 -0
- package/dist/cjs/buildParamMeta-CkG6cUIl.js.map +1 -0
- package/dist/cjs/cloneRouter-a6LJt-zh.js +2 -0
- package/dist/cjs/cloneRouter-a6LJt-zh.js.map +1 -0
- package/dist/cjs/index-CAnGQpnz.d.ts +974 -0
- package/dist/cjs/index-CAnGQpnz.d.ts.map +1 -0
- package/dist/{esm/index-Cwd11Hun.d.mts → cjs/index-DDrryY2U.d.ts} +3 -3
- package/dist/cjs/{index-A1sdfTRT.d.ts.map → index-DDrryY2U.d.ts.map} +1 -1
- package/dist/cjs/index.d.ts +192 -7
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/types-xg2zHVF6.d.ts +171 -0
- package/dist/cjs/types-xg2zHVF6.d.ts.map +1 -0
- package/dist/cjs/types.d.ts +2 -0
- package/dist/cjs/types.js +0 -0
- package/dist/cjs/utils.d.ts +1 -1
- package/dist/cjs/utils.js +1 -1
- package/dist/cjs/utils.js.map +1 -1
- package/dist/cjs/validation.d.ts +163 -8
- package/dist/cjs/validation.d.ts.map +1 -1
- package/dist/cjs/validation.js +2 -1
- package/dist/cjs/validation.js.map +1 -0
- package/dist/esm/{Router-Bm2qafJA.d.mts → Router-Cy75qbgU.d.mts} +4 -10
- package/dist/{cjs/Router-Bm2qafJA.d.ts.map → esm/Router-Cy75qbgU.d.mts.map} +1 -1
- package/dist/esm/Router-De0Gr9Ll.mjs +2 -0
- package/dist/esm/Router-De0Gr9Ll.mjs.map +1 -0
- package/dist/esm/RouterValidator-CZ8kPkrI.d.mts +107 -0
- package/dist/esm/RouterValidator-CZ8kPkrI.d.mts.map +1 -0
- package/dist/esm/api.d.mts +20 -4
- package/dist/esm/api.d.mts.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/api.mjs.map +1 -1
- package/dist/esm/buildParamMeta-Bl0uORu6.mjs +2 -0
- package/dist/esm/buildParamMeta-Bl0uORu6.mjs.map +1 -0
- package/dist/esm/cloneRouter-CqS4kTs8.mjs +2 -0
- package/dist/esm/cloneRouter-CqS4kTs8.mjs.map +1 -0
- package/dist/esm/index-CAnGQpnz.d.mts +974 -0
- package/dist/esm/index-CAnGQpnz.d.mts.map +1 -0
- package/dist/{cjs/index-A1sdfTRT.d.ts → esm/index-DnSU6huX.d.mts} +3 -3
- package/dist/esm/{index-Cwd11Hun.d.mts.map → index-DnSU6huX.d.mts.map} +1 -1
- package/dist/esm/index.d.mts +192 -7
- package/dist/esm/index.d.mts.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/types-xg2zHVF6.d.mts +171 -0
- package/dist/esm/types-xg2zHVF6.d.mts.map +1 -0
- package/dist/esm/types.d.mts +2 -0
- package/dist/esm/types.mjs +0 -0
- package/dist/esm/utils.d.mts +1 -1
- package/dist/esm/utils.mjs +1 -1
- package/dist/esm/utils.mjs.map +1 -1
- package/dist/esm/validation.d.mts +162 -9
- package/dist/esm/validation.d.mts.map +1 -1
- package/dist/esm/validation.mjs +2 -1
- package/dist/esm/validation.mjs.map +1 -0
- package/package.json +15 -12
- package/dist/cjs/Router-CLGzVSB7.js +0 -2
- package/dist/cjs/Router-CLGzVSB7.js.map +0 -1
- package/dist/cjs/RouterError-OKaEXSBZ.d.ts +0 -292
- package/dist/cjs/RouterError-OKaEXSBZ.d.ts.map +0 -1
- package/dist/cjs/cloneRouter-B9QmW8WN.js +0 -2
- package/dist/cjs/cloneRouter-B9QmW8WN.js.map +0 -1
- package/dist/cjs/esm-6qkkdCI3.js +0 -2
- package/dist/cjs/esm-6qkkdCI3.js.map +0 -1
- package/dist/cjs/index-raddZEYH.d.ts +0 -356
- package/dist/cjs/index-raddZEYH.d.ts.map +0 -1
- package/dist/esm/Router-Bm2qafJA.d.mts.map +0 -1
- package/dist/esm/Router-x5kV9fKk.mjs +0 -2
- package/dist/esm/Router-x5kV9fKk.mjs.map +0 -1
- package/dist/esm/RouterError-OKaEXSBZ.d.mts +0 -292
- package/dist/esm/RouterError-OKaEXSBZ.d.mts.map +0 -1
- package/dist/esm/cloneRouter-C6fB27Wq.mjs +0 -2
- package/dist/esm/cloneRouter-C6fB27Wq.mjs.map +0 -1
- package/dist/esm/esm-DgICGBiW.mjs +0 -2
- package/dist/esm/esm-DgICGBiW.mjs.map +0 -1
- package/dist/esm/index-raddZEYH.d.mts +0 -356
- package/dist/esm/index-raddZEYH.d.mts.map +0 -1
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
//#region src/types/RouterValidator.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* RouterValidator interface - defines all validation methods used by the router.
|
|
4
|
+
*
|
|
5
|
+
* This interface is implemented by the validation plugin and injected into RouterInternals.
|
|
6
|
+
* When ctx.validator is null (default), validation is skipped.
|
|
7
|
+
* When ctx.validator is set (by validation plugin), all methods are called.
|
|
8
|
+
*
|
|
9
|
+
* All parameters use `unknown` type to avoid coupling to internal type names.
|
|
10
|
+
*/
|
|
11
|
+
interface RouterValidator {
|
|
12
|
+
/**
|
|
13
|
+
* Route validation methods
|
|
14
|
+
*/
|
|
15
|
+
routes: {
|
|
16
|
+
validateBuildPathArgs: (route: unknown) => void;
|
|
17
|
+
validateMatchPathArgs: (path: unknown) => void;
|
|
18
|
+
validateIsActiveRouteArgs: (name: unknown, params: unknown, strict: unknown, ignoreQP: unknown) => void;
|
|
19
|
+
validateShouldUpdateNodeArgs: (name: unknown) => void;
|
|
20
|
+
validateStateBuilderArgs: (name: unknown, params: unknown, caller: string) => void;
|
|
21
|
+
validateAddRouteArgs: (routes: unknown) => void;
|
|
22
|
+
validateRoutes: (routes: unknown[], tree: unknown, parentName?: string) => void;
|
|
23
|
+
validateRemoveRouteArgs: (name: unknown) => void;
|
|
24
|
+
validateUpdateRouteBasicArgs: (name: unknown, updates: unknown) => void;
|
|
25
|
+
validateUpdateRoutePropertyTypes: (name: string, updates: unknown) => void;
|
|
26
|
+
validateUpdateRoute: (name: string, updates: unknown, tree: unknown) => void;
|
|
27
|
+
validateParentOption: (parent: unknown, tree: unknown) => void;
|
|
28
|
+
validateRouteName: (name: unknown, caller: string) => void;
|
|
29
|
+
throwIfInternalRoute: (name: unknown, caller: string) => void;
|
|
30
|
+
throwIfInternalRouteInArray: (routes: unknown[], caller: string) => void;
|
|
31
|
+
validateSetRootPathArgs: (rootPath: unknown) => void;
|
|
32
|
+
guardRouteCallbacks: (route: unknown) => void;
|
|
33
|
+
guardNoAsyncCallbacks: (route: unknown) => void;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Options validation methods
|
|
37
|
+
*/
|
|
38
|
+
options: {
|
|
39
|
+
validateOptions: (options: unknown, methodName: string) => void;
|
|
40
|
+
validateResolvedDefaultRoute: (routeName: unknown, store: unknown) => void;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Dependencies validation methods
|
|
44
|
+
*/
|
|
45
|
+
dependencies: {
|
|
46
|
+
validateDependencyName: (name: unknown, caller: string) => void;
|
|
47
|
+
validateSetDependencyArgs: (name: unknown, value: unknown, caller: string) => void;
|
|
48
|
+
validateDependenciesObject: (deps: unknown, caller: string) => void;
|
|
49
|
+
validateDependencyExists: (name: string, store: unknown) => void;
|
|
50
|
+
validateDependencyCount: (store: unknown, methodName: string) => void;
|
|
51
|
+
validateCloneArgs: (dependencies: unknown) => void;
|
|
52
|
+
warnOverwrite: (name: string, methodName: string) => void;
|
|
53
|
+
warnBatchOverwrite: (keys: string[], methodName: string) => void;
|
|
54
|
+
warnRemoveNonExistent: (name: unknown) => void;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Plugin validation methods
|
|
58
|
+
*/
|
|
59
|
+
plugins: {
|
|
60
|
+
validatePluginLimit: (count: number, limits: unknown) => void;
|
|
61
|
+
validateNoDuplicatePlugins: (factory: unknown, factories: unknown[]) => void;
|
|
62
|
+
validatePluginKeys: (plugin: unknown) => void;
|
|
63
|
+
validateCountThresholds: (count: number) => void;
|
|
64
|
+
warnBatchDuplicates: (plugins: unknown[]) => void;
|
|
65
|
+
warnPluginMethodType: (methodName: string) => void;
|
|
66
|
+
warnPluginAfterStart: (methodName: string) => void;
|
|
67
|
+
validateAddInterceptorArgs: (method: unknown, fn: unknown) => void;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Lifecycle guard validation methods
|
|
71
|
+
*/
|
|
72
|
+
lifecycle: {
|
|
73
|
+
validateHandler: (handler: unknown, caller: string) => void;
|
|
74
|
+
validateHandlerLimit: (count: number, methodName: string) => void;
|
|
75
|
+
validateCountThresholds: (count: number, methodName: string) => void;
|
|
76
|
+
warnOverwrite: (name: string, type: string, methodName: string) => void;
|
|
77
|
+
warnAsyncGuardSync: (name: string, methodName: string) => void;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Navigation validation methods
|
|
81
|
+
*/
|
|
82
|
+
navigation: {
|
|
83
|
+
validateNavigateArgs: (name: unknown) => void;
|
|
84
|
+
validateNavigateToDefaultArgs: (options: unknown) => void;
|
|
85
|
+
validateNavigateToStateArgs: (state: unknown) => void;
|
|
86
|
+
validateNavigationOptions: (options: unknown, caller: string) => void;
|
|
87
|
+
validateParams: (params: unknown, methodName: string) => void;
|
|
88
|
+
validateStartArgs: (path: unknown) => void;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* State validation methods
|
|
92
|
+
*/
|
|
93
|
+
state: {
|
|
94
|
+
validateMakeStateArgs: (name: unknown, params: unknown, path: unknown) => void;
|
|
95
|
+
validateAreStatesEqualArgs: (s1: unknown, s2: unknown, ignoreQP: unknown) => void;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Event bus validation methods
|
|
99
|
+
*/
|
|
100
|
+
eventBus: {
|
|
101
|
+
validateListenerArgs: (name: unknown, cb: unknown) => void;
|
|
102
|
+
validateCountThresholds: (count: number, eventName: string, methodName: string) => void;
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { RouterValidator as t };
|
|
107
|
+
//# sourceMappingURL=RouterValidator-CZ8kPkrI.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouterValidator-CZ8kPkrI.d.ts","names":[],"sources":["../../src/types/RouterValidator.ts"],"mappings":";;AAUA;;;;;;;;UAAiB,eAAA;EAOb;;;EAHF,MAAA;IACE,qBAAA,GAAwB,KAAA;IACxB,qBAAA,GAAwB,IAAA;IACxB,yBAAA,GACE,IAAA,WACA,MAAA,WACA,MAAA,WACA,QAAA;IAEF,4BAAA,GAA+B,IAAA;IAC/B,wBAAA,GACE,IAAA,WACA,MAAA,WACA,MAAA;IAEF,oBAAA,GAAuB,MAAA;IACvB,cAAA,GACE,MAAA,aACA,IAAA,WACA,UAAA;IAEF,uBAAA,GAA0B,IAAA;IAC1B,4BAAA,GAA+B,IAAA,WAAe,OAAA;IAC9C,gCAAA,GAAmC,IAAA,UAAc,OAAA;IACjD,mBAAA,GACE,IAAA,UACA,OAAA,WACA,IAAA;IAEF,oBAAA,GAAuB,MAAA,WAAiB,IAAA;IACxC,iBAAA,GAAoB,IAAA,WAAe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2BAAA,GAA8B,KAAA;IAC9B,yBAAA,GAA4B,OAAA,WAAkB,MAAA;IAC9C,cAAA,GAAiB,MAAA,WAAiB,UAAA;IAClC,iBAAA,GAAoB,IAAA;EAAA;EAzCiB;;;EA+CvC,KAAA;IACE,qBAAA,GACE,IAAA,WACA,MAAA,WACA,IAAA;IAEF,0BAAA,GACE,EAAA,WACA,EAAA,WACA,QAAA;EAAA;EA/CF;;;EAsDF,QAAA;IACE,oBAAA,GAAuB,IAAA,WAAe,EAAA;IACtC,uBAAA,GACE,KAAA,UACA,SAAA,UACA,UAAA;EAAA;AAAA"}
|
package/dist/cjs/api.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { n as RouteTree } from "./types-xg2zHVF6.js";
|
|
2
|
+
import { I as LoggerConfig, U as Router, a as LifecycleApi, n as DependenciesApi, o as PluginApi$1, s as RoutesApi, w as DefaultDependencies } from "./index-CAnGQpnz.js";
|
|
3
|
+
import { t as Router$1 } from "./Router-BG5yNYUG.js";
|
|
4
4
|
|
|
5
5
|
//#region src/api/types.d.ts
|
|
6
6
|
interface PluginApi extends Omit<PluginApi$1, "getTree"> {
|
|
@@ -20,6 +20,22 @@ declare function getDependenciesApi<Dependencies extends DefaultDependencies = D
|
|
|
20
20
|
declare function getLifecycleApi<Dependencies extends DefaultDependencies = DefaultDependencies>(router: Router<Dependencies>): LifecycleApi<Dependencies>;
|
|
21
21
|
//#endregion
|
|
22
22
|
//#region src/api/cloneRouter.d.ts
|
|
23
|
+
/**
|
|
24
|
+
* Per-clone overrides beyond dependencies.
|
|
25
|
+
*/
|
|
26
|
+
interface CloneOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Per-clone logger config override, merged **over** the base router's resolved
|
|
29
|
+
* logger config. Primary use: per-request `traceId` in SSR — a fresh
|
|
30
|
+
* `callback` closed over the request id, while `level` inherits the base.
|
|
31
|
+
* Omitted keys inherit the base (level / callback / callbackIgnoresLevel).
|
|
32
|
+
*
|
|
33
|
+
* Override is by **config**, not a logger instance: `RouterLogger` is
|
|
34
|
+
* core-internal (only its `{ log, warn, error }` interface is public), so
|
|
35
|
+
* nothing outside core constructs one — configuration is the whole surface.
|
|
36
|
+
*/
|
|
37
|
+
logger?: Partial<LoggerConfig>;
|
|
38
|
+
}
|
|
23
39
|
/**
|
|
24
40
|
* Build an independent router instance that shares the route tree, options,
|
|
25
41
|
* lifecycle guards, and plugin factories of `router`. The primary use case
|
|
@@ -83,7 +99,7 @@ declare function getLifecycleApi<Dependencies extends DefaultDependencies = Defa
|
|
|
83
99
|
* @see createRequestScope — `@real-router/core/utils` SSR helper that
|
|
84
100
|
* wraps this function and injects `abortSignal` automatically.
|
|
85
101
|
*/
|
|
86
|
-
declare function cloneRouter<Dependencies extends DefaultDependencies = DefaultDependencies>(router: Router<Dependencies>, dependencies?: Dependencies): Router$1<Dependencies>;
|
|
102
|
+
declare function cloneRouter<Dependencies extends DefaultDependencies = DefaultDependencies>(router: Router<Dependencies>, dependencies?: Dependencies, opts?: CloneOptions): Router$1<Dependencies>;
|
|
87
103
|
//#endregion
|
|
88
104
|
export { type DependenciesApi, type LifecycleApi, type PluginApi, type RoutesApi, cloneRouter, getDependenciesApi, getLifecycleApi, getPluginApi, getRoutesApi };
|
|
89
105
|
//# sourceMappingURL=api.d.ts.map
|
package/dist/cjs/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","names":[],"sources":["../../src/api/types.ts","../../src/api/getPluginApi.ts","../../src/api/getRoutesApi.ts","../../src/api/getDependenciesApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.ts"],"mappings":";;;;;UAGiB,SAAA,SAAkB,IAAA,CAAK,WAAA;EACtC,OAAA,QAAe,SAAA;AAAA;;;iBCkBD,YAAA,sBACO,mBAAA,GAAsB,mBAAA,EAC3C,MAAA,EAAQ,MAAA,CAAO,YAAA,IAAgB,SAAA;;;
|
|
1
|
+
{"version":3,"file":"api.d.ts","names":[],"sources":["../../src/api/types.ts","../../src/api/getPluginApi.ts","../../src/api/getRoutesApi.ts","../../src/api/getDependenciesApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.ts"],"mappings":";;;;;UAGiB,SAAA,SAAkB,IAAA,CAAK,WAAA;EACtC,OAAA,QAAe,SAAA;AAAA;;;iBCkBD,YAAA,sBACO,mBAAA,GAAsB,mBAAA,EAC3C,MAAA,EAAQ,MAAA,CAAO,YAAA,IAAgB,SAAA;;;iBC0mBjB,YAAA,sBACO,mBAAA,GAAsB,mBAAA,EAC3C,MAAA,EAAQ,MAAA,CAAO,YAAA,IAAgB,SAAA,CAAU,YAAA;;;iBCtjB3B,kBAAA,sBACO,mBAAA,GAAsB,mBAAA,EAC3C,MAAA,EAAQ,MAAA,CAAO,YAAA,IAAgB,eAAA,CAAgB,YAAA;;;iBC1EjC,eAAA,sBACO,mBAAA,GAAsB,mBAAA,EAC3C,MAAA,EAAQ,MAAA,CAAO,YAAA,IAAgB,YAAA,CAAa,YAAA;;;;;;UCU7B,YAAA;ELfU;;;;;;;;;;EK0BzB,MAAA,GAAS,OAAO,CAAC,YAAA;AAAA;ALzBO;;;;ACkB1B;;;;;;;;;;;;;;;;;;AAE0C;;;;AC0mB1C;;;;;;;;;;;;;;;;;;;;AAEuD;;;;ACtjBvD;;;;;;;;;;;;;AH1E0B,iBK2FV,WAAA,sBACO,mBAAA,GAAsB,mBAAA,EAE3C,MAAA,EAAQ,MAAA,CAAO,YAAA,GACf,YAAA,GAAe,YAAA,EACf,IAAA,GAAO,YAAA,GACN,QAAA,CAAY,YAAA"}
|
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-D6NzRxBA.js"),t=require("./buildParamMeta-CkG6cUIl.js"),n=require("./cloneRouter-a6LJt-zh.js");function r(e,t,n,r){if(t){let n=t===e,i=t.startsWith(`${e}.`);if(n||i){let i=n?``:` (current: "${t}")`;return r.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return n&&r.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}function i(e,t){return e?(t.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const a=Object.freeze({replace:!0,revalidate:!0});function o(t,n,r,i){let a=e=>e===t||e.startsWith(`${t}.`);e.v(n.decoders,a),e.v(n.encoders,a),e.v(n.defaultParams,a),e.v(n.forwardMap,a),e.v(n.forwardFnMap,a),e.v(r,a),e.v(n.forwardMap,e=>a(n.forwardMap[e]));let[o,s]=i.getFactories();for(let e of Object.keys(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of Object.keys(o))a(e)&&i.clearCanDeactivate(e,`both`)}function s(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.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 c(e,t,n,r){let i={name:e.name,path:e.path};return s(i,t,n,r),e.children&&(i.children=e.children.map(e=>c(e,`${t}.${e.name}`,n,r))),i}function l(e,t,n,r){let i={name:e,path:t};return s(i,e,n,r),Object.freeze(i)}function u(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,l(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function d(e,t){let n=`${t}.`,r=u(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function f(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(l(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function p(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 m(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function h(t,n,r,i){e.a(t,n,r);let a=e.u(t,n,r,i);t.lifecycleNamespace.preflightHandlerLimit(a.pendingCanActivate.keys(),a.pendingCanDeactivate.keys(),!1),e.i(t,a)}function g(e,t,n){e.setState(t),e.emitTransitionSuccess(t,n,a)}function _(t,n,r,i,a){e.c(n,`addRoute`),e.o(n,``,`addRoute`),e.s(n,``,`addRoute`);let o=e.d(n,t.rootPath,t.matcherOptions,r.logger);t.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!0);let s=e.m(o,t.depsStore);if(t.lifecycleNamespace.clearDefinitionGuards(),e.i(t,o,s),a?.(),i!==void 0){let n=r.matchPath(i.path,r.getOptions());if(n)if(n.name===i.name)g(r,{...n,context:i.context,transition:i.transition},i);else{let{toDeactivate:a,toActivate:o}=e.r(n,i);t.lifecycleNamespace.canNavigateTo(a,o,n,i)?g(r,{...n,transition:i.transition},i):r.navigateToNotFound(i.path)}else r.navigateToNotFound(i.path)}}function v(t,n){let r=t.definitions;return e.y(r,n)?(o(n,t.config,t.routeCustomFields,t.lifecycleNamespace),e.p(t,r),!0):!1}function y(t,n){let r=t.matcher.getSegmentsByName(n);if(!r)return;let i=e.b(r.at(-1)),a=t.lifecycleNamespace.getFactories();return c(i,n,t.config,a)}const b=new WeakMap;function x(a){let o=b.get(a);if(o)return o;let s=t.f(a),c=s.routeGetStore(),l=e=>{s.treeChanged.emit(e)},g={add:(t,r)=>{n.i(s.isDisposed),n.a(s.treeChanged.isEmitting);let i=Array.isArray(t)?t:[t],a=r?.parent;if(e.S(i,s.validator),a!==void 0&&s.validator?.routes.validateParentOption(a,c.tree),s.validator?.routes.throwIfInternalRouteInArray(i,`addRoute`),s.validator?.routes.validateAddRouteArgs(i),s.validator?.routes.validateRoutes(i,c,a),h(c,i,a,s.logger),s.treeChanged.listenerCount()>0){let e=f(i,a,c);l(a===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:a})}},remove:t=>{if(n.i(s.isDisposed),n.a(s.treeChanged.isEmitting),s.validator?.routes.validateRemoveRouteArgs(t),s.validator?.routes.throwIfInternalRoute(t,`removeRoute`),e.l(t,`removeRoute`),!r(t,s.getStateName(),s.isTransitioning(),s.logger))return;let i=s.treeChanged.listenerCount()>0?d(c,t):void 0;if(!v(c,t)){s.logger.warn(`router.removeRoute`,`Route "${t}" not found. No changes made.`);return}i!==void 0&&l({op:`remove`,name:t,removedSubtree:i})},update:(t,r)=>{if(n.i(s.isDisposed),n.a(s.treeChanged.isEmitting),s.validator?.routes.validateUpdateRouteBasicArgs(t,r),s.validator?.routes.throwIfInternalRoute(t,`updateRoute`),e.l(t,`updateRoute`),s.validator?.routes.validateUpdateRoutePropertyTypes(t,r),s.isTransitioning()&&s.logger.error(`router.updateRoute`,`Updating route "${t}" while navigation is in progress. This may cause unexpected behavior.`),s.validator?.routes.validateUpdateRoute(t,r,c),!c.matcher.hasRoute(t))return;let i=c.lifecycleNamespace,a=e.f(c,i,t,r);if(s.treeChanged.listenerCount()>0){let e=m(a);Object.keys(e).length>0&&l({op:`update`,name:t,patch:e})}},clear:()=>{if(n.i(s.isDisposed),n.a(s.treeChanged.isEmitting),!i(s.isTransitioning(),s.logger))return;let t=s.treeChanged.listenerCount()>0?Object.freeze([...u(c,()=>!0).values()]):void 0;e.h(c),c.lifecycleNamespace.clearAll(),s.clearState(),t!==void 0&&l({op:`clear`,removed:t})},has:e=>(s.validator?.routes.validateRouteName(e,`hasRoute`),c.matcher.hasRoute(e)),get:e=>(s.validator?.routes.validateRouteName(e,`getRoute`),y(c,e)),replace:t=>{n.i(s.isDisposed),n.a(s.treeChanged.isEmitting);let r=Array.isArray(t)?t:[t];if(!i(s.isTransitioning(),s.logger))return;e.S(r,s.validator),s.validator?.routes.throwIfInternalRouteInArray(r,`replaceRoutes`),s.validator?.routes.validateAddRouteArgs(r),s.validator?.routes.validateRoutes(r,c);let o=a.getState(),d=s.treeChanged.listenerCount()>0?u(c,()=>!0):void 0;_(c,r,s,o,d===void 0?void 0:()=>{let{removed:e,added:t}=p(d,u(c,()=>!0));l({op:`replace`,removed:e,added:t})})},subscribeChanges:e=>s.treeChanged.subscribe(e)};return b.set(a,g),g}function S(e,t,n,r){if(n!==void 0){if(!Object.hasOwn(e.dependencies,t))r?.dependencies.validateDependencyCount(e,`setDependency`);else{let i=e.dependencies[t];i!==n&&!(Number.isNaN(i)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(t,`setDependency`)}e.dependencies[t]=n}}function C(e,t,n){let r=[];for(let i in t)t[i]!==void 0&&(Object.hasOwn(e.dependencies,i)?r.push(i):n?.dependencies.validateDependencyCount(e,`setDependencies`),e.dependencies[i]=t[i]);r.length>0&&n?.dependencies.warnBatchOverwrite(r,`setDependencies`)}function w(e){let r=t.f(e);return{get:e=>{r.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=r.dependenciesGetStore(),n=t.dependencies[e];return r.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>({...r.dependenciesGetStore().dependencies}),set:(e,t)=>{n.i(r.isDisposed),r.validator?.dependencies.validateSetDependencyArgs(e,t,`setDependency`),S(r.dependenciesGetStore(),e,t,r.validator)},setAll:e=>{n.i(r.isDisposed);let t=r.dependenciesGetStore();r.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),C(t,e,r.validator)},remove:e=>{n.i(r.isDisposed),r.validator?.dependencies.validateDependencyName(e,`removeDependency`);let t=r.dependenciesGetStore();Object.hasOwn(t.dependencies,e)||r.validator?.dependencies.warnRemoveNonExistent(e),delete t.dependencies[e]},reset:()=>{n.i(r.isDisposed);let e=r.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(r.validator?.dependencies.validateDependencyName(e,`hasDependency`),Object.hasOwn(r.dependenciesGetStore().dependencies,e))}}exports.cloneRouter=n.t,exports.getDependenciesApi=w,exports.getLifecycleApi=n.n,exports.getPluginApi=n.r,exports.getRoutesApi=x;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
package/dist/cjs/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","names":["buildAddArtifacts","buildReplaceArtifacts","compileArtifactGuards","getTransitionPath","removeFromDefinitions","nodeToDefinition","getInternals","commitRouteUpdate","getInternals"],"sources":["../../src/namespaces/RoutesNamespace/routeGuards.ts","../../src/api/getRoutesApi.ts","../../src/api/getDependenciesApi.ts"],"sourcesContent":["import { logger } from \"@real-router/logger\";\n\n/**\n * Validates removeRoute constraints.\n * Returns false if removal should be blocked (route is active).\n * Logs warnings for edge cases.\n *\n * @param name - Route name to remove\n * @param currentStateName - Current active route name (or undefined)\n * @param isNavigating - Whether navigation is in progress\n * @returns true if removal can proceed, false if blocked\n */\nexport function validateRemoveRoute(\n name: string,\n currentStateName: string | undefined,\n isNavigating: boolean,\n): boolean {\n if (currentStateName) {\n const isExactMatch = currentStateName === name;\n const isParentOfCurrent = currentStateName.startsWith(`${name}.`);\n\n if (isExactMatch || isParentOfCurrent) {\n const suffix = isExactMatch ? \"\" : ` (current: \"${currentStateName}\")`;\n\n logger.warn(\n \"router.removeRoute\",\n `Cannot remove route \"${name}\" — it is currently active${suffix}. Navigate away first.`,\n );\n\n return false;\n }\n }\n\n if (isNavigating) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" removed while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n return true;\n}\n\n/**\n * Validates clearRoutes operation.\n * Returns false if operation should be blocked (navigation in progress).\n *\n * @param isNavigating - Whether navigation is in progress\n * @returns true if clearRoutes can proceed, false if blocked\n */\nexport function validateClearRoutes(isNavigating: boolean): boolean {\n if (isNavigating) {\n logger.error(\n \"router.clearRoutes\",\n \"Cannot clear routes while navigation is in progress. Wait for navigation to complete.\",\n );\n\n return false;\n }\n\n return true;\n}\n","import { logger } from \"@real-router/logger\";\nimport { nodeToDefinition } from \"route-tree\";\n\nimport { throwIfDisposed, throwIfReentrantTreeMutation } from \"./helpers\";\nimport { guardRouteStructure } from \"../guards\";\nimport { getInternals } from \"../internals\";\nimport {\n clearConfigEntries,\n removeFromDefinitions,\n} from \"../namespaces/RoutesNamespace/helpers\";\nimport {\n validateClearRoutes,\n validateRemoveRoute,\n} from \"../namespaces/RoutesNamespace/routeGuards\";\nimport {\n adoptRouteArtifacts,\n assertAddable,\n assertNoDuplicateNamesInBatch,\n assertNoDuplicatePathsInBatch,\n assertNoInternalNamesInBatch,\n assertNoInternalRouteName,\n buildAddArtifacts,\n buildReplaceArtifacts,\n commitRouteUpdate,\n commitTreeChanges,\n compileArtifactGuards,\n resetStore,\n} from \"../namespaces/RoutesNamespace/routesStore\";\nimport { getTransitionPath } from \"../transitionPath\";\n\nimport type { RoutesApi } from \"./types\";\nimport type { RouterInternals } from \"../internals\";\nimport type { RouteLifecycleNamespace, RouteConfig } from \"../namespaces\";\nimport type { RoutesStore } from \"../namespaces/RoutesNamespace\";\nimport type { GuardFnFactory, Route } from \"../types\";\nimport type {\n DefaultDependencies,\n ForwardToCallback,\n NavigationOptions,\n Params,\n Router,\n State,\n TreeChangedEvent,\n TreeStructuralPatch,\n} from \"@real-router/types\";\nimport type { RouteDefinition, RouteTree } from \"route-tree\";\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Opts attached to the `TRANSITION_SUCCESS` emitted by `replace()` when it\n * revalidates the active state (#950). `replace` does not push history, so it\n * is a replace-type success — matching `navigateToNotFound`'s opts for the\n * dropped-route branch.\n */\nconst REVALIDATE_OPTS: NavigationOptions = Object.freeze({\n replace: true,\n revalidate: true,\n});\n\n/**\n * Clears all config entries and lifecycle handlers for a removed route\n * (and all its descendants).\n */\nfunction clearRouteConfigurations<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routeName: string,\n config: RouteConfig,\n routeCustomFields: Record<string, Record<string, unknown>>,\n lifecycleNamespace: RouteLifecycleNamespace<Dependencies>,\n): void {\n const shouldClear = (name: string): boolean =>\n name === routeName || name.startsWith(`${routeName}.`);\n\n clearConfigEntries(config.decoders, shouldClear);\n clearConfigEntries(config.encoders, shouldClear);\n clearConfigEntries(config.defaultParams, shouldClear);\n clearConfigEntries(config.forwardMap, shouldClear);\n clearConfigEntries(config.forwardFnMap, shouldClear);\n clearConfigEntries(routeCustomFields, shouldClear);\n\n // Clear forwardMap entries pointing TO the deleted route (or its descendants)\n clearConfigEntries(config.forwardMap, (key) =>\n shouldClear(config.forwardMap[key]),\n );\n\n // Clear lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n lifecycleNamespace.getFactories();\n\n for (const name of Object.keys(canActivateFactories)) {\n if (shouldClear(name)) {\n // Route removed from the tree — both origin slots go (route no longer exists).\n lifecycleNamespace.clearCanActivate(name, \"both\");\n }\n }\n\n for (const name of Object.keys(canDeactivateFactories)) {\n if (shouldClear(name)) {\n lifecycleNamespace.clearCanDeactivate(name, \"both\");\n }\n }\n}\n\n/**\n * Re-attaches the stored config (forwardTo / defaultParams / encode-decode) and\n * lifecycle guards for `lookupName` onto `route`, then returns it (mutates in\n * place). Shared by {@link enrichRoute} (nested, bare `name`) and\n * {@link buildFlatRoute} (flat, full dotted `name`) — one source of truth for\n * the route-config field set.\n */\nfunction assignRouteConfig<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n route: Route<Dependencies>,\n lookupName: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const forwardToFn = config.forwardFnMap[lookupName];\n const forwardToStr = config.forwardMap[lookupName];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (forwardToFn !== undefined) {\n route.forwardTo = forwardToFn;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n } else if (forwardToStr !== undefined) {\n route.forwardTo = forwardToStr;\n }\n\n if (lookupName in config.defaultParams) {\n route.defaultParams = config.defaultParams[lookupName];\n }\n\n if (lookupName in config.decoders) {\n route.decodeParams = config.decoders[lookupName];\n }\n\n if (lookupName in config.encoders) {\n route.encodeParams = config.encoders[lookupName];\n }\n\n const [canDeactivateFactories, canActivateFactories] = factories;\n\n if (lookupName in canActivateFactories) {\n route.canActivate = canActivateFactories[lookupName];\n }\n\n if (lookupName in canDeactivateFactories) {\n route.canDeactivate = canDeactivateFactories[lookupName];\n }\n\n return route;\n}\n\n/**\n * Builds a full Route object from a bare RouteDefinition by re-attaching\n * config entries and lifecycle factories.\n *\n * RECURSIVE — call with the factories tuple obtained ONCE from\n * `lifecycleNamespace.getFactories()` and pass it through to children.\n */\nfunction enrichRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routeDef: RouteDefinition,\n routeName: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const route: Route<Dependencies> = {\n name: routeDef.name,\n path: routeDef.path,\n };\n\n assignRouteConfig(route, routeName, config, factories);\n\n if (routeDef.children) {\n route.children = routeDef.children.map((child) =>\n enrichRoute(child, `${routeName}.${child.name}`, config, factories),\n );\n }\n\n return route;\n}\n\n// ============================================================================\n// TREE_CHANGED payload helpers\n// ============================================================================\n\n/**\n * Builds a single FLAT `Route` for `fullName` from the store config + lifecycle\n * factories — `name` is the FULL dotted name and there is no `children` array\n * (consumers want a flat, by-name list). Frozen on construction.\n */\nfunction buildFlatRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n fullName: string,\n path: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const route: Route<Dependencies> = { name: fullName, path };\n\n assignRouteConfig(route, fullName, config, factories);\n\n return Object.freeze(route);\n}\n\n/**\n * Walks the store's definitions depth-first, building a FLAT\n * `Map<fullName, Route>` for every node whose full dotted name satisfies\n * `include`. Reads the live store, so call it at the right moment relative to\n * the mutation (before for removed, after for added).\n */\nfunction collectFlatRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n include: (fullName: string) => boolean,\n): Map<string, Route<Dependencies>> {\n const result = new Map<string, Route<Dependencies>>();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const factories = store.lifecycleNamespace!.getFactories();\n\n const walk = (defs: readonly RouteDefinition[], parentName: string): void => {\n for (const def of defs) {\n const fullName = parentName ? `${parentName}.${def.name}` : def.name;\n\n if (include(fullName)) {\n result.set(\n fullName,\n buildFlatRoute(fullName, def.path, store.config, factories),\n );\n }\n\n if (def.children) {\n walk(def.children, fullName);\n }\n }\n };\n\n walk(store.definitions, \"\");\n\n return result;\n}\n\n/**\n * Collects the route `name` and all of its descendants as a FLAT, frozen array.\n * MUST be called BEFORE the removal mutation — the nodes are gone afterwards.\n */\nfunction collectSubtree<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n name: string,\n): readonly Route<Dependencies>[] {\n const prefix = `${name}.`;\n const subtree = collectFlatRoutes(\n store,\n (fullName) => fullName === name || fullName.startsWith(prefix),\n );\n\n return Object.freeze([...subtree.values()]);\n}\n\n/**\n * Builds the FLAT, frozen payload array for an `add`, walking only the input\n * routes — O(added), not O(tree). `path` is taken from the input verbatim\n * (`sanitizeRoute` never rewrites it); config fields are read from the\n * post-commit store by full name. `add` never removes, so the input subtree is\n * exactly what changed.\n */\nfunction collectAddedRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n parentName: string | undefined,\n store: RoutesStore<Dependencies>,\n): readonly Route<Dependencies>[] {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const factories = store.lifecycleNamespace!.getFactories();\n const result: Route<Dependencies>[] = [];\n\n const walk = (\n input: readonly Route<Dependencies>[],\n parent: string,\n ): void => {\n for (const route of input) {\n const fullName = parent ? `${parent}.${route.name}` : route.name;\n\n result.push(\n buildFlatRoute(fullName, route.path, store.config, factories),\n );\n\n if (route.children) {\n walk(route.children, fullName);\n }\n }\n };\n\n walk(routes, parentName ?? \"\");\n\n return Object.freeze(result);\n}\n\n/** Diffs two flat route maps by full name into frozen removed/added arrays. */\nfunction diffFlatRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n before: ReadonlyMap<string, Route<Dependencies>>,\n after: ReadonlyMap<string, Route<Dependencies>>,\n): {\n removed: readonly Route<Dependencies>[];\n added: readonly Route<Dependencies>[];\n} {\n const removed: Route<Dependencies>[] = [];\n const added: Route<Dependencies>[] = [];\n\n for (const [fullName, route] of before) {\n if (!after.has(fullName)) {\n removed.push(route);\n }\n }\n\n for (const [fullName, route] of after) {\n if (!before.has(fullName)) {\n added.push(route);\n }\n }\n\n return { removed: Object.freeze(removed), added: Object.freeze(added) };\n}\n\n/**\n * Builds the structural subset of an `update()` patch (forwardTo /\n * defaultParams / encodeParams / decodeParams) from the already-destructured\n * update fields — so user getters are not re-invoked. A guard-only patch yields\n * an empty object → the caller emits no TREE_CHANGED (О-7: guards are\n * invoked-on-demand, not cached, so they need no observation channel).\n *\n * The returned envelope is a fresh object (caller's patch untouched) and is\n * frozen on construction. Nested values (e.g. `defaultParams`) are kept by\n * reference — the same objects the router stored — so exotic inputs (circular\n * refs, class instances) are tolerated, matching `update()`'s existing contract.\n */\nfunction buildStructuralPatch<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(fields: {\n forwardTo?: string | ForwardToCallback<Dependencies> | null | undefined;\n defaultParams?: Params | null | undefined;\n decodeParams?: ((params: Params) => Params) | null | undefined;\n encodeParams?: ((params: Params) => Params) | null | undefined;\n}): Readonly<TreeStructuralPatch<Dependencies>> {\n const patch: TreeStructuralPatch<Dependencies> = {};\n\n if (fields.forwardTo !== undefined) {\n patch.forwardTo = fields.forwardTo;\n }\n\n if (fields.defaultParams !== undefined) {\n patch.defaultParams = fields.defaultParams;\n }\n\n if (fields.encodeParams !== undefined) {\n patch.encodeParams = fields.encodeParams;\n }\n\n if (fields.decodeParams !== undefined) {\n patch.decodeParams = fields.decodeParams;\n }\n\n return Object.freeze(patch);\n}\n\n// ============================================================================\n// CRUD operations\n// ============================================================================\n\n/**\n * Adds one or more routes to the router.\n * Input already validated by facade.\n */\nfunction addRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n routes: Route<Dependencies>[],\n parentName?: string,\n): void {\n // Prepare-then-commit (issue #698): reject the silent-corruption cases\n // up front (dup name vs existing, missing parent), build the merged tree /\n // config into locals (async/circular forwardTo + invalid constraint throw\n // here), then swap atomically. A rejected add leaves the store untouched.\n assertAddable(store, routes, parentName);\n\n const artifacts = buildAddArtifacts(store, routes, parentName);\n\n // Pre-flight the #961 handler-limit into PREPARE so a limit-exceeding batch\n // aborts before the swap (#1046). `add` does not clear guards, so the\n // projection runs against the live union count (clearsDefinition = false).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.preflightHandlerLimit(\n artifacts.pendingCanActivate.keys(),\n artifacts.pendingCanDeactivate.keys(),\n false,\n );\n\n adoptRouteArtifacts(store, artifacts);\n}\n\n/**\n * Commits a revalidated state after `replace()` and emits `TRANSITION_SUCCESS`\n * so `router.subscribe` / adapters re-render (#950). The emit carries\n * `REVALIDATE_OPTS` — the single distinguishable marker (`revalidate: true`) a\n * plugin's `onTransitionSuccess` can read to special-case a revalidation vs a\n * real navigation (#1201).\n */\nfunction commitRevalidated<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n ctx: RouterInternals<Dependencies>,\n nextState: State,\n fromState: State,\n): void {\n ctx.setState(nextState);\n ctx.emitTransitionSuccess(nextState, fromState, REVALIDATE_OPTS);\n}\n\n/**\n * Atomically replaces all routes with a new set (HMR / code-splitting).\n * Prepare-then-commit (issue #698): the new set is fully built into locals\n * first — a circular/async forwardTo or invalid path throws here, leaving the\n * existing tree intact — then committed.\n */\nfunction replaceRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n routes: Route<Dependencies>[],\n ctx: RouterInternals<Dependencies>,\n currentState: State | undefined,\n onCommitted?: () => void,\n): void {\n // Reject the silent-corruption cases `assertAddable` catches for `add`, BEFORE\n // building/swapping, so bare-core parity is symmetric (#1047): within-batch\n // duplicate names (#968), reserved \"@@\" names (#954), and within-batch\n // duplicate paths (#955). methodName is \"addRoute\" to match validation-plugin\n // (which reports \"addRoute\" for replace batches too), so the no-plugin error\n // is identical to the with-plugin one.\n assertNoInternalNamesInBatch(routes, \"addRoute\");\n assertNoDuplicateNamesInBatch(routes, \"\", \"addRoute\");\n assertNoDuplicatePathsInBatch(routes, \"\", \"addRoute\");\n\n // Build the whole new set BEFORE touching the store.\n const artifacts = buildReplaceArtifacts(\n routes,\n store.rootPath,\n store.matcherOptions,\n );\n\n // Pre-flight the #961 handler-limit BEFORE clearDefinitionGuards mutates, so a\n // limit-exceeding batch aborts with BOTH the tree and the definition guards\n // intact (#1046). replace clears definition guards first, so the projection\n // runs against the surviving external guards (clearsDefinition = true).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.preflightHandlerLimit(\n artifacts.pendingCanActivate.keys(),\n artifacts.pendingCanDeactivate.keys(),\n true,\n );\n\n // Pre-compile the new batch's guard factories in the PREPARE phase — BEFORE\n // clearDefinitionGuards — so a compile-throwing factory (or a non-function)\n // aborts here with BOTH the tree AND the old definition guards intact (#1193,\n // mirror of the #1046 handler-limit hoist). adoptRouteArtifacts then installs\n // these pre-compiled functions without re-running the factories.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const compiledGuards = compileArtifactGuards(artifacts, store.depsStore!);\n\n // Clear definition lifecycle handlers (preserve external guards), then swap.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.clearDefinitionGuards();\n adoptRouteArtifacts(store, artifacts, compiledGuards);\n\n // TREE_CHANGED fires here (О-5): the new tree is committed but state is not\n // yet revalidated, so the handler sees the new tree and the still-old state.\n onCommitted?.();\n\n // Revalidate the active state against the new tree AND notify subscribers\n // (#950). A structural replace can change or drop the currently-active state;\n // emitting TRANSITION_SUCCESS makes router.subscribe / useSyncExternalStore\n // adapters re-render instead of rendering the pre-replace state. (This is the\n // one structural mutation that emits a transition event — clear() stays a\n // silent reset; the asymmetry is deliberate, see #950.)\n if (currentState !== undefined) {\n const revalidated = ctx.matchPath(currentState.path, ctx.getOptions());\n\n if (revalidated) {\n if (revalidated.name === currentState.name) {\n // Survivor — the URL still maps to the route the user was already on.\n // Keep it WITHOUT re-running guards: the user legitimately reached this\n // route via a real navigation, and `replace()` is not a navigation they\n // performed, so re-checking guards here would evict them on a stateful\n // or async guard (parity with `update()`, which never revalidates the\n // active state). Preserve the prior transition meta and emit so\n // subscribers see the revalidated state (#1201). Carry the prior\n // `context` (#1236): the route name and path are unchanged, so the\n // plugin data written into `state.context.<namespace>` (SSR data, rsc,\n // navigation, …) is still valid — the matchPath-rebuilt state would\n // otherwise wipe it, and revalidation re-runs neither the loader nor the\n // start interceptor to bring it back.\n const nextState: State = {\n ...revalidated,\n context: currentState.context,\n transition: currentState.transition,\n };\n\n commitRevalidated(ctx, nextState, currentState);\n } else {\n // Route-identity change — the URL is now owned by a DIFFERENT route (an\n // ownership reshuffle, or a newly-added `forwardTo` that teleports the\n // state). That is effectively a navigation the user never performed, so\n // consult the new route's guards exactly as `navigate` would (#1201).\n // Commit on pass; on a block — or an async guard that cannot be\n // evaluated synchronously (mirrors `canNavigateTo`) — route to\n // not-found rather than silently activating a guarded route.\n const { toDeactivate, toActivate } = getTransitionPath(\n revalidated,\n currentState,\n );\n\n const allowed =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.canNavigateTo(\n toDeactivate,\n toActivate,\n revalidated,\n currentState,\n );\n\n if (allowed) {\n const nextState: State = {\n ...revalidated,\n transition: currentState.transition,\n };\n\n commitRevalidated(ctx, nextState, currentState);\n } else {\n ctx.navigateToNotFound(currentState.path);\n }\n }\n } else {\n // The active route no longer exists in the new tree — surface it as\n // not-found (commits UNKNOWN_ROUTE + emits TRANSITION_SUCCESS) so the\n // change is observable, rather than silently clearing the state.\n ctx.navigateToNotFound(currentState.path);\n }\n }\n}\n\n/**\n * Removes a route and all its children.\n *\n * @returns true if removed, false if not found\n */\nfunction removeRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(store: RoutesStore<Dependencies>, name: string): boolean {\n // `store.definitions` is a fresh tree-derived snapshot — mutate it locally,\n // then commit the mutated table as the new tree.\n const definitions = store.definitions;\n const wasRemoved = removeFromDefinitions(definitions, name);\n\n if (!wasRemoved) {\n return false;\n }\n\n clearRouteConfigurations(\n name,\n store.config,\n store.routeCustomFields,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n store.lifecycleNamespace!,\n );\n\n commitTreeChanges(store, definitions);\n\n return true;\n}\n\n/**\n * Gets a route by name with all its configuration.\n */\nfunction getRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n name: string,\n): Route<Dependencies> | undefined {\n const segments = store.matcher.getSegmentsByName(name);\n\n if (!segments) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- segments is non-empty (checked above)\n const targetNode = segments.at(-1)! as RouteTree;\n const definition = nodeToDefinition(targetNode);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const factories = store.lifecycleNamespace!.getFactories();\n\n return enrichRoute(definition, name, store.config, factories);\n}\n\n// ============================================================================\n// API factory\n// ============================================================================\n\n// Cache the assembled RoutesApi per router — mirrors getPluginApi()/getNavigator():\n// avoids re-allocating the 9-closure bag on each call (adapters/plugins poll it\n// from constructors) and gives spy/stub helpers a stable object identity. Closures\n// capture `ctx`/`store`, both stable for the router's lifetime, so caching is safe.\n// Single cast site: the value is stored as `unknown` (RoutesApi is invariant in\n// Dependencies, so one typed map can't hold every instantiation) and cast on read.\nconst cache = new WeakMap<object, unknown>();\n\nexport function getRoutesApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): RoutesApi<Dependencies> {\n const cached = cache.get(router);\n\n if (cached) {\n return cached as RoutesApi<Dependencies>;\n }\n\n const ctx = getInternals(router);\n\n const store = ctx.routeGetStore();\n\n // Single cast site: the channel is typed with default Dependencies on\n // RouterInternals (RouterEventMap is non-generic), but payloads are built\n // with this api's Dependencies. The runtime shape is identical.\n const emitChange = (event: TreeChangedEvent<Dependencies>): void => {\n ctx.treeChanged.emit(event as TreeChangedEvent);\n };\n\n const api: RoutesApi<Dependencies> = {\n add: (routes, options) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const routeArray = Array.isArray(routes) ? routes : [routes];\n const parentName = options?.parent;\n\n guardRouteStructure(routeArray, ctx.validator);\n\n if (parentName !== undefined) {\n ctx.validator?.routes.validateParentOption(parentName, store.tree);\n }\n\n ctx.validator?.routes.throwIfInternalRouteInArray(routeArray, \"addRoute\");\n ctx.validator?.routes.validateAddRouteArgs(routeArray);\n ctx.validator?.routes.validateRoutes(routeArray, store, parentName);\n\n addRoutes(store, routeArray, parentName);\n\n // Built from the post-commit store (О-1), only when someone is listening.\n if (ctx.treeChanged.listenerCount() > 0) {\n const added = collectAddedRoutes(routeArray, parentName, store);\n\n emitChange(\n parentName === undefined\n ? { op: \"add\", added }\n : { op: \"add\", added, parent: parentName },\n );\n }\n },\n\n remove: (name) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n ctx.validator?.routes.validateRemoveRouteArgs(name);\n ctx.validator?.routes.throwIfInternalRoute(name, \"removeRoute\");\n // Always-on parity backstop (#1047 / #238): a reserved \"@@\" name is\n // internal and cannot be removed, with or without the validation-plugin.\n assertNoInternalRouteName(name, \"removeRoute\");\n\n const canRemove = validateRemoveRoute(\n name,\n ctx.getStateName(),\n ctx.isTransitioning(),\n );\n\n if (!canRemove) {\n return;\n }\n\n // Snapshot the subtree BEFORE the mutation — the nodes are gone after.\n const removedSubtree =\n ctx.treeChanged.listenerCount() > 0\n ? collectSubtree(store, name)\n : undefined;\n const wasRemoved = removeRoute(store, name);\n\n if (!wasRemoved) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" not found. No changes made.`,\n );\n\n return;\n }\n\n if (removedSubtree !== undefined) {\n emitChange({ op: \"remove\", name, removedSubtree });\n }\n },\n\n update: (name, updates) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n ctx.validator?.routes.validateUpdateRouteBasicArgs(name, updates);\n ctx.validator?.routes.throwIfInternalRoute(name, \"updateRoute\");\n // Always-on parity backstop (#1047 / #238): a reserved \"@@\" name is\n // internal and cannot be updated, with or without the validation-plugin.\n assertNoInternalRouteName(name, \"updateRoute\");\n\n ctx.validator?.routes.validateUpdateRoutePropertyTypes(name, updates);\n\n /* v8 ignore next 6 -- @preserve: race condition guard, mirrors Router.updateRoute() same-path guard tested via Router.ts unit tests */\n if (ctx.isTransitioning()) {\n logger.error(\n \"router.updateRoute\",\n `Updating route \"${name}\" while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n ctx.validator?.routes.validateUpdateRoute(name, updates, store);\n\n // #1205: bare-core existence backstop as a TRUE no-op — NOT a throw\n // (validation is opt-in). update() of a route that does not exist used to\n // seed config.defaultParams + compile/register the guard (commitRouteUpdate\n // below) and emit a lying TREE_CHANGED \"update\" event for a route get()/\n // has() cannot see; a future add() of that name then inherited the phantom\n // config + a blocking guard. Skip the commit and the emit entirely when the\n // route is absent. (With the validation-plugin, validateUpdateRoute above\n // already threw a ReferenceError, so this is only reached in bare core.)\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n // Field-patch commit core (NO_TREE_REBUILD) — co-located in routesStore.ts\n // beside the add/replace (adoptRouteArtifacts) / remove (commitTreeChanges)\n // / clear (resetStore) cores. Returns the structural fields for the\n // conditional emit below (each user getter read once inside).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycle = store.lifecycleNamespace!;\n const structural = commitRouteUpdate(store, lifecycle, name, updates);\n\n // Conditional emit: structural fields only. A guard-only or empty patch\n // produces no event (О-7 + empty-patch rule).\n if (ctx.treeChanged.listenerCount() > 0) {\n const patch = buildStructuralPatch<Dependencies>(structural);\n\n if (Object.keys(patch).length > 0) {\n emitChange({ op: \"update\", name, patch });\n }\n }\n },\n\n clear: () => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const canClear = validateClearRoutes(ctx.isTransitioning());\n\n /* v8 ignore next 3 -- @preserve: race condition guard, mirrors Router.clearRoutes() same-path guard tested via validateClearRoutes unit tests */\n if (!canClear) {\n return;\n }\n\n // Snapshot the routes BEFORE the reset empties them. Emitted whenever\n // there is a listener — even for an empty clear (О-4).\n const removed =\n ctx.treeChanged.listenerCount() > 0\n ? Object.freeze([...collectFlatRoutes(store, () => true).values()])\n : undefined;\n\n resetStore(store);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.clearAll();\n ctx.clearState();\n\n if (removed !== undefined) {\n emitChange({ op: \"clear\", removed });\n }\n },\n\n has: (name) => {\n ctx.validator?.routes.validateRouteName(name, \"hasRoute\");\n\n return store.matcher.hasRoute(name);\n },\n\n get: (name) => {\n ctx.validator?.routes.validateRouteName(name, \"getRoute\");\n\n return getRoute(store, name);\n },\n\n replace: (routes) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const routeArray = Array.isArray(routes) ? routes : [routes];\n\n const canReplace = validateClearRoutes(ctx.isTransitioning());\n\n if (!canReplace) {\n return;\n }\n\n guardRouteStructure(routeArray, ctx.validator);\n\n ctx.validator?.routes.throwIfInternalRouteInArray(\n routeArray,\n \"replaceRoutes\",\n );\n ctx.validator?.routes.validateAddRouteArgs(routeArray);\n ctx.validator?.routes.validateRoutes(routeArray, store);\n\n const currentState = router.getState();\n\n // The flat removed/added diff is O(N) — compute it only when someone is\n // listening (Решение 3.B). Snapshot the old tree BEFORE the swap.\n const before =\n ctx.treeChanged.listenerCount() > 0\n ? collectFlatRoutes(store, () => true)\n : undefined;\n\n replaceRoutes(\n store,\n routeArray,\n ctx,\n currentState,\n before === undefined\n ? undefined\n : () => {\n const after = collectFlatRoutes(store, () => true);\n const { removed, added } = diffFlatRoutes(before, after);\n\n emitChange({ op: \"replace\", removed, added });\n },\n );\n },\n\n subscribeChanges: (handler) => ctx.treeChanged.subscribe(handler),\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { DependenciesApi } from \"./types\";\nimport type { DependenciesStore } from \"../namespaces\";\nimport type { RouterValidator } from \"../types/RouterValidator\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n// =============================================================================\n// Module-private CRUD functions\n// =============================================================================\n\nfunction setDependency(\n store: DependenciesStore,\n dependencyName: string,\n dependencyValue: unknown,\n validator?: RouterValidator | null,\n): void {\n // undefined = \"don't set\" (feature for conditional setting)\n if (dependencyValue === undefined) {\n return;\n }\n\n const isNewKey = !Object.hasOwn(store.dependencies, dependencyName);\n\n if (isNewKey) {\n // Only check limit when adding new keys (overwrites don't increase count)\n validator?.dependencies.validateDependencyCount(store, \"setDependency\");\n } else {\n const oldValue = (store.dependencies as Record<string, unknown>)[\n dependencyName\n ];\n const isChanging = oldValue !== dependencyValue;\n // Special case for NaN idempotency (NaN !== NaN is always true)\n const bothAreNaN = Number.isNaN(oldValue) && Number.isNaN(dependencyValue);\n\n if (isChanging && !bothAreNaN) {\n validator?.dependencies.warnOverwrite(dependencyName, \"setDependency\");\n }\n }\n\n (store.dependencies as Record<string, unknown>)[dependencyName] =\n dependencyValue;\n}\n\nfunction setMultipleDependencies(\n store: DependenciesStore,\n deps: Record<string, unknown>,\n validator?: RouterValidator | null,\n): void {\n const overwrittenKeys: string[] = [];\n\n for (const key in deps) {\n if (deps[key] === undefined) {\n continue;\n }\n\n if (Object.hasOwn(store.dependencies, key)) {\n overwrittenKeys.push(key);\n } else {\n validator?.dependencies.validateDependencyCount(store, \"setDependencies\");\n }\n\n (store.dependencies as Record<string, unknown>)[key] = deps[key];\n }\n\n if (overwrittenKeys.length > 0) {\n validator?.dependencies.warnBatchOverwrite(\n overwrittenKeys,\n \"setDependencies\",\n );\n }\n}\n\n// =============================================================================\n// Public API factory\n// =============================================================================\n\nexport function getDependenciesApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): DependenciesApi<Dependencies> {\n const ctx = getInternals(router);\n\n return {\n get: (name) => {\n ctx.validator?.dependencies.validateDependencyName(name, \"getDependency\");\n\n const store = ctx.dependenciesGetStore();\n const value = (store.dependencies as Record<string, unknown>)[\n name as string\n ];\n\n ctx.validator?.dependencies.validateDependencyExists(\n name as string,\n store,\n );\n\n return value as Dependencies[typeof name];\n },\n getAll: () => ({ ...ctx.dependenciesGetStore().dependencies }),\n set: (name, value) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.dependencies.validateSetDependencyArgs(\n name,\n value,\n \"setDependency\",\n );\n\n setDependency(ctx.dependenciesGetStore(), name, value, ctx.validator);\n },\n setAll: (deps) => {\n throwIfDisposed(ctx.isDisposed);\n\n const store = ctx.dependenciesGetStore();\n\n ctx.validator?.dependencies.validateDependenciesObject(\n deps,\n \"setDependencies\",\n );\n\n setMultipleDependencies(\n store,\n deps as Record<string, unknown>,\n ctx.validator,\n );\n },\n remove: (name) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.dependencies.validateDependencyName(\n name,\n \"removeDependency\",\n );\n\n const store = ctx.dependenciesGetStore();\n\n if (!Object.hasOwn(store.dependencies, name)) {\n ctx.validator?.dependencies.warnRemoveNonExistent(name);\n }\n\n delete (store.dependencies as Record<string, unknown>)[name as string];\n },\n reset: () => {\n throwIfDisposed(ctx.isDisposed);\n const store = ctx.dependenciesGetStore();\n\n store.dependencies = Object.create(null) as Partial<Dependencies>;\n },\n has: (name) => {\n ctx.validator?.dependencies.validateDependencyName(name, \"hasDependency\");\n\n return Object.hasOwn(ctx.dependenciesGetStore().dependencies, name);\n },\n };\n}\n"],"mappings":"sNAYA,SAAgB,EACd,EACA,EACA,EACS,CACT,GAAI,EAAkB,CACpB,IAAM,EAAe,IAAqB,EACpC,EAAoB,EAAiB,WAAW,GAAG,EAAK,EAAE,EAEhE,GAAI,GAAgB,EAAmB,CACrC,IAAM,EAAS,EAAe,GAAK,eAAe,EAAiB,IAOnE,OALA,EAAA,OAAO,KACL,qBACA,wBAAwB,EAAK,4BAA4B,EAAO,uBAClE,EAEO,EACT,CACF,CASA,OAPI,GACF,EAAA,OAAO,KACL,qBACA,UAAU,EAAK,+EACjB,EAGK,EACT,CASA,SAAgB,EAAoB,EAAgC,CAUlE,OATI,GACF,EAAA,OAAO,MACL,qBACA,u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WAAW,aAAa,sBAAsB,CAAI,EAGxD,OAAQ,EAAM,aAAyC,EACzD,EACA,UAAa,CACX,EAAA,EAAgB,EAAI,UAAU,EAC9B,IAAM,EAAQ,EAAI,qBAAqB,EAEvC,EAAM,aAAe,OAAO,OAAO,IAAI,CACzC,EACA,IAAM,IACJ,EAAI,WAAW,aAAa,uBAAuB,EAAM,eAAe,EAEjE,OAAO,OAAO,EAAI,qBAAqB,CAAC,CAAC,aAAc,CAAI,EAEtE,CACF"}
|
|
1
|
+
{"version":3,"file":"api.js","names":["buildAddArtifacts","buildReplaceArtifacts","compileArtifactGuards","getTransitionPath","removeFromDefinitions","nodeToDefinition","getInternals","commitRouteUpdate","getInternals"],"sources":["../../src/namespaces/RoutesNamespace/routeGuards.ts","../../src/api/getRoutesApi.ts","../../src/api/getDependenciesApi.ts"],"sourcesContent":["import type { RouterLogger } from \"../../types\";\n\n/**\n * Validates removeRoute constraints.\n * Returns false if removal should be blocked (route is active).\n * Logs warnings for edge cases.\n *\n * @param name - Route name to remove\n * @param currentStateName - Current active route name (or undefined)\n * @param isNavigating - Whether navigation is in progress\n * @param logger - Per-router logger instance (from `getInternals(router).logger`)\n * @returns true if removal can proceed, false if blocked\n */\nexport function validateRemoveRoute(\n name: string,\n currentStateName: string | undefined,\n isNavigating: boolean,\n logger: RouterLogger,\n): boolean {\n if (currentStateName) {\n const isExactMatch = currentStateName === name;\n const isParentOfCurrent = currentStateName.startsWith(`${name}.`);\n\n if (isExactMatch || isParentOfCurrent) {\n const suffix = isExactMatch ? \"\" : ` (current: \"${currentStateName}\")`;\n\n logger.warn(\n \"router.removeRoute\",\n `Cannot remove route \"${name}\" — it is currently active${suffix}. Navigate away first.`,\n );\n\n return false;\n }\n }\n\n if (isNavigating) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" removed while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n return true;\n}\n\n/**\n * Validates clearRoutes operation.\n * Returns false if operation should be blocked (navigation in progress).\n *\n * @param isNavigating - Whether navigation is in progress\n * @param logger - Per-router logger instance (from `getInternals(router).logger`)\n * @returns true if clearRoutes can proceed, false if blocked\n */\nexport function validateClearRoutes(\n isNavigating: boolean,\n logger: RouterLogger,\n): boolean {\n if (isNavigating) {\n logger.error(\n \"router.clearRoutes\",\n \"Cannot clear routes while navigation is in progress. Wait for navigation to complete.\",\n );\n\n return false;\n }\n\n return true;\n}\n","import { nodeToDefinition } from \"../engine\";\nimport { throwIfDisposed, throwIfReentrantTreeMutation } from \"./helpers\";\nimport { guardRouteStructure } from \"../guards\";\nimport { getInternals } from \"../internals\";\nimport {\n clearConfigEntries,\n removeFromDefinitions,\n} from \"../namespaces/RoutesNamespace/helpers\";\nimport {\n validateClearRoutes,\n validateRemoveRoute,\n} from \"../namespaces/RoutesNamespace/routeGuards\";\nimport {\n adoptRouteArtifacts,\n assertAddable,\n assertNoDuplicateNamesInBatch,\n assertNoDuplicatePathsInBatch,\n assertNoInternalNamesInBatch,\n assertNoInternalRouteName,\n buildAddArtifacts,\n buildReplaceArtifacts,\n commitRouteUpdate,\n commitTreeChanges,\n compileArtifactGuards,\n resetStore,\n} from \"../namespaces/RoutesNamespace/routesStore\";\nimport { getTransitionPath } from \"../transitionPath\";\n\nimport type { RoutesApi } from \"./types\";\nimport type { RouteDefinition, RouteTree } from \"../engine\";\nimport type { RouterInternals } from \"../internals\";\nimport type { RouteLifecycleNamespace, RouteConfig } from \"../namespaces\";\nimport type { RoutesStore } from \"../namespaces/RoutesNamespace\";\nimport type {\n DefaultDependencies,\n ForwardToCallback,\n NavigationOptions,\n Params,\n Router,\n RouterLogger,\n State,\n TreeChangedEvent,\n TreeStructuralPatch,\n GuardFnFactory,\n Route,\n} from \"../types\";\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Opts attached to the `TRANSITION_SUCCESS` emitted by `replace()` when it\n * revalidates the active state (#950). `replace` does not push history, so it\n * is a replace-type success — matching `navigateToNotFound`'s opts for the\n * dropped-route branch.\n */\nconst REVALIDATE_OPTS: NavigationOptions = Object.freeze({\n replace: true,\n revalidate: true,\n});\n\n/**\n * Clears all config entries and lifecycle handlers for a removed route\n * (and all its descendants).\n */\nfunction clearRouteConfigurations<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routeName: string,\n config: RouteConfig,\n routeCustomFields: Record<string, Record<string, unknown>>,\n lifecycleNamespace: RouteLifecycleNamespace<Dependencies>,\n): void {\n const shouldClear = (name: string): boolean =>\n name === routeName || name.startsWith(`${routeName}.`);\n\n clearConfigEntries(config.decoders, shouldClear);\n clearConfigEntries(config.encoders, shouldClear);\n clearConfigEntries(config.defaultParams, shouldClear);\n clearConfigEntries(config.forwardMap, shouldClear);\n clearConfigEntries(config.forwardFnMap, shouldClear);\n clearConfigEntries(routeCustomFields, shouldClear);\n\n // Clear forwardMap entries pointing TO the deleted route (or its descendants)\n clearConfigEntries(config.forwardMap, (key) =>\n shouldClear(config.forwardMap[key]),\n );\n\n // Clear lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n lifecycleNamespace.getFactories();\n\n for (const name of Object.keys(canActivateFactories)) {\n if (shouldClear(name)) {\n // Route removed from the tree — both origin slots go (route no longer exists).\n lifecycleNamespace.clearCanActivate(name, \"both\");\n }\n }\n\n for (const name of Object.keys(canDeactivateFactories)) {\n if (shouldClear(name)) {\n lifecycleNamespace.clearCanDeactivate(name, \"both\");\n }\n }\n}\n\n/**\n * Re-attaches the stored config (forwardTo / defaultParams / encode-decode) and\n * lifecycle guards for `lookupName` onto `route`, then returns it (mutates in\n * place). Shared by {@link enrichRoute} (nested, bare `name`) and\n * {@link buildFlatRoute} (flat, full dotted `name`) — one source of truth for\n * the route-config field set.\n */\nfunction assignRouteConfig<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n route: Route<Dependencies>,\n lookupName: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const forwardToFn = config.forwardFnMap[lookupName];\n const forwardToStr = config.forwardMap[lookupName];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (forwardToFn !== undefined) {\n route.forwardTo = forwardToFn;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n } else if (forwardToStr !== undefined) {\n route.forwardTo = forwardToStr;\n }\n\n if (lookupName in config.defaultParams) {\n route.defaultParams = config.defaultParams[lookupName];\n }\n\n if (lookupName in config.decoders) {\n route.decodeParams = config.decoders[lookupName];\n }\n\n if (lookupName in config.encoders) {\n route.encodeParams = config.encoders[lookupName];\n }\n\n const [canDeactivateFactories, canActivateFactories] = factories;\n\n if (lookupName in canActivateFactories) {\n route.canActivate = canActivateFactories[lookupName];\n }\n\n if (lookupName in canDeactivateFactories) {\n route.canDeactivate = canDeactivateFactories[lookupName];\n }\n\n return route;\n}\n\n/**\n * Builds a full Route object from a bare RouteDefinition by re-attaching\n * config entries and lifecycle factories.\n *\n * RECURSIVE — call with the factories tuple obtained ONCE from\n * `lifecycleNamespace.getFactories()` and pass it through to children.\n */\nfunction enrichRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routeDef: RouteDefinition,\n routeName: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const route: Route<Dependencies> = {\n name: routeDef.name,\n path: routeDef.path,\n };\n\n assignRouteConfig(route, routeName, config, factories);\n\n if (routeDef.children) {\n route.children = routeDef.children.map((child) =>\n enrichRoute(child, `${routeName}.${child.name}`, config, factories),\n );\n }\n\n return route;\n}\n\n// ============================================================================\n// TREE_CHANGED payload helpers\n// ============================================================================\n\n/**\n * Builds a single FLAT `Route` for `fullName` from the store config + lifecycle\n * factories — `name` is the FULL dotted name and there is no `children` array\n * (consumers want a flat, by-name list). Frozen on construction.\n */\nfunction buildFlatRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n fullName: string,\n path: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const route: Route<Dependencies> = { name: fullName, path };\n\n assignRouteConfig(route, fullName, config, factories);\n\n return Object.freeze(route);\n}\n\n/**\n * Walks the store's definitions depth-first, building a FLAT\n * `Map<fullName, Route>` for every node whose full dotted name satisfies\n * `include`. Reads the live store, so call it at the right moment relative to\n * the mutation (before for removed, after for added).\n */\nfunction collectFlatRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n include: (fullName: string) => boolean,\n): Map<string, Route<Dependencies>> {\n const result = new Map<string, Route<Dependencies>>();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const factories = store.lifecycleNamespace!.getFactories();\n\n const walk = (defs: readonly RouteDefinition[], parentName: string): void => {\n for (const def of defs) {\n const fullName = parentName ? `${parentName}.${def.name}` : def.name;\n\n if (include(fullName)) {\n result.set(\n fullName,\n buildFlatRoute(fullName, def.path, store.config, factories),\n );\n }\n\n if (def.children) {\n walk(def.children, fullName);\n }\n }\n };\n\n walk(store.definitions, \"\");\n\n return result;\n}\n\n/**\n * Collects the route `name` and all of its descendants as a FLAT, frozen array.\n * MUST be called BEFORE the removal mutation — the nodes are gone afterwards.\n */\nfunction collectSubtree<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n name: string,\n): readonly Route<Dependencies>[] {\n const prefix = `${name}.`;\n const subtree = collectFlatRoutes(\n store,\n (fullName) => fullName === name || fullName.startsWith(prefix),\n );\n\n return Object.freeze([...subtree.values()]);\n}\n\n/**\n * Builds the FLAT, frozen payload array for an `add`, walking only the input\n * routes — O(added), not O(tree). `path` is taken from the input verbatim\n * (`sanitizeRoute` never rewrites it); config fields are read from the\n * post-commit store by full name. `add` never removes, so the input subtree is\n * exactly what changed.\n */\nfunction collectAddedRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n parentName: string | undefined,\n store: RoutesStore<Dependencies>,\n): readonly Route<Dependencies>[] {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const factories = store.lifecycleNamespace!.getFactories();\n const result: Route<Dependencies>[] = [];\n\n const walk = (\n input: readonly Route<Dependencies>[],\n parent: string,\n ): void => {\n for (const route of input) {\n const fullName = parent ? `${parent}.${route.name}` : route.name;\n\n result.push(\n buildFlatRoute(fullName, route.path, store.config, factories),\n );\n\n if (route.children) {\n walk(route.children, fullName);\n }\n }\n };\n\n walk(routes, parentName ?? \"\");\n\n return Object.freeze(result);\n}\n\n/** Diffs two flat route maps by full name into frozen removed/added arrays. */\nfunction diffFlatRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n before: ReadonlyMap<string, Route<Dependencies>>,\n after: ReadonlyMap<string, Route<Dependencies>>,\n): {\n removed: readonly Route<Dependencies>[];\n added: readonly Route<Dependencies>[];\n} {\n const removed: Route<Dependencies>[] = [];\n const added: Route<Dependencies>[] = [];\n\n for (const [fullName, route] of before) {\n if (!after.has(fullName)) {\n removed.push(route);\n }\n }\n\n for (const [fullName, route] of after) {\n if (!before.has(fullName)) {\n added.push(route);\n }\n }\n\n return { removed: Object.freeze(removed), added: Object.freeze(added) };\n}\n\n/**\n * Builds the structural subset of an `update()` patch (forwardTo /\n * defaultParams / encodeParams / decodeParams) from the already-destructured\n * update fields — so user getters are not re-invoked. A guard-only patch yields\n * an empty object → the caller emits no TREE_CHANGED (О-7: guards are\n * invoked-on-demand, not cached, so they need no observation channel).\n *\n * The returned envelope is a fresh object (caller's patch untouched) and is\n * frozen on construction. Nested values (e.g. `defaultParams`) are kept by\n * reference — the same objects the router stored — so exotic inputs (circular\n * refs, class instances) are tolerated, matching `update()`'s existing contract.\n */\nfunction buildStructuralPatch<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(fields: {\n forwardTo?: string | ForwardToCallback<Dependencies> | null | undefined;\n defaultParams?: Params | null | undefined;\n decodeParams?: ((params: Params) => Params) | null | undefined;\n encodeParams?: ((params: Params) => Params) | null | undefined;\n}): Readonly<TreeStructuralPatch<Dependencies>> {\n const patch: TreeStructuralPatch<Dependencies> = {};\n\n if (fields.forwardTo !== undefined) {\n patch.forwardTo = fields.forwardTo;\n }\n\n if (fields.defaultParams !== undefined) {\n patch.defaultParams = fields.defaultParams;\n }\n\n if (fields.encodeParams !== undefined) {\n patch.encodeParams = fields.encodeParams;\n }\n\n if (fields.decodeParams !== undefined) {\n patch.decodeParams = fields.decodeParams;\n }\n\n return Object.freeze(patch);\n}\n\n// ============================================================================\n// CRUD operations\n// ============================================================================\n\n/**\n * Adds one or more routes to the router.\n * Input already validated by facade.\n */\nfunction addRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n routes: Route<Dependencies>[],\n parentName: string | undefined,\n logger: RouterLogger,\n): void {\n // Prepare-then-commit (issue #698): reject the silent-corruption cases\n // up front (dup name vs existing, missing parent), build the merged tree /\n // config into locals (async/circular forwardTo + invalid constraint throw\n // here), then swap atomically. A rejected add leaves the store untouched.\n assertAddable(store, routes, parentName);\n\n const artifacts = buildAddArtifacts(store, routes, parentName, logger);\n\n // Pre-flight the #961 handler-limit into PREPARE so a limit-exceeding batch\n // aborts before the swap (#1046). `add` does not clear guards, so the\n // projection runs against the live union count (clearsDefinition = false).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.preflightHandlerLimit(\n artifacts.pendingCanActivate.keys(),\n artifacts.pendingCanDeactivate.keys(),\n false,\n );\n\n adoptRouteArtifacts(store, artifacts);\n}\n\n/**\n * Commits a revalidated state after `replace()` and emits `TRANSITION_SUCCESS`\n * so `router.subscribe` / adapters re-render (#950). The emit carries\n * `REVALIDATE_OPTS` — the single distinguishable marker (`revalidate: true`) a\n * plugin's `onTransitionSuccess` can read to special-case a revalidation vs a\n * real navigation (#1201).\n */\nfunction commitRevalidated<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n ctx: RouterInternals<Dependencies>,\n nextState: State,\n fromState: State,\n): void {\n ctx.setState(nextState);\n ctx.emitTransitionSuccess(nextState, fromState, REVALIDATE_OPTS);\n}\n\n/**\n * Atomically replaces all routes with a new set (HMR / code-splitting).\n * Prepare-then-commit (issue #698): the new set is fully built into locals\n * first — a circular/async forwardTo or invalid path throws here, leaving the\n * existing tree intact — then committed.\n */\nfunction replaceRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n routes: Route<Dependencies>[],\n ctx: RouterInternals<Dependencies>,\n currentState: State | undefined,\n onCommitted?: () => void,\n): void {\n // Reject the silent-corruption cases `assertAddable` catches for `add`, BEFORE\n // building/swapping, so bare-core parity is symmetric (#1047): within-batch\n // duplicate names (#968), reserved \"@@\" names (#954), and within-batch\n // duplicate paths (#955). methodName is \"addRoute\" to match validation-plugin\n // (which reports \"addRoute\" for replace batches too), so the no-plugin error\n // is identical to the with-plugin one.\n assertNoInternalNamesInBatch(routes, \"addRoute\");\n assertNoDuplicateNamesInBatch(routes, \"\", \"addRoute\");\n assertNoDuplicatePathsInBatch(routes, \"\", \"addRoute\");\n\n // Build the whole new set BEFORE touching the store.\n const artifacts = buildReplaceArtifacts(\n routes,\n store.rootPath,\n store.matcherOptions,\n ctx.logger,\n );\n\n // Pre-flight the #961 handler-limit BEFORE clearDefinitionGuards mutates, so a\n // limit-exceeding batch aborts with BOTH the tree and the definition guards\n // intact (#1046). replace clears definition guards first, so the projection\n // runs against the surviving external guards (clearsDefinition = true).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.preflightHandlerLimit(\n artifacts.pendingCanActivate.keys(),\n artifacts.pendingCanDeactivate.keys(),\n true,\n );\n\n // Pre-compile the new batch's guard factories in the PREPARE phase — BEFORE\n // clearDefinitionGuards — so a compile-throwing factory (or a non-function)\n // aborts here with BOTH the tree AND the old definition guards intact (#1193,\n // mirror of the #1046 handler-limit hoist). adoptRouteArtifacts then installs\n // these pre-compiled functions without re-running the factories.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const compiledGuards = compileArtifactGuards(artifacts, store.depsStore!);\n\n // Clear definition lifecycle handlers (preserve external guards), then swap.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.clearDefinitionGuards();\n adoptRouteArtifacts(store, artifacts, compiledGuards);\n\n // TREE_CHANGED fires here (О-5): the new tree is committed but state is not\n // yet revalidated, so the handler sees the new tree and the still-old state.\n onCommitted?.();\n\n // Revalidate the active state against the new tree AND notify subscribers\n // (#950). A structural replace can change or drop the currently-active state;\n // emitting TRANSITION_SUCCESS makes router.subscribe / useSyncExternalStore\n // adapters re-render instead of rendering the pre-replace state. (This is the\n // one structural mutation that emits a transition event — clear() stays a\n // silent reset; the asymmetry is deliberate, see #950.)\n if (currentState !== undefined) {\n const revalidated = ctx.matchPath(currentState.path, ctx.getOptions());\n\n if (revalidated) {\n if (revalidated.name === currentState.name) {\n // Survivor — the URL still maps to the route the user was already on.\n // Keep it WITHOUT re-running guards: the user legitimately reached this\n // route via a real navigation, and `replace()` is not a navigation they\n // performed, so re-checking guards here would evict them on a stateful\n // or async guard (parity with `update()`, which never revalidates the\n // active state). Preserve the prior transition meta and emit so\n // subscribers see the revalidated state (#1201). Carry the prior\n // `context` (#1236): the route name and path are unchanged, so the\n // plugin data written into `state.context.<namespace>` (SSR data, rsc,\n // navigation, …) is still valid — the matchPath-rebuilt state would\n // otherwise wipe it, and revalidation re-runs neither the loader nor the\n // start interceptor to bring it back.\n const nextState: State = {\n ...revalidated,\n context: currentState.context,\n transition: currentState.transition,\n };\n\n commitRevalidated(ctx, nextState, currentState);\n } else {\n // Route-identity change — the URL is now owned by a DIFFERENT route (an\n // ownership reshuffle, or a newly-added `forwardTo` that teleports the\n // state). That is effectively a navigation the user never performed, so\n // consult the new route's guards exactly as `navigate` would (#1201).\n // Commit on pass; on a block — or an async guard that cannot be\n // evaluated synchronously (mirrors `canNavigateTo`) — route to\n // not-found rather than silently activating a guarded route.\n const { toDeactivate, toActivate } = getTransitionPath(\n revalidated,\n currentState,\n );\n\n const allowed =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.canNavigateTo(\n toDeactivate,\n toActivate,\n revalidated,\n currentState,\n );\n\n if (allowed) {\n const nextState: State = {\n ...revalidated,\n transition: currentState.transition,\n };\n\n commitRevalidated(ctx, nextState, currentState);\n } else {\n ctx.navigateToNotFound(currentState.path);\n }\n }\n } else {\n // The active route no longer exists in the new tree — surface it as\n // not-found (commits UNKNOWN_ROUTE + emits TRANSITION_SUCCESS) so the\n // change is observable, rather than silently clearing the state.\n ctx.navigateToNotFound(currentState.path);\n }\n }\n}\n\n/**\n * Removes a route and all its children.\n *\n * @returns true if removed, false if not found\n */\nfunction removeRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(store: RoutesStore<Dependencies>, name: string): boolean {\n // `store.definitions` is a fresh tree-derived snapshot — mutate it locally,\n // then commit the mutated table as the new tree.\n const definitions = store.definitions;\n const wasRemoved = removeFromDefinitions(definitions, name);\n\n if (!wasRemoved) {\n return false;\n }\n\n clearRouteConfigurations(\n name,\n store.config,\n store.routeCustomFields,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n store.lifecycleNamespace!,\n );\n\n commitTreeChanges(store, definitions);\n\n return true;\n}\n\n/**\n * Gets a route by name with all its configuration.\n */\nfunction getRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n name: string,\n): Route<Dependencies> | undefined {\n const segments = store.matcher.getSegmentsByName(name);\n\n if (!segments) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- segments is non-empty (checked above)\n const targetNode = segments.at(-1)! as RouteTree;\n const definition = nodeToDefinition(targetNode);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const factories = store.lifecycleNamespace!.getFactories();\n\n return enrichRoute(definition, name, store.config, factories);\n}\n\n// ============================================================================\n// API factory\n// ============================================================================\n\n// Cache the assembled RoutesApi per router — mirrors getPluginApi()/getNavigator():\n// avoids re-allocating the 9-closure bag on each call (adapters/plugins poll it\n// from constructors) and gives spy/stub helpers a stable object identity. Closures\n// capture `ctx`/`store`, both stable for the router's lifetime, so caching is safe.\n// Single cast site: the value is stored as `unknown` (RoutesApi is invariant in\n// Dependencies, so one typed map can't hold every instantiation) and cast on read.\nconst cache = new WeakMap<object, unknown>();\n\nexport function getRoutesApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): RoutesApi<Dependencies> {\n const cached = cache.get(router);\n\n if (cached) {\n return cached as RoutesApi<Dependencies>;\n }\n\n const ctx = getInternals(router);\n\n const store = ctx.routeGetStore();\n\n // Single cast site: the channel is typed with default Dependencies on\n // RouterInternals (RouterEventMap is non-generic), but payloads are built\n // with this api's Dependencies. The runtime shape is identical.\n const emitChange = (event: TreeChangedEvent<Dependencies>): void => {\n ctx.treeChanged.emit(event as TreeChangedEvent);\n };\n\n const api: RoutesApi<Dependencies> = {\n add: (routes, options) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const routeArray = Array.isArray(routes) ? routes : [routes];\n const parentName = options?.parent;\n\n guardRouteStructure(routeArray, ctx.validator);\n\n if (parentName !== undefined) {\n ctx.validator?.routes.validateParentOption(parentName, store.tree);\n }\n\n ctx.validator?.routes.throwIfInternalRouteInArray(routeArray, \"addRoute\");\n ctx.validator?.routes.validateAddRouteArgs(routeArray);\n ctx.validator?.routes.validateRoutes(routeArray, store, parentName);\n\n addRoutes(store, routeArray, parentName, ctx.logger);\n\n // Built from the post-commit store (О-1), only when someone is listening.\n if (ctx.treeChanged.listenerCount() > 0) {\n const added = collectAddedRoutes(routeArray, parentName, store);\n\n emitChange(\n parentName === undefined\n ? { op: \"add\", added }\n : { op: \"add\", added, parent: parentName },\n );\n }\n },\n\n remove: (name) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n ctx.validator?.routes.validateRemoveRouteArgs(name);\n ctx.validator?.routes.throwIfInternalRoute(name, \"removeRoute\");\n // Always-on parity backstop (#1047 / #238): a reserved \"@@\" name is\n // internal and cannot be removed, with or without the validation-plugin.\n assertNoInternalRouteName(name, \"removeRoute\");\n\n const canRemove = validateRemoveRoute(\n name,\n ctx.getStateName(),\n ctx.isTransitioning(),\n ctx.logger,\n );\n\n if (!canRemove) {\n return;\n }\n\n // Snapshot the subtree BEFORE the mutation — the nodes are gone after.\n const removedSubtree =\n ctx.treeChanged.listenerCount() > 0\n ? collectSubtree(store, name)\n : undefined;\n const wasRemoved = removeRoute(store, name);\n\n if (!wasRemoved) {\n ctx.logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" not found. No changes made.`,\n );\n\n return;\n }\n\n if (removedSubtree !== undefined) {\n emitChange({ op: \"remove\", name, removedSubtree });\n }\n },\n\n update: (name, updates) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n ctx.validator?.routes.validateUpdateRouteBasicArgs(name, updates);\n ctx.validator?.routes.throwIfInternalRoute(name, \"updateRoute\");\n // Always-on parity backstop (#1047 / #238): a reserved \"@@\" name is\n // internal and cannot be updated, with or without the validation-plugin.\n assertNoInternalRouteName(name, \"updateRoute\");\n\n ctx.validator?.routes.validateUpdateRoutePropertyTypes(name, updates);\n\n /* v8 ignore next 6 -- @preserve: race condition guard, mirrors Router.updateRoute() same-path guard tested via Router.ts unit tests */\n if (ctx.isTransitioning()) {\n ctx.logger.error(\n \"router.updateRoute\",\n `Updating route \"${name}\" while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n ctx.validator?.routes.validateUpdateRoute(name, updates, store);\n\n // #1205: bare-core existence backstop as a TRUE no-op — NOT a throw\n // (validation is opt-in). update() of a route that does not exist used to\n // seed config.defaultParams + compile/register the guard (commitRouteUpdate\n // below) and emit a lying TREE_CHANGED \"update\" event for a route get()/\n // has() cannot see; a future add() of that name then inherited the phantom\n // config + a blocking guard. Skip the commit and the emit entirely when the\n // route is absent. (With the validation-plugin, validateUpdateRoute above\n // already threw a ReferenceError, so this is only reached in bare core.)\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n // Field-patch commit core (NO_TREE_REBUILD) — co-located in routesStore.ts\n // beside the add/replace (adoptRouteArtifacts) / remove (commitTreeChanges)\n // / clear (resetStore) cores. Returns the structural fields for the\n // conditional emit below (each user getter read once inside).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycle = store.lifecycleNamespace!;\n const structural = commitRouteUpdate(store, lifecycle, name, updates);\n\n // Conditional emit: structural fields only. A guard-only or empty patch\n // produces no event (О-7 + empty-patch rule).\n if (ctx.treeChanged.listenerCount() > 0) {\n const patch = buildStructuralPatch<Dependencies>(structural);\n\n if (Object.keys(patch).length > 0) {\n emitChange({ op: \"update\", name, patch });\n }\n }\n },\n\n clear: () => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const canClear = validateClearRoutes(ctx.isTransitioning(), ctx.logger);\n\n /* v8 ignore next 3 -- @preserve: race condition guard, mirrors Router.clearRoutes() same-path guard tested via validateClearRoutes unit tests */\n if (!canClear) {\n return;\n }\n\n // Snapshot the routes BEFORE the reset empties them. Emitted whenever\n // there is a listener — even for an empty clear (О-4).\n const removed =\n ctx.treeChanged.listenerCount() > 0\n ? Object.freeze([...collectFlatRoutes(store, () => true).values()])\n : undefined;\n\n resetStore(store);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.clearAll();\n ctx.clearState();\n\n if (removed !== undefined) {\n emitChange({ op: \"clear\", removed });\n }\n },\n\n has: (name) => {\n ctx.validator?.routes.validateRouteName(name, \"hasRoute\");\n\n return store.matcher.hasRoute(name);\n },\n\n get: (name) => {\n ctx.validator?.routes.validateRouteName(name, \"getRoute\");\n\n return getRoute(store, name);\n },\n\n replace: (routes) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const routeArray = Array.isArray(routes) ? routes : [routes];\n\n const canReplace = validateClearRoutes(ctx.isTransitioning(), ctx.logger);\n\n if (!canReplace) {\n return;\n }\n\n guardRouteStructure(routeArray, ctx.validator);\n\n ctx.validator?.routes.throwIfInternalRouteInArray(\n routeArray,\n \"replaceRoutes\",\n );\n ctx.validator?.routes.validateAddRouteArgs(routeArray);\n ctx.validator?.routes.validateRoutes(routeArray, store);\n\n const currentState = router.getState();\n\n // The flat removed/added diff is O(N) — compute it only when someone is\n // listening (Решение 3.B). Snapshot the old tree BEFORE the swap.\n const before =\n ctx.treeChanged.listenerCount() > 0\n ? collectFlatRoutes(store, () => true)\n : undefined;\n\n replaceRoutes(\n store,\n routeArray,\n ctx,\n currentState,\n before === undefined\n ? undefined\n : () => {\n const after = collectFlatRoutes(store, () => true);\n const { removed, added } = diffFlatRoutes(before, after);\n\n emitChange({ op: \"replace\", removed, added });\n },\n );\n },\n\n subscribeChanges: (handler) => ctx.treeChanged.subscribe(handler),\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { DependenciesApi } from \"./types\";\nimport type { DependenciesStore } from \"../namespaces\";\nimport type { DefaultDependencies, Router } from \"../types\";\nimport type { RouterValidator } from \"../types/RouterValidator\";\n\n// =============================================================================\n// Module-private CRUD functions\n// =============================================================================\n\nfunction setDependency(\n store: DependenciesStore,\n dependencyName: string,\n dependencyValue: unknown,\n validator?: RouterValidator | null,\n): void {\n // undefined = \"don't set\" (feature for conditional setting)\n if (dependencyValue === undefined) {\n return;\n }\n\n const isNewKey = !Object.hasOwn(store.dependencies, dependencyName);\n\n if (isNewKey) {\n // Only check limit when adding new keys (overwrites don't increase count)\n validator?.dependencies.validateDependencyCount(store, \"setDependency\");\n } else {\n const oldValue = (store.dependencies as Record<string, unknown>)[\n dependencyName\n ];\n const isChanging = oldValue !== dependencyValue;\n // Special case for NaN idempotency (NaN !== NaN is always true)\n const bothAreNaN = Number.isNaN(oldValue) && Number.isNaN(dependencyValue);\n\n if (isChanging && !bothAreNaN) {\n validator?.dependencies.warnOverwrite(dependencyName, \"setDependency\");\n }\n }\n\n (store.dependencies as Record<string, unknown>)[dependencyName] =\n dependencyValue;\n}\n\nfunction setMultipleDependencies(\n store: DependenciesStore,\n deps: Record<string, unknown>,\n validator?: RouterValidator | null,\n): void {\n const overwrittenKeys: string[] = [];\n\n for (const key in deps) {\n if (deps[key] === undefined) {\n continue;\n }\n\n if (Object.hasOwn(store.dependencies, key)) {\n overwrittenKeys.push(key);\n } else {\n validator?.dependencies.validateDependencyCount(store, \"setDependencies\");\n }\n\n (store.dependencies as Record<string, unknown>)[key] = deps[key];\n }\n\n if (overwrittenKeys.length > 0) {\n validator?.dependencies.warnBatchOverwrite(\n overwrittenKeys,\n \"setDependencies\",\n );\n }\n}\n\n// =============================================================================\n// Public API factory\n// =============================================================================\n\nexport function getDependenciesApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): DependenciesApi<Dependencies> {\n const ctx = getInternals(router);\n\n return {\n get: (name) => {\n ctx.validator?.dependencies.validateDependencyName(name, \"getDependency\");\n\n const store = ctx.dependenciesGetStore();\n const value = (store.dependencies as Record<string, unknown>)[\n name as string\n ];\n\n ctx.validator?.dependencies.validateDependencyExists(\n name as string,\n store,\n );\n\n return value as Dependencies[typeof name];\n },\n getAll: () => ({ ...ctx.dependenciesGetStore().dependencies }),\n set: (name, value) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.dependencies.validateSetDependencyArgs(\n name,\n value,\n \"setDependency\",\n );\n\n setDependency(ctx.dependenciesGetStore(), name, value, ctx.validator);\n },\n setAll: (deps) => {\n throwIfDisposed(ctx.isDisposed);\n\n const store = ctx.dependenciesGetStore();\n\n ctx.validator?.dependencies.validateDependenciesObject(\n deps,\n \"setDependencies\",\n );\n\n setMultipleDependencies(\n store,\n deps as Record<string, unknown>,\n ctx.validator,\n );\n },\n remove: (name) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.dependencies.validateDependencyName(\n name,\n \"removeDependency\",\n );\n\n const store = ctx.dependenciesGetStore();\n\n if (!Object.hasOwn(store.dependencies, name)) {\n ctx.validator?.dependencies.warnRemoveNonExistent(name);\n }\n\n delete (store.dependencies as Record<string, unknown>)[name as string];\n },\n reset: () => {\n throwIfDisposed(ctx.isDisposed);\n const store = ctx.dependenciesGetStore();\n\n store.dependencies = Object.create(null) as Partial<Dependencies>;\n },\n has: (name) => {\n ctx.validator?.dependencies.validateDependencyName(name, \"hasDependency\");\n\n return Object.hasOwn(ctx.dependenciesGetStore().dependencies, name);\n },\n };\n}\n"],"mappings":"4LAaA,SAAgB,EACd,EACA,EACA,EACA,EACS,CACT,GAAI,EAAkB,CACpB,IAAM,EAAe,IAAqB,EACpC,EAAoB,EAAiB,WAAW,GAAG,EAAK,EAAE,EAEhE,GAAI,GAAgB,EAAmB,CACrC,IAAM,EAAS,EAAe,GAAK,eAAe,EAAiB,IAOnE,OALA,EAAO,KACL,qBACA,wBAAwB,EAAK,4BAA4B,EAAO,uBAClE,EAEO,EACT,CACF,CASA,OAPI,GACF,EAAO,KACL,qBACA,UAAU,EAAK,+EACjB,EAGK,EACT,CAUA,SAAgB,EACd,EACA,EACS,CAUT,OATI,GACF,EAAO,MACL,qBACA,uFACF,EAEO,IAGF,EACT,CCVA,MAAM,EAAqC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,EAAM,aAAc,CAAI,GACzC,EAAI,WAAW,aAAa,sBAAsB,CAAI,EAGxD,OAAQ,EAAM,aAAyC,EACzD,EACA,UAAa,CACX,EAAA,EAAgB,EAAI,UAAU,EAC9B,IAAM,EAAQ,EAAI,qBAAqB,EAEvC,EAAM,aAAe,OAAO,OAAO,IAAI,CACzC,EACA,IAAM,IACJ,EAAI,WAAW,aAAa,uBAAuB,EAAM,eAAe,EAEjE,OAAO,OAAO,EAAI,qBAAqB,CAAC,CAAC,aAAc,CAAI,EAEtE,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=new WeakMap;function t(t){let n=e.get(t);if(!n)throw TypeError(`[real-router] Invalid router instance — not found in internals registry`);return n}function n(t,n){e.set(t,n)}function r(e,t,n){let r=t;for(let t of e){let e=r;r=(...n)=>t(e,...n)}return r(...n)}function i(e,t,n){return((...i)=>{let a=n.get(e);return!a||a.length===0?t(...i):r(a,t,i)})}function a(e,t,n){return(i,a)=>{let o=n.get(e);return!o||o.length===0?t(i,a):r(o,t,[i,a])}}const o=`[^>]*`;function s(e){let t=!1;for(let n of e)if(n===`<`)t=!0;else if(n===`>`){if(!t)return!1;t=!1}return!t}const c=/[<>]/u,l=e=>e===58||e===42;function u(e){let t=[],n=0,r=!1;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);a===60?r=!0:a===62?r=!1:a===47&&!r&&(t.push(e.slice(n,i)),n=i+1)}return t.push(e.slice(n)),t}function d(e){let t=e.length;if(t===0)return{kind:`static`,text:``};if(!l(e.charCodeAt(0))){for(let n=0;n<t;n+=1){let r=e.charCodeAt(n);if(r===60)return{error:`constraint-in-static`};if(l(r)&&n+1<t&&e.charCodeAt(n+1)!==60)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===63)break;r+=1}let i=e.slice(1,r);if(i.length===0)return{error:`name-less`};if(l(i.charCodeAt(i.length-1)))return{error:`trailing-marker`};let a,o=!1;if(r<t)if(e.charCodeAt(r)===60){let n=e.indexOf(`>`,r+1);if(n===-1)return{error:`unbalanced-constraint`};if(n===r+1)return{error:`empty-constraint`};a=e.slice(r,n+1);let i=n+1;if(i<t)if(e.charCodeAt(i)===63)o=!0;else return{error:`fused-constraint-suffix`}}else o=!0;return n?o?{error:`optional-splat`}:{kind:`splat`,name:i}:a===void 0?{kind:`param`,name:i,optional:o}:{kind:`param`,name:i,constraint:a,optional:o}}function f(e){for(let t of u(e)){let e=d(t);if(`error`in e)return e.error}}function p(e){let t=u(e);for(let e=2;e<t.length;e+=1)if(t[e].startsWith(`*`)&&m(t[e-1])&&m(t[e-2]))return!0;return!1}function m(e){return e.startsWith(`:`)&&e.endsWith(`?`)}function h(e){return`(${e.slice(1,-1)})`}function g(e,t){try{return RegExp(`^${h(e)}$`)}catch{throw Error(`[buildParamMeta] Invalid constraint '${e}' on parameter '${t}': the body between '<' and '>' must be a valid regular expression (e.g. '<[0-9]+>', '<[a-z]+>').`)}}const _=new RegExp(String.raw`([:*]${`[^/?<]+`}(?:<${o}>)?)\?(?=[/?]|$)`,`g`),v=RegExp(`<${o}>`,`g`),y=/\?(.+)$/;function b(e){return e.replaceAll(v,e=>`<${`x`.repeat(e.length-2)}>`).replaceAll(_,`$1\0`)}const x=Object.freeze([]),S=Object.freeze({}),C=new Map,w=Object.freeze({urlParams:x,queryParams:x,spatParams:x,paramTypeMap:S,constraintPatterns:C,pathPattern:``});function T(e,t,n,r,i){for(let a of u(e)){if(a.length===0)continue;let e=d(a);`error`in e||e.kind===`static`||(t.push(e.name),r[e.name]=`url`,e.kind===`splat`?n.push(e.name):e.constraint!==void 0&&i.set(e.name,{pattern:g(e.constraint,e.name),constraint:e.constraint}))}}function E(e){let t=[],n=[],r=[],i={},a=new Map,o=y.exec(b(e));if(o!==null){let t=e.slice(o.index+1).split(`&`);for(let e of t){let t=e.trim();t.length>0&&(n.push(t),i[t]=`query`)}e=e.slice(0,o.index)}return T(e,t,r,i,a),D(t,n,r,i,a,e)}function D(e,t,n,r,i,a){return{urlParams:e.length===0?x:e,queryParams:t.length===0?x:t,spatParams:n.length===0?x:n,paramTypeMap:e.length===0&&t.length===0?S:r,constraintPatterns:i.size===0?C:i,pathPattern:a}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return a}});
|
|
2
|
+
//# sourceMappingURL=buildParamMeta-CkG6cUIl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildParamMeta-CkG6cUIl.js","names":[],"sources":["../../src/internals.ts","../../src/engine/path-matcher/constraint-grammar.ts","../../src/engine/path-matcher/parseSegment.ts","../../src/engine/path-matcher/buildParamMeta.ts"],"sourcesContent":["import type { RouteTree } from \"./engine\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type {\n DefaultDependencies,\n EventName,\n LoggerConfig,\n NavigationOptions,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouterLogger,\n RouteTreeState,\n SimpleState,\n State,\n TreeChangedEvent,\n Unsubscribe,\n EventMethodMap,\n PluginFactory,\n} from \"./types\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\nimport type { SerializedRouterState } from \"./utils\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <P extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: Record<string, Record<string, \"url\" | \"query\">>,\n ) => State<P>;\n\n readonly forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => SimpleState<P>;\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?: Options,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options;\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: (route: string, params?: Params) => string;\n\n readonly emitTransitionError: (error: Error) => void;\n\n /**\n * Emits `TRANSITION_SUCCESS` directly (no FSM transition) — used by\n * `getRoutesApi().replace()` to notify `router.subscribe` listeners when a\n * structural replace revalidates the active state (#950). Mirrors the success\n * emission `completeTransition` / `navigateToNotFound` perform.\n */\n readonly emitTransitionSuccess: (\n toState: State,\n fromState: State | undefined,\n opts?: NavigationOptions,\n ) => 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 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 // `foundation/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;\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 };\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 readonly clearState: () => void;\n readonly setState: (state: State) => void;\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\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 createBinaryInterceptable} instead when the\n * wrapped method takes exactly two args and the caller needs the precise\n * `(a, b) => r` signature preserved (the variadic form widens args to `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 * Two-argument interceptor wrapper — preserves the exact `(a: A, b: B) => R`\n * signature, which the variadic {@link createInterceptable} cannot express\n * (it widens args to `any[]`). Used for the binary interceptable methods\n * `forwardState(routeName, routeParams)` and `buildPath(route, params)`.\n */\nexport function createBinaryInterceptable<A, B, R>(\n name: string,\n original: (a: A, b: B) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B) => R {\n return (arg1: A, arg2: B) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\n","/**\n * Single source of truth for the constraint-delimiter `<...>` grammar (#804).\n *\n * Before this module the `<...>` grammar was re-spelled independently in 6\n * places across `path-matcher` + `route-tree`, with a live `+`/`*` desync\n * between the match side (`<[^>]+>`) and the strip/build side (`<[^>]*>`) — the\n * exact \"two desynced regexes\" class #738 unified for the param-*name* axis.\n * This module is the constraint-axis counterpart of `PARAM_NAME_PATTERN`:\n *\n * - `CONSTRAINT_BODY_PATTERN` — the one atom every constraint-parsing regex\n * (match / strip / build) derives from, so they can never disagree again.\n * - `isConstraintBalanced` — the one balance predicate the route-tree gate and\n * the `registerTree` backstop consume, so no layer re-rolls the scan.\n *\n * @module constraint-grammar\n */\n\n/**\n * Constraint body between `<` and `>`: any run of characters except the\n * closing `>`. Canonical quantifier is `*` (empties allowed at the *grammar*\n * level; the semantically-useless empty `<>` is rejected at the route-tree gate\n * and the `registerTree` backstop, not smuggled through — see #804 §3.3). Every\n * regex that parses `<...>` derives from this constant via interpolation, so the\n * match / strip / build phases share one definition — the same discipline\n * `PARAM_NAME_PATTERN` established for the param-name axis (#738).\n */\nexport const CONSTRAINT_BODY_PATTERN = \"[^>]*\";\n\n/**\n * Reports whether a path's `<...>` constraint delimiters are balanced.\n *\n * Single linear scan: a `<` opens a constraint and the first following `>`\n * closes it; a `<` inside the body is allowed (`<[a<b]>`). A `>` seen outside a\n * constraint, or a `<` left unclosed at the end, is a stray/unbalanced\n * delimiter.\n *\n * Implemented as a scan rather than a `replaceAll(new RegExp(...), \"\")` strip so\n * the intent — delimiter *balance*, not HTML *sanitization* — is unambiguous to\n * both readers and static analysis (the regex strip is the classic\n * incomplete-tag-sanitizer pattern CodeQL flags, which this is not).\n *\n * Authoritative in the producing layer (#804): `route-tree`'s `validateRoutePath`\n * gate and `path-matcher`'s own `registerTree` backstop both consume this — the\n * opt-in/gate validators never reimplement the scan (same axis as #1047).\n */\nexport function isConstraintBalanced(path: string): boolean {\n let insideConstraint = false;\n\n for (const char of path) {\n if (char === \"<\") {\n insideConstraint = true;\n } else if (char === \">\") {\n if (!insideConstraint) {\n return false; // stray `>` with no open `<`\n }\n\n insideConstraint = false;\n }\n }\n\n return !insideConstraint; // a still-open `<` is an unclosed constraint\n}\n\n/**\n * A query-param NAME may not contain `<`/`>` (#1242 §5.1) — such a char is a\n * constraint delimiter leaked into the query, e.g. a reverse-order modifier typo\n * `/a/:b?<\\d+>` parses the `?` as the query start, making `<\\d+>` the query name.\n * Single-sourced so the route-tree gate and the `registerTree` backstop share one\n * definition of \"invalid query-name char\".\n */\nexport const INVALID_QUERY_NAME_RGX = /[<>]/u;\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 (RFC §4):\n * 1. Leading `:`/`*` → param/splat; otherwise `static` (a marker glued *after* a\n * static prefix ⇒ `fused-marker`; a `<...>` in a marker-less segment ⇒\n * `constraint-in-static`; a trailing `?` on a marker-less segment ⇒ `name-less`\n * — the optional 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. constraint = `<...>` after the name; unbalanced/`<>` ⇒ `unbalanced`/`empty`\n * (#804); text after `>` other than a trailing `?` ⇒ `fused-constraint-suffix`\n * (#1150).\n * 5. a trailing `?` ⇒ optional; on a splat ⇒ `optional-splat` (#1149).\n *\n * @module parseSegment\n */\n\n/* eslint-disable unicorn/prefer-code-point, 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 (:550). Markers compared are ASCII (`:` `*` `<` `?`, < 0x80). */\n\n/** A successfully tokenized segment. */\nexport type SegmentTokens =\n | { readonly kind: \"static\"; readonly text: string }\n | {\n readonly kind: \"param\";\n readonly name: string;\n readonly constraint?: string;\n readonly optional: boolean;\n }\n | { readonly kind: \"splat\"; readonly name: string };\n\n/** Grammar-shape rejections, each mirroring an existing 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 | \"fused-constraint-suffix\" // #1150 — static text after a constraint's `>`\n | \"constraint-in-static\" // #1311 — a `<...>` in a marker-less segment\n | \"optional-splat\" // #1149 — `*name?`\n | \"unbalanced-constraint\" // #804 — `<` with no matching `>`\n | \"empty-constraint\"; // #804 — `<>` (compiles to a never-matching `^()$`)\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 — but NOT on a `/` inside a\n * `<...>` constraint, whose body may legally contain `/` (e.g. `:id<a/b>`, which\n * the current whole-path `buildParamMeta` scan tolerates). First-`>` semantics,\n * matching the constraint grammar (`<[^>]*>`). This is the **segmentation** half\n * of the path-grammar unification: `parseSegment` owns the per-segment grammar,\n * `splitPathSegments` owns where a segment begins and ends. Reused by every layer\n * that must go from a path string to per-segment tokens (L1 now; L3 in a later\n * phase), so segmentation itself can never drift.\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 let inConstraint = false;\n\n for (let i = 0; i < path.length; i += 1) {\n const code = path.charCodeAt(i);\n\n if (code === LT) {\n inConstraint = true;\n } else if (code === GT) {\n inConstraint = false;\n } else if (code === SLASH && !inConstraint) {\n segments.push(path.slice(start, i));\n start = i + 1;\n }\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 `<...>` in a marker-less segment reshapes the route (#1311).\n if (code === LT) {\n return { error: \"constraint-in-static\" };\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 // Two placements are NOT fused: a marker ENDING the segment (a static ending in\n // `:`/`*` — `/a:`, `/a*`, F2 — caught by `i + 1 < length` being false), and a\n // marker followed by `<` (the constraint-in-static case `a<b>`, caught by the\n // `<` branch above). Every OTHER following char is fused — including a `?`\n // (`a:?`): that shape never reaches the tokenizer through a real path (a `?`\n // after a bare marker is not a valid `:name?` optional, so the query mask strips\n // it before `/`-segmentation), so a direct call correctly reports fused-marker.\n if (\n isMarker(code) &&\n i + 1 < length &&\n segment.charCodeAt(i + 1) !== LT\n ) {\n return { error: \"fused-marker\" };\n }\n }\n\n // A trailing `?` is the optional modifier; on a marker-less segment (no param\n // name) it is an optional-with-no-name — name-less (#858/#1241, `/faq?`). The\n // backstop rejects it by the SAME rule: its `endsWith(\"?\")` optional fork routes\n // the segment to `extractParamName` → this tokenizer. Owning the `?` modifier\n // here (not just in the marker branches) is what lets the gate and backstop\n // agree on it — 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 `<` or `?` (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 === 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 // ---- constraint + optional --------------------------------------------\n let constraint: string | undefined;\n let optional = false;\n\n if (cursor < length) {\n if (segment.charCodeAt(cursor) === LT) {\n const close = segment.indexOf(\">\", cursor + 1);\n\n if (close === -1) {\n return { error: \"unbalanced-constraint\" }; // #804\n }\n\n if (close === cursor + 1) {\n return { error: \"empty-constraint\" }; // #804 — `<>`\n }\n\n constraint = segment.slice(cursor, close + 1);\n\n const after = close + 1;\n\n if (after < length) {\n // Only a trailing `?` may follow a constraint (matches the current\n // `(\\?)?` capture); any other text is fused (#1150).\n if (segment.charCodeAt(after) === QUESTION) {\n optional = true;\n } else {\n return { error: \"fused-constraint-suffix\" };\n }\n }\n } else {\n // segment.charCodeAt(cursor) === QUESTION\n optional = true;\n }\n }\n\n if (splat) {\n if (optional) {\n return { error: \"optional-splat\" }; // #1149\n }\n\n return { kind: \"splat\", name };\n }\n\n return constraint === undefined\n ? { kind: \"param\", name, optional }\n : { kind: \"param\", name, constraint, optional };\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/**\n * Whether a path places ≥2 optional params DIRECTLY before a splat\n * (`/:a?/:b?/*rest`, `/:a<c>?/:b<c>?/*rest`, #1287). A single trie slot carries\n * only one optional→splat fork, so the outer optional's mark overwrites the\n * inner's — the omit-outer/take-inner form silently reshapes into the splat.\n *\n * A whole-path (cross-segment) property that `parseSegment` cannot decide per\n * segment — so, like `isConstraintBalanced`, it is shared verbatim between the\n * matcher's `registerTree` backstop and `route-tree`'s validation gate, and the\n * two cannot drift. Runs on the RAW path: `splitPathSegments` is constraint-aware,\n * so a `<[^/]+>` body does not break the segment split.\n */\nexport function hasMultipleOptionalsBeforeSplat(path: string): boolean {\n const segments = splitPathSegments(path);\n\n for (let i = 2; i < segments.length; i += 1) {\n if (\n segments[i].startsWith(\"*\") &&\n isOptionalParamSegment(segments[i - 1]) &&\n isOptionalParamSegment(segments[i - 2])\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction isOptionalParamSegment(segment: string): boolean {\n return segment.startsWith(\":\") && segment.endsWith(\"?\");\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 { CONSTRAINT_BODY_PATTERN } from \"./constraint-grammar\";\nimport { parseSegment, splitPathSegments } from \"./parseSegment\";\n\nimport type { ConstraintPattern, ParamMeta } from \"./types\";\n\n/**\n * Extracts the regex pattern from a constraint string.\n *\n * @param constraint - Constraint string (e.g., \"<\\\\d+>\")\n * @returns Regex capture group pattern (e.g., \"(\\\\d+)\")\n */\nfunction extractConstraintPattern(constraint: string): string {\n // Strip the \"<\"/\">\" delimiters. parseSegment guarantees the `<body>` shape\n // (balanced, non-empty body — #804), so a plain slice is exact — and avoids\n // the regex-strip idiom the incomplete-multi-character-sanitization SAST\n // class flags (semgrep/CodeQL).\n return `(${constraint.slice(1, -1)})`;\n}\n\n/**\n * Compiles a `<...>` constraint body to its anchored `^(…)$` matcher, rejecting a\n * body that is not a valid regular expression (`<*x>`, `<(>`, `<[>`) with a clear\n * error. Without this, an invalid body would surface as a raw V8 `SyntaxError`\n * (\"Invalid regular expression … Nothing to repeat\") deep inside tree-building\n * (`computeCaches`) OR the validation gate (both call `buildParamMeta`) — this is\n * the single constraint-compilation site, so one guard covers every consumer.\n */\nfunction compileConstraintPattern(\n constraint: string,\n paramName: string,\n): RegExp {\n try {\n return new RegExp(`^${extractConstraintPattern(constraint)}$`);\n } catch {\n throw new Error(\n `[buildParamMeta] Invalid constraint '${constraint}' on parameter '${paramName}': ` +\n `the body between '<' and '>' must be a valid regular expression (e.g. '<[0-9]+>', '<[a-z]+>').`,\n );\n }\n}\n\n/**\n * Canonical param-name character class: any char except `/`, `?`, `<`.\n *\n * **Single source of truth** for \"what characters a parameter name may contain\"\n * (#738), now consumed by the whole-path query-mask (`OPTIONAL_PARAM_MARKER_RGX`\n * below). The route-tree gate reads the per-segment grammar through `parseSegment`\n * (`findSegmentGrammarError`), not this char class. The\n * per-segment name grammar itself lives in `parseSegment` (the tokenizer this\n * module now consumes for URL-param extraction), so `match()` / `buildPath()`\n * cannot disagree on a name.\n */\nexport const PARAM_NAME_PATTERN = \"[^/?<]+\";\n\n// The optional-param marker `?` ends at a segment boundary (`/`), the start of a\n// query string (`?`, e.g. `/:id??tab`), or end of input. Including `?` in the\n// lookahead is what stops the optional marker being mistaken for the query\n// separator when a query follows an optional param directly.\nconst OPTIONAL_PARAM_MARKER_RGX = new RegExp(\n String.raw`([:*]${PARAM_NAME_PATTERN}(?:<${CONSTRAINT_BODY_PATTERN}>)?)\\?(?=[/?]|$)`,\n \"g\",\n);\n\n// Matches a `<...>` constraint body; used to neutralize `?` inside constraints\n// before query detection. Delimiter grammar derives from the single\n// `CONSTRAINT_BODY_PATTERN` atom (#804) so match/strip/build cannot desync.\n\nconst CONSTRAINT_RGX = new RegExp(`<${CONSTRAINT_BODY_PATTERN}>`, \"g\");\n\n/**\n * Regex for matching query parameters in path patterns.\n *\n * Matches query string portion after \"?\" in path.\n *\n * @example\n * ```\n * \"/search?q&page\" → matches \"q&page\"\n * ```\n */\n// eslint-disable-next-line sonarjs/super-linear-regex -- bounded input from route definitions, not user input\nconst QUERY_PARAM_RGX = /\\?(.+)$/;\n\n/**\n * Length-preserving mask used only to locate the real query separator `?`.\n *\n * Two kinds of `?` must NOT be mistaken for the query separator:\n * - the optional-param marker (`:id?`),\n * - a `?` inside a `<...>` constraint (e.g. the lazy quantifier in `:id<\\d?>`).\n *\n * Both are neutralized in place (same length, so the match index maps back onto\n * the original `path`). Without this, `/a/:id<\\d?>` was split at the constraint's\n * `?`, producing `queryParams:[\">\"]`, a truncated `pathPattern`, and a lost\n * constraint — crashing `start()` with `Missing required param` (#738).\n */\nfunction maskForQueryDetection(path: string): string {\n // Blank constraint interiors: \"<\\d?>\" → \"<xxx>\" (length preserved).\n const constraintsMasked = path.replaceAll(\n CONSTRAINT_RGX,\n (constraint) => `<${\"x\".repeat(constraint.length - 2)}>`,\n );\n\n // Replace the optional-param `?` with NUL (length preserved, never a `?`).\n return constraintsMasked.replaceAll(OPTIONAL_PARAM_MARKER_RGX, \"$1\u0000\");\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 * // → {\n * // urlParams: [\"id\"],\n * // queryParams: [],\n * // spatParams: [],\n * // paramTypeMap: { id: \"url\" }\n * // }\n *\n * buildParamMeta(\"/search?q&page\")\n * // → {\n * // urlParams: [],\n * // queryParams: [\"q\", \"page\"],\n * // spatParams: [],\n * // paramTypeMap: { q: \"query\", page: \"query\" }\n * // }\n *\n * buildParamMeta(\"/files/*path\")\n * // → {\n * // urlParams: [\"path\"],\n * // queryParams: [],\n * // spatParams: [\"path\"],\n * // paramTypeMap: { path: \"url\" }\n * // }\n *\n * buildParamMeta(\"/users/:id/posts/:postId?q&page\")\n * // → {\n * // urlParams: [\"id\", \"postId\"],\n * // queryParams: [\"q\", \"page\"],\n * // spatParams: [],\n * // paramTypeMap: { id: \"url\", postId: \"url\", q: \"query\", page: \"query\" }\n * // }\n * ```\n */\n// Shared frozen sentinels for the common no-params case — avoid a fresh empty\n// array/object/Map 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({});\nconst EMPTY_CONSTRAINTS: ReadonlyMap<string, ConstraintPattern> = new Map();\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 6-field wrapper carries zero per-route information. The\n// RETAINING caller (route-tree's computeCaches) swaps a matching fresh result\n// for this instance — buildParamMeta itself keeps returning fresh objects so\n// the 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 constraintPatterns: EMPTY_CONSTRAINTS,\n pathPattern: \"\",\n});\n\n/**\n * Extracts URL/splat params + constraints from a path's segments into the given\n * accumulators via the canonical `parseSegment` tokenizer (RFC Phase 2). Split\n * out of `buildParamMeta` so the builder stays under the cognitive-complexity\n * budget (like `shareEmptyCollections`). A malformed segment (token errors) or a\n * `static` segment contributes nothing — a malformed route is rejected downstream\n * before it compiles, so its meta is moot (this includes the #1324 trailing-marker\n * family the old whole-path scan swallowed into a param name: the enumerated §8\n * flip, affecting only that dead route's unused meta until the trie migrates).\n */\nfunction collectUrlParams(\n path: string,\n urlParams: string[],\n spatParams: string[],\n paramTypeMap: Record<string, \"url\" | \"query\">,\n constraintPatterns: Map<string, ConstraintPattern>,\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 } else if (token.constraint !== undefined) {\n constraintPatterns.set(token.name, {\n pattern: compileConstraintPattern(token.constraint, token.name),\n constraint: token.constraint,\n });\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: Record<string, \"url\" | \"query\"> = {};\n const constraintPatterns = new Map<string, ConstraintPattern>();\n\n // Locate the real query separator on a length-preserving mask (so the index\n // maps back onto `path`) that hides the optional-param `?` marker and any `?`\n // inside a `<...>` constraint.\n const queryMatch = QUERY_PARAM_RGX.exec(maskForQueryDetection(path));\n\n if (queryMatch !== null) {\n const queryString = path.slice(queryMatch.index + 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, queryMatch.index);\n }\n\n collectUrlParams(\n path,\n urlParams,\n spatParams,\n paramTypeMap,\n constraintPatterns,\n );\n\n return shareEmptyCollections(\n urlParams,\n queryParams,\n spatParams,\n paramTypeMap,\n constraintPatterns,\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 constraintPatterns: Map<string, ConstraintPattern>,\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 constraintPatterns:\n constraintPatterns.size === 0 ? EMPTY_CONSTRAINTS : constraintPatterns,\n pathPattern,\n };\n}\n"],"mappings":"AAqLA,MAAM,EAAY,IAAI,QAEtB,SAAgB,EACd,EACoB,CACpB,IAAM,EAAM,EAAU,IAAI,CAAM,EAEhC,GAAI,CAAC,EACH,MAAU,UACR,yEACF,EAGF,OAAO,CACT,CAEA,SAAgB,EACd,EACA,EACM,CACN,EAAU,IAAI,EAAQ,CAAG,CAC3B,CAGA,SAAS,EACP,EACA,EACA,EACG,CACH,IAAI,EAAQ,EAEZ,IAAK,IAAM,KAAe,EAAc,CACtC,IAAM,EAAO,EAEb,GAAS,GAAG,IAAqB,EAAY,EAAM,GAAG,CAAS,CACjE,CAEA,OAAO,EAAM,GAAG,CAAI,CACtB,CAQA,SAAgB,EACd,EACA,EACA,EAIG,CACH,QAAS,GAAG,IAAgB,CAC1B,IAAM,EAAQ,EAAa,IAAI,CAAI,EAMnC,MAJI,CAAC,GAAS,EAAM,SAAW,EACtB,EAAS,GAAG,CAAI,EAGlB,EAAwB,EAAO,EAAU,CAAI,CACtD,EACF,CAQA,SAAgB,EACd,EACA,EACA,EAImB,CACnB,OAAQ,EAAS,IAAY,CAC3B,IAAM,EAAQ,EAAa,IAAI,CAAI,EAMnC,MAJI,CAAC,GAAS,EAAM,SAAW,EACtB,EAAS,EAAM,CAAI,EAGrB,EAAwB,EAAO,EAAU,CAAC,EAAM,CAAI,CAAC,CAC9D,CACF,CCnPA,MAAa,EAA0B,QAmBvC,SAAgB,EAAqB,EAAuB,CAC1D,IAAI,EAAmB,GAEvB,IAAK,IAA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EAAM,WAAY,EAAM,IAAI,EAC9D,WAAY,EAAM,UACpB,CAAC,EAEL,CACF,CAEA,SAAgB,EAAe,EAAyB,CACtD,IAAM,EAAsB,CAAC,EACvB,EAAwB,CAAC,EACzB,EAAuB,CAAC,EACxB,EAAgD,CAAC,EACjD,EAAqB,IAAI,IAKzB,EAAa,EAAgB,KAAK,EAAsB,CAAI,CAAC,EAEnE,GAAI,IAAe,KAAM,CAEvB,IAAM,EADc,EAAK,MAAM,EAAW,MAAQ,CACzB,CAAC,CAAC,MAAM,GAAG,EAEpC,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAY,EAAM,KAAK,EAEzB,EAAU,OAAS,IACrB,EAAY,KAAK,CAAS,EAC1B,EAAa,GAAa,QAE9B,CAEA,EAAO,EAAK,MAAM,EAAG,EAAW,KAAK,CACvC,CAUA,OARA,EACE,EACA,EACA,EACA,EACA,CACF,EAEO,EACL,EACA,EACA,EACA,EACA,EACA,CACF,CACF,CAMA,SAAS,EACP,EACA,EACA,EACA,EACA,EACA,EACW,CACX,MAAO,CACL,UAAW,EAAU,SAAW,EAAI,EAAoB,EACxD,YAAa,EAAY,SAAW,EAAI,EAAoB,EAC5D,WAAY,EAAW,SAAW,EAAI,EAAoB,EAC1D,aACE,EAAU,SAAW,GAAK,EAAY,SAAW,EAC7C,EACA,EACN,mBACE,EAAmB,OAAS,EAAI,EAAoB,EACtD,aACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./Router-D6NzRxBA.js"),t=require("./buildParamMeta-CkG6cUIl.js");function n(t){if(t())throw new e.n(e.T.ROUTER_DISPOSED)}function r(t){if(t())throw new e.n(e.T.REENTRANT_TREE_MUTATION)}const i=new WeakMap;function a(r){let a=i.get(r);if(a)return a;let o=t.f(r),s={makeState:(e,t,n,r)=>(o.validator?.state.validateMakeStateArgs(e,t,n),o.makeState(e,t,n,r?.params)),buildState:(e,t)=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=o.forwardState(e,t);return o.buildStateResolved(n,r)},forwardState:(e,t)=>(o.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),o.forwardState(e,t)),matchPath:e=>(o.validator?.routes.validateMatchPathArgs(e),o.matchPath(e,o.getOptions())),navigateToState:(e,t)=>(n(o.isDisposed),o.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&o.validator?.navigation.validateNavigationOptions(t,`navigateToState`),o.navigateToState(e,t)),setRootPath:e=>{n(o.isDisposed),o.validator?.routes.validateSetRootPathArgs(e),o.setRootPath(e)},getRootPath:o.getRootPath,addEventListener:(e,t)=>(n(o.isDisposed),o.validator?.eventBus.validateListenerArgs(e,t),o.addEventListener(e,t)),buildNavigationState:(e,t={})=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=o.forwardState(e,t),i=o.buildStateResolved(n,r);if(i)return o.makeState(i.name,i.params,o.buildPath(i.name,i.params),i.meta)},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{n(o.isDisposed),o.validator?.plugins.validateAddInterceptorArgs(e,t);let r=o.interceptors.get(e);r||(r=[],o.interceptors.set(e,r)),r.push(t);let i=!1;return()=>{i||(i=!0,r.splice(r.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:t=>{n(o.isDisposed);let i=Object.keys(t);for(let t of i)if(t in r)throw new e.n(e.T.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${t}" already exists`});for(let e of i)r[e]=t[e];let a={keys:i};o.routerExtensions.push(a);let s=!1;return()=>{if(s)return;s=!0;for(let e of a.keys)delete r[e];let e=o.routerExtensions.indexOf(a);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{n(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:t=>{if(n(o.isDisposed),typeof t!=`string`||t===``)throw TypeError(`[claimContextNamespace] namespace must be a non-empty string, got ${typeof t==`string`?`an empty string`:typeof t}`);if(o.contextClaimRecords.has(t))throw new e.n(e.T.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return o.contextClaimRecords.add(t),{write(e,n){t===`__proto__`?Object.defineProperty(e.context,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e.context[t]=n},release(){o.contextClaimRecords.delete(t)}}}};return i.set(r,s),s}function o(e){let r=t.f(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addActivateGuard`),r.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t)},addDeactivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addDeactivateGuard`),r.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t)},removeActivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}function s(n,r,i){let a=t.f(n);if(a.isDisposed())throw new e.n(e.T.ROUTER_DISPOSED);a.validator?.dependencies.validateCloneArgs(r);let s=a.routeGetStore(),c=e.x(s.tree),l=s.config,u=s.resolvedForwardMap,d=s.routeCustomFields,{options:f,dependencies:p,pluginFactories:m,loggerConfig:h}=a.getCloneState(),{definition:g,external:_}=s.lifecycleNamespace.getFactoriesByOrigin(),v={...p,...r},y=i?.logger?{...h,...i.logger}:h,b=new e.t(c,{...f,logger:y},v),x=t.f(b),S=x.routeGetStore(),C=S.lifecycleNamespace;e._(S.config,l),Object.assign(S.resolvedForwardMap,u),Object.assign(S.routeCustomFields,d),s.rootPath!==``&&x.setRootPath(s.rootPath);let[w,T]=g,[E,D]=_;for(let[e,t]of Object.entries(w))C.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(T))C.addCanActivate(e,t,!0);let O=o(b);for(let[e,t]of Object.entries(E))O.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(D))O.addActivateGuard(e,t);let k=new Set(x.getCloneState().pluginFactories),A=m.filter(e=>!k.has(e));return A.length>0&&b.usePlugin(...A),b}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
|
+
//# sourceMappingURL=cloneRouter-a6LJt-zh.js.map
|