@vielzeug/wayfinder 26.10.15 → 26.10.17
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/LICENSE +21 -0
- package/dist/_dev.cjs.map +1 -1
- package/dist/_dev.js +6 -1
- package/dist/_dev.js.map +1 -1
- package/dist/_navigation.cjs.map +1 -1
- package/dist/_navigation.js +20 -1
- package/dist/_navigation.js.map +1 -1
- package/dist/compile.cjs.map +1 -1
- package/dist/compile.js +46 -1
- package/dist/compile.js.map +1 -1
- package/dist/context.cjs +1 -1
- package/dist/context.cjs.map +1 -1
- package/dist/context.js +54 -1
- package/dist/context.js.map +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.js +17 -1
- package/dist/errors.js.map +1 -1
- package/dist/guards.cjs.map +1 -1
- package/dist/guards.js +9 -1
- package/dist/guards.js.map +1 -1
- package/dist/history.cjs.map +1 -1
- package/dist/history.js +103 -1
- package/dist/history.js.map +1 -1
- package/dist/index.js +7 -1
- package/dist/middleware.cjs.map +1 -1
- package/dist/middleware.js +9 -1
- package/dist/middleware.js.map +1 -1
- package/dist/path.cjs +1 -1
- package/dist/path.cjs.map +1 -1
- package/dist/path.js +124 -1
- package/dist/path.js.map +1 -1
- package/dist/phase-mirror.cjs +1 -1
- package/dist/phase-mirror.cjs.map +1 -1
- package/dist/phase-mirror.js +58 -1
- package/dist/phase-mirror.js.map +1 -1
- package/dist/route-signals.cjs.map +1 -1
- package/dist/route-signals.js +17 -1
- package/dist/route-signals.js.map +1 -1
- package/dist/router.cjs +1 -1
- package/dist/router.cjs.map +1 -1
- package/dist/router.js +477 -1
- package/dist/router.js.map +1 -1
- package/dist/wayfinder.cjs +1 -1
- package/dist/wayfinder.cjs.map +1 -1
- package/dist/wayfinder.iife.js +1 -1
- package/dist/wayfinder.iife.js.map +1 -1
- package/dist/wayfinder.js +898 -1
- package/dist/wayfinder.js.map +1 -1
- package/package.json +6 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Helmuth Saatkamp
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/_dev.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __WAYFINDER_PROD__?: boolean }).__WAYFINDER_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/wayfinder] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/wayfinder] ${msg}`, ...args);\n}\n"],"mappings":"AAGA,SAAgB,KAAK,EAAmB,CAExC,CAGA,SAAgB,MAAM,EAAa,
|
|
1
|
+
{"version":3,"file":"_dev.cjs","names":["args"],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __WAYFINDER_PROD__?: boolean }).__WAYFINDER_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/wayfinder] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/wayfinder] ${msg}`, ...args);\n}\n"],"mappings":"AAGA,SAAgB,KAAK,EAAmB,CAExC,CAGA,SAAgB,MAAM,EAAa,GAAGA,EAAuB,CAE7D,C"}
|
package/dist/_dev.js
CHANGED
package/dist/_dev.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __WAYFINDER_PROD__?: boolean }).__WAYFINDER_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/wayfinder] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/wayfinder] ${msg}`, ...args);\n}\n"],"mappings":"AAGA,SAAgB,KAAK,
|
|
1
|
+
{"version":3,"file":"_dev.js","names":["args"],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __WAYFINDER_PROD__?: boolean }).__WAYFINDER_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/wayfinder] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/wayfinder] ${msg}`, ...args);\n}\n"],"mappings":";AAGA,SAAgB,KAAK,GAAmB,CAExC;AAGA,SAAgB,MAAM,GAAa,GAAGA,GAAuB,CAE7D"}
|
package/dist/_navigation.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_navigation.cjs","names":[],"sources":["../src/_navigation.ts"],"sourcesContent":["export type NavigationAttempt = {\n isCurrent(): boolean;\n readonly signal: AbortSignal;\n};\n\n/** Coordinates navigation ownership so stale work cannot commit router state. */\nexport function createNavigationCoordinator() {\n let active: AbortController | undefined;\n\n return {\n begin(): NavigationAttempt {\n active?.abort();\n\n const controller = new AbortController();\n\n active = controller;\n\n return {\n isCurrent: () => active === controller && !controller.signal.aborted,\n signal: controller.signal,\n };\n },\n\n invalidate(reason?: unknown): void {\n active?.abort(reason);\n active = undefined;\n },\n };\n}\n"],"mappings":"AAMA,SAAgB,6BAA8B,CAC5C,
|
|
1
|
+
{"version":3,"file":"_navigation.cjs","names":["active","controller","reason"],"sources":["../src/_navigation.ts"],"sourcesContent":["export type NavigationAttempt = {\n isCurrent(): boolean;\n readonly signal: AbortSignal;\n};\n\n/** Coordinates navigation ownership so stale work cannot commit router state. */\nexport function createNavigationCoordinator() {\n let active: AbortController | undefined;\n\n return {\n begin(): NavigationAttempt {\n active?.abort();\n\n const controller = new AbortController();\n\n active = controller;\n\n return {\n isCurrent: () => active === controller && !controller.signal.aborted,\n signal: controller.signal,\n };\n },\n\n invalidate(reason?: unknown): void {\n active?.abort(reason);\n active = undefined;\n },\n };\n}\n"],"mappings":"AAMA,SAAgB,6BAA8B,CAC5C,IAAIA,EAEJ,MAAO,CACL,OAA2B,CACzBA,GAAQ,MAAM,EAEd,IAAMC,EAAa,IAAI,gBAIvB,MAFA,GAASA,EAEF,CACL,cAAiBD,IAAWC,GAAc,CAACA,EAAW,OAAO,QAC7D,OAAQA,EAAW,MACrB,CACF,EAEA,WAAW,EAAwB,CACjCD,GAAQ,MAAME,CAAM,EACpB,EAAS,IAAA,EACX,CACF,CACF,C"}
|
package/dist/_navigation.js
CHANGED
|
@@ -1,2 +1,21 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/_navigation.ts
|
|
2
|
+
function createNavigationCoordinator() {
|
|
3
|
+
let e;
|
|
4
|
+
return {
|
|
5
|
+
begin() {
|
|
6
|
+
e?.abort();
|
|
7
|
+
let t = new AbortController();
|
|
8
|
+
return e = t, {
|
|
9
|
+
isCurrent: () => e === t && !t.signal.aborted,
|
|
10
|
+
signal: t.signal
|
|
11
|
+
};
|
|
12
|
+
},
|
|
13
|
+
invalidate(t) {
|
|
14
|
+
e?.abort(t), e = void 0;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { createNavigationCoordinator };
|
|
20
|
+
|
|
2
21
|
//# sourceMappingURL=_navigation.js.map
|
package/dist/_navigation.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_navigation.js","names":[],"sources":["../src/_navigation.ts"],"sourcesContent":["export type NavigationAttempt = {\n isCurrent(): boolean;\n readonly signal: AbortSignal;\n};\n\n/** Coordinates navigation ownership so stale work cannot commit router state. */\nexport function createNavigationCoordinator() {\n let active: AbortController | undefined;\n\n return {\n begin(): NavigationAttempt {\n active?.abort();\n\n const controller = new AbortController();\n\n active = controller;\n\n return {\n isCurrent: () => active === controller && !controller.signal.aborted,\n signal: controller.signal,\n };\n },\n\n invalidate(reason?: unknown): void {\n active?.abort(reason);\n active = undefined;\n },\n };\n}\n"],"mappings":"AAMA,SAAgB,
|
|
1
|
+
{"version":3,"file":"_navigation.js","names":["active","controller","reason"],"sources":["../src/_navigation.ts"],"sourcesContent":["export type NavigationAttempt = {\n isCurrent(): boolean;\n readonly signal: AbortSignal;\n};\n\n/** Coordinates navigation ownership so stale work cannot commit router state. */\nexport function createNavigationCoordinator() {\n let active: AbortController | undefined;\n\n return {\n begin(): NavigationAttempt {\n active?.abort();\n\n const controller = new AbortController();\n\n active = controller;\n\n return {\n isCurrent: () => active === controller && !controller.signal.aborted,\n signal: controller.signal,\n };\n },\n\n invalidate(reason?: unknown): void {\n active?.abort(reason);\n active = undefined;\n },\n };\n}\n"],"mappings":";AAMA,SAAgB,8BAA8B;CAC5C,IAAIA;CAEJ,OAAO;EACL,QAA2B;GACzB,GAAQ,MAAM;GAEd,IAAMC,IAAa,IAAI,gBAAgB;GAIvC,OAFA,IAASA,GAEF;IACL,iBAAiBD,MAAWC,KAAc,CAACA,EAAW,OAAO;IAC7D,QAAQA,EAAW;GACrB;EACF;EAEA,WAAW,GAAwB;GAEjC,AADAD,GAAQ,MAAME,CAAM,GACpB,IAAS,KAAA;EACX;CACF;AACF"}
|
package/dist/compile.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.cjs","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderConfigError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\nimport type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nexport type CompiledRoutes = {\n records: readonly RouteRecord[];\n routesByName: ReadonlyMap<string, RouteRecord>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): CompiledRoutes {\n const records: RouteRecord[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef[],\n ancestorMiddleware: RouteRecord['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" must define path or set index: true`);\n }\n\n const ownPath = route.index\n ? ancestorPath\n : normalizePath(route.path ? joinPaths(ancestorPath, route.path) : ancestorPath);\n\n const branchDefs: RouteBranchDef[] = [\n ...ancestorBranchDefs,\n {\n dataFn: route.data,\n name,\n onError: route.onError as RouteBranchDef['onError'],\n },\n ];\n\n const ownMiddleware: Middleware[] = [\n ...ancestorMiddleware,\n ...((route.middleware ?? []) as unknown as Middleware[]),\n ];\n\n if (route.children) {\n for (const [childName, childRoute] of Object.entries(route.children)) {\n compile(`${name}.${childName}`, childRoute, ownPath, branchDefs, ownMiddleware);\n }\n }\n\n // Emit a record for leaf routes (no children) and routes with data or redirect.\n // A bare parent-only route (children but no data/redirect) is not emitted as a leaf.\n if (route.redirect !== undefined || !route.children || route.data !== undefined) {\n const leaf = branchDefs[branchDefs.length - 1]!;\n\n records.push({\n branchDefs,\n coerceSearch: route.coerceSearch,\n leaf,\n matcher: compilePathMatcher(ownPath),\n ownMiddleware,\n path: ownPath,\n redirect: route.redirect,\n });\n }\n };\n\n for (const [name, route] of Object.entries(options.routes)) {\n compile(name, route, '/', [], []);\n }\n\n // Validate duplicate names.\n const namesSeen = new Set<string>();\n\n for (const record of records) {\n if (namesSeen.has(record.leaf.name)) {\n throw new WayfinderConfigError(\n `Duplicate route name: \"${record.leaf.name}\". A top-level route key must not coincide with a nested route's dot-notation name.`,\n );\n }\n\n namesSeen.add(record.leaf.name);\n }\n\n // Warn when a catch-all or wildcard-param route precedes more specific routes.\n // Routes match in array order (object key order), so a wildcard placed too early silently shadows later routes.\n let wildcardSeen = false;\n\n for (const record of records) {\n const isCatchAll =\n record.path === '/*' || record.path.endsWith('/*') || (record.path.includes(':') && record.path.endsWith('*'));\n\n if (wildcardSeen && !isCatchAll) {\n warn(\n `Route \"${record.leaf.name}\" (${record.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`,\n );\n }\n\n if (isCatchAll) wildcardSeen = true;\n }\n\n return {\n records,\n routesByName: new Map(records.map((r) => [r.leaf.name, r])),\n };\n}\n"],"mappings":"8EAUA,SAAgB,cAA0C,EAAiD,CACzG,
|
|
1
|
+
{"version":3,"file":"compile.cjs","names":["WayfinderConfigError","normalizePath","joinPaths","compilePathMatcher","require_errors","require_path","records","route","name","ownPath","ancestorPath","branchDefs","ancestorBranchDefs","ownMiddleware","ancestorMiddleware","childName","childRoute","leaf","options","namesSeen","record","wildcardSeen","isCatchAll","r"],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderConfigError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\nimport type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nexport type CompiledRoutes = {\n records: readonly RouteRecord[];\n routesByName: ReadonlyMap<string, RouteRecord>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): CompiledRoutes {\n const records: RouteRecord[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef[],\n ancestorMiddleware: RouteRecord['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" must define path or set index: true`);\n }\n\n const ownPath = route.index\n ? ancestorPath\n : normalizePath(route.path ? joinPaths(ancestorPath, route.path) : ancestorPath);\n\n const branchDefs: RouteBranchDef[] = [\n ...ancestorBranchDefs,\n {\n dataFn: route.data,\n name,\n onError: route.onError as RouteBranchDef['onError'],\n },\n ];\n\n const ownMiddleware: Middleware[] = [\n ...ancestorMiddleware,\n ...((route.middleware ?? []) as unknown as Middleware[]),\n ];\n\n if (route.children) {\n for (const [childName, childRoute] of Object.entries(route.children)) {\n compile(`${name}.${childName}`, childRoute, ownPath, branchDefs, ownMiddleware);\n }\n }\n\n // Emit a record for leaf routes (no children) and routes with data or redirect.\n // A bare parent-only route (children but no data/redirect) is not emitted as a leaf.\n if (route.redirect !== undefined || !route.children || route.data !== undefined) {\n const leaf = branchDefs[branchDefs.length - 1]!;\n\n records.push({\n branchDefs,\n coerceSearch: route.coerceSearch,\n leaf,\n matcher: compilePathMatcher(ownPath),\n ownMiddleware,\n path: ownPath,\n redirect: route.redirect,\n });\n }\n };\n\n for (const [name, route] of Object.entries(options.routes)) {\n compile(name, route, '/', [], []);\n }\n\n // Validate duplicate names.\n const namesSeen = new Set<string>();\n\n for (const record of records) {\n if (namesSeen.has(record.leaf.name)) {\n throw new WayfinderConfigError(\n `Duplicate route name: \"${record.leaf.name}\". A top-level route key must not coincide with a nested route's dot-notation name.`,\n );\n }\n\n namesSeen.add(record.leaf.name);\n }\n\n // Warn when a catch-all or wildcard-param route precedes more specific routes.\n // Routes match in array order (object key order), so a wildcard placed too early silently shadows later routes.\n let wildcardSeen = false;\n\n for (const record of records) {\n const isCatchAll =\n record.path === '/*' || record.path.endsWith('/*') || (record.path.includes(':') && record.path.endsWith('*'));\n\n if (wildcardSeen && !isCatchAll) {\n warn(\n `Route \"${record.leaf.name}\" (${record.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`,\n );\n }\n\n if (isCatchAll) wildcardSeen = true;\n }\n\n return {\n records,\n routesByName: new Map(records.map((r) => [r.leaf.name, r])),\n };\n}\n"],"mappings":"A,8EAUA,SAAgB,cAA0C,EAAiD,CACzG,IAAMM,EAAyB,CAAC,EAE1B,SACJ,EACA,EACA,EACA,EACA,IACS,CACT,GAAIC,EAAM,OAASA,EAAM,OAAS,IAAA,GAChC,MAAM,IAAIP,EAAAA,qBAAqB,UAAUQ,EAAK,oCAAoC,EAGpF,GAAI,CAACD,EAAM,OAASA,EAAM,OAAS,IAAA,GACjC,MAAM,IAAIP,EAAAA,qBAAqB,UAAUQ,EAAK,sCAAsC,EAGtF,IAAMC,EAAUF,EAAM,MAClBG,EACAT,EAAAA,cAAcM,EAAM,KAAOL,EAAAA,UAAUQ,EAAcH,EAAM,IAAI,EAAIG,CAAY,EAE3EC,EAA+B,CACnC,GAAGC,EACH,CACE,OAAQL,EAAM,KACd,OACA,QAASA,EAAM,OACjB,CACF,EAEMM,EAA8B,CAClC,GAAGC,EACH,GAAKP,EAAM,YAAc,CAAC,CAC5B,EAEA,GAAIA,EAAM,SACR,IAAK,GAAM,CAACQ,EAAWC,KAAe,OAAO,QAAQT,EAAM,QAAQ,EACjE,QAAQ,GAAGC,EAAK,GAAGO,IAAaC,EAAYP,EAASE,EAAYE,CAAa,EAMlF,GAAIN,EAAM,WAAa,IAAA,IAAa,CAACA,EAAM,UAAYA,EAAM,OAAS,IAAA,GAAW,CAC/E,IAAMU,EAAON,EAAWA,EAAW,OAAS,GAE5CL,EAAQ,KAAK,CACX,aACA,aAAcC,EAAM,aACpB,OACA,QAASJ,EAAAA,mBAAmBM,CAAO,EACnC,gBACA,KAAMA,EACN,SAAUF,EAAM,QAClB,CAAC,CACH,CACF,EAEA,IAAK,GAAM,CAACC,EAAMD,KAAU,OAAO,QAAQW,EAAQ,MAAM,EACvD,QAAQV,EAAMD,EAAO,IAAK,CAAC,EAAG,CAAC,CAAC,EAIlC,IAAMY,EAAY,IAAI,IAEtB,IAAK,IAAMC,KAAUd,EAAS,CAC5B,GAAIa,EAAU,IAAIC,EAAO,KAAK,IAAI,EAChC,MAAM,IAAIpB,EAAAA,qBACR,0BAA0BoB,EAAO,KAAK,KAAK,oFAC7C,EAGFD,EAAU,IAAIC,EAAO,KAAK,IAAI,CAChC,CAIA,IAAIC,EAAe,GAEnB,IAAK,IAAMD,KAAUd,EAAS,CAC5B,IAAMgB,EACJF,EAAO,OAAS,MAAQA,EAAO,KAAK,SAAS,IAAI,GAAMA,EAAO,KAAK,SAAS,GAAG,GAAKA,EAAO,KAAK,SAAS,GAAG,EAE1GC,GAAgB,CAACC,GAEjB,GAAUF,EAAO,KAAK,KAAtB,EAAgCA,EAAO,KAAvC,EAIAE,IAAY,EAAe,GACjC,CAEA,MAAO,CACL,UACA,aAAc,IAAI,IAAIhB,EAAQ,IAAK,GAAM,CAACiB,EAAE,KAAK,KAAMA,CAAC,CAAC,CAAC,CAC5D,CACF,C"}
|
package/dist/compile.js
CHANGED
|
@@ -1,2 +1,47 @@
|
|
|
1
|
-
import{WayfinderConfigError as e}from"./errors.js";
|
|
1
|
+
import { WayfinderConfigError as e } from "./errors.js";
|
|
2
|
+
import { compilePathMatcher as t, joinPaths as n, normalizePath as r } from "./path.js";
|
|
3
|
+
import "./_dev.js";
|
|
4
|
+
//#region src/compile.ts
|
|
5
|
+
function compileRoutes(i) {
|
|
6
|
+
let a = [], compile = (i, o, s, c, l) => {
|
|
7
|
+
if (o.index && o.path !== void 0) throw new e(`Route "${i}" cannot define both index and path`);
|
|
8
|
+
if (!o.index && o.path === void 0) throw new e(`Route "${i}" must define path or set index: true`);
|
|
9
|
+
let u = o.index ? s : r(o.path ? n(s, o.path) : s), d = [...c, {
|
|
10
|
+
dataFn: o.data,
|
|
11
|
+
name: i,
|
|
12
|
+
onError: o.onError
|
|
13
|
+
}], f = [...l, ...o.middleware ?? []];
|
|
14
|
+
if (o.children) for (let [e, t] of Object.entries(o.children)) compile(`${i}.${e}`, t, u, d, f);
|
|
15
|
+
if (o.redirect !== void 0 || !o.children || o.data !== void 0) {
|
|
16
|
+
let e = d[d.length - 1];
|
|
17
|
+
a.push({
|
|
18
|
+
branchDefs: d,
|
|
19
|
+
coerceSearch: o.coerceSearch,
|
|
20
|
+
leaf: e,
|
|
21
|
+
matcher: t(u),
|
|
22
|
+
ownMiddleware: f,
|
|
23
|
+
path: u,
|
|
24
|
+
redirect: o.redirect
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
for (let [e, t] of Object.entries(i.routes)) compile(e, t, "/", [], []);
|
|
29
|
+
let o = /* @__PURE__ */ new Set();
|
|
30
|
+
for (let t of a) {
|
|
31
|
+
if (o.has(t.leaf.name)) throw new e(`Duplicate route name: "${t.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);
|
|
32
|
+
o.add(t.leaf.name);
|
|
33
|
+
}
|
|
34
|
+
let s = !1;
|
|
35
|
+
for (let e of a) {
|
|
36
|
+
let t = e.path === "/*" || e.path.endsWith("/*") || e.path.includes(":") && e.path.endsWith("*");
|
|
37
|
+
s && !t && `${e.leaf.name}${e.path}`, t && (s = !0);
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
records: a,
|
|
41
|
+
routesByName: new Map(a.map((e) => [e.leaf.name, e]))
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
export { compileRoutes };
|
|
46
|
+
|
|
2
47
|
//# sourceMappingURL=compile.js.map
|
package/dist/compile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderConfigError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\nimport type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nexport type CompiledRoutes = {\n records: readonly RouteRecord[];\n routesByName: ReadonlyMap<string, RouteRecord>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): CompiledRoutes {\n const records: RouteRecord[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef[],\n ancestorMiddleware: RouteRecord['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" must define path or set index: true`);\n }\n\n const ownPath = route.index\n ? ancestorPath\n : normalizePath(route.path ? joinPaths(ancestorPath, route.path) : ancestorPath);\n\n const branchDefs: RouteBranchDef[] = [\n ...ancestorBranchDefs,\n {\n dataFn: route.data,\n name,\n onError: route.onError as RouteBranchDef['onError'],\n },\n ];\n\n const ownMiddleware: Middleware[] = [\n ...ancestorMiddleware,\n ...((route.middleware ?? []) as unknown as Middleware[]),\n ];\n\n if (route.children) {\n for (const [childName, childRoute] of Object.entries(route.children)) {\n compile(`${name}.${childName}`, childRoute, ownPath, branchDefs, ownMiddleware);\n }\n }\n\n // Emit a record for leaf routes (no children) and routes with data or redirect.\n // A bare parent-only route (children but no data/redirect) is not emitted as a leaf.\n if (route.redirect !== undefined || !route.children || route.data !== undefined) {\n const leaf = branchDefs[branchDefs.length - 1]!;\n\n records.push({\n branchDefs,\n coerceSearch: route.coerceSearch,\n leaf,\n matcher: compilePathMatcher(ownPath),\n ownMiddleware,\n path: ownPath,\n redirect: route.redirect,\n });\n }\n };\n\n for (const [name, route] of Object.entries(options.routes)) {\n compile(name, route, '/', [], []);\n }\n\n // Validate duplicate names.\n const namesSeen = new Set<string>();\n\n for (const record of records) {\n if (namesSeen.has(record.leaf.name)) {\n throw new WayfinderConfigError(\n `Duplicate route name: \"${record.leaf.name}\". A top-level route key must not coincide with a nested route's dot-notation name.`,\n );\n }\n\n namesSeen.add(record.leaf.name);\n }\n\n // Warn when a catch-all or wildcard-param route precedes more specific routes.\n // Routes match in array order (object key order), so a wildcard placed too early silently shadows later routes.\n let wildcardSeen = false;\n\n for (const record of records) {\n const isCatchAll =\n record.path === '/*' || record.path.endsWith('/*') || (record.path.includes(':') && record.path.endsWith('*'));\n\n if (wildcardSeen && !isCatchAll) {\n warn(\n `Route \"${record.leaf.name}\" (${record.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`,\n );\n }\n\n if (isCatchAll) wildcardSeen = true;\n }\n\n return {\n records,\n routesByName: new Map(records.map((r) => [r.leaf.name, r])),\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"compile.js","names":["records","route","WayfinderConfigError","name","ownPath","ancestorPath","normalizePath","joinPaths","branchDefs","ancestorBranchDefs","ownMiddleware","ancestorMiddleware","childName","childRoute","leaf","compilePathMatcher","options","namesSeen","record","wildcardSeen","isCatchAll","r"],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderConfigError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\nimport type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nexport type CompiledRoutes = {\n records: readonly RouteRecord[];\n routesByName: ReadonlyMap<string, RouteRecord>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): CompiledRoutes {\n const records: RouteRecord[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef[],\n ancestorMiddleware: RouteRecord['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderConfigError(`Route \"${name}\" must define path or set index: true`);\n }\n\n const ownPath = route.index\n ? ancestorPath\n : normalizePath(route.path ? joinPaths(ancestorPath, route.path) : ancestorPath);\n\n const branchDefs: RouteBranchDef[] = [\n ...ancestorBranchDefs,\n {\n dataFn: route.data,\n name,\n onError: route.onError as RouteBranchDef['onError'],\n },\n ];\n\n const ownMiddleware: Middleware[] = [\n ...ancestorMiddleware,\n ...((route.middleware ?? []) as unknown as Middleware[]),\n ];\n\n if (route.children) {\n for (const [childName, childRoute] of Object.entries(route.children)) {\n compile(`${name}.${childName}`, childRoute, ownPath, branchDefs, ownMiddleware);\n }\n }\n\n // Emit a record for leaf routes (no children) and routes with data or redirect.\n // A bare parent-only route (children but no data/redirect) is not emitted as a leaf.\n if (route.redirect !== undefined || !route.children || route.data !== undefined) {\n const leaf = branchDefs[branchDefs.length - 1]!;\n\n records.push({\n branchDefs,\n coerceSearch: route.coerceSearch,\n leaf,\n matcher: compilePathMatcher(ownPath),\n ownMiddleware,\n path: ownPath,\n redirect: route.redirect,\n });\n }\n };\n\n for (const [name, route] of Object.entries(options.routes)) {\n compile(name, route, '/', [], []);\n }\n\n // Validate duplicate names.\n const namesSeen = new Set<string>();\n\n for (const record of records) {\n if (namesSeen.has(record.leaf.name)) {\n throw new WayfinderConfigError(\n `Duplicate route name: \"${record.leaf.name}\". A top-level route key must not coincide with a nested route's dot-notation name.`,\n );\n }\n\n namesSeen.add(record.leaf.name);\n }\n\n // Warn when a catch-all or wildcard-param route precedes more specific routes.\n // Routes match in array order (object key order), so a wildcard placed too early silently shadows later routes.\n let wildcardSeen = false;\n\n for (const record of records) {\n const isCatchAll =\n record.path === '/*' || record.path.endsWith('/*') || (record.path.includes(':') && record.path.endsWith('*'));\n\n if (wildcardSeen && !isCatchAll) {\n warn(\n `Route \"${record.leaf.name}\" (${record.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`,\n );\n }\n\n if (isCatchAll) wildcardSeen = true;\n }\n\n return {\n records,\n routesByName: new Map(records.map((r) => [r.leaf.name, r])),\n };\n}\n"],"mappings":";;;;AAUA,SAAgB,cAA0C,GAAiD;CACzG,IAAMA,IAAyB,CAAC,GAE1B,WACJ,GACA,GACA,GACA,GACA,MACS;EACT,IAAIC,EAAM,SAASA,EAAM,SAAS,KAAA,GAChC,MAAM,IAAIC,EAAqB,UAAUC,EAAK,oCAAoC;EAGpF,IAAI,CAACF,EAAM,SAASA,EAAM,SAAS,KAAA,GACjC,MAAM,IAAIC,EAAqB,UAAUC,EAAK,sCAAsC;EAGtF,IAAMC,IAAUH,EAAM,QAClBI,IACAC,EAAcL,EAAM,OAAOM,EAAUF,GAAcJ,EAAM,IAAI,IAAII,CAAY,GAE3EG,IAA+B,CACnC,GAAGC,GACH;GACE,QAAQR,EAAM;GACd;GACA,SAASA,EAAM;EACjB,CACF,GAEMS,IAA8B,CAClC,GAAGC,GACH,GAAKV,EAAM,cAAc,CAAC,CAC5B;EAEA,IAAIA,EAAM,UACR,KAAK,IAAM,CAACW,GAAWC,MAAe,OAAO,QAAQZ,EAAM,QAAQ,GACjE,QAAQ,GAAGE,EAAK,GAAGS,KAAaC,GAAYT,GAASI,GAAYE,CAAa;EAMlF,IAAIT,EAAM,aAAa,KAAA,KAAa,CAACA,EAAM,YAAYA,EAAM,SAAS,KAAA,GAAW;GAC/E,IAAMa,IAAON,EAAWA,EAAW,SAAS;GAE5C,EAAQ,KAAK;IACX;IACA,cAAcP,EAAM;IACpB;IACA,SAASc,EAAmBX,CAAO;IACnC;IACA,MAAMA;IACN,UAAUH,EAAM;GAClB,CAAC;EACH;CACF;CAEA,KAAK,IAAM,CAACE,GAAMF,MAAU,OAAO,QAAQe,EAAQ,MAAM,GACvD,QAAQb,GAAMF,GAAO,KAAK,CAAC,GAAG,CAAC,CAAC;CAIlC,IAAMgB,oBAAY,IAAI,IAAY;CAElC,KAAK,IAAMC,KAAUlB,GAAS;EAC5B,IAAIiB,EAAU,IAAIC,EAAO,KAAK,IAAI,GAChC,MAAM,IAAIhB,EACR,0BAA0BgB,EAAO,KAAK,KAAK,oFAC7C;EAGF,EAAU,IAAIA,EAAO,KAAK,IAAI;CAChC;CAIA,IAAIC,IAAe;CAEnB,KAAK,IAAMD,KAAUlB,GAAS;EAC5B,IAAMoB,IACJF,EAAO,SAAS,QAAQA,EAAO,KAAK,SAAS,IAAI,KAAMA,EAAO,KAAK,SAAS,GAAG,KAAKA,EAAO,KAAK,SAAS,GAAG;EAQ9G,AANIC,KAAgB,CAACC,KAEjB,GAAUF,EAAO,KAAK,KAAtB,EAAgCA,EAAO,KAAvC,GAIAE,MAAY,IAAe;CACjC;CAEA,OAAO;EACL;EACA,cAAc,IAAI,IAAIpB,EAAQ,KAAK,MAAM,CAACqB,EAAE,KAAK,MAAMA,CAAC,CAAC,CAAC;CAC5D;AACF"}
|
package/dist/context.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");require("./_dev.cjs");function createRouteState(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function buildMatchBranch(e,t,n,r){return e.map((e,i)=>({data:r[i],name:e.name,params:{...t},pathname:n}))}function createRouteContext(e,t,n,r,i){return{hash:e.hash,historyState:e.historyState,locals:{},matches:r,navigate:i,params:n,pathname:e.pathname,query:t}}async function executeMiddlewarePipeline(t,n,r,i){let a=!1;async function dispatch(o){if(o<n.length){let r=!1;try{await n[o]?.(t,async()=>{if(r)throw new e.WayfinderApiError(`next() called multiple times`);r=!0,await dispatch(o+1)})}catch(e){throw i?.(e)??e}
|
|
1
|
+
const e=require("./errors.cjs");require("./_dev.cjs");function createRouteState(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function buildMatchBranch(e,t,n,r){return e.map((e,i)=>({data:r[i],name:e.name,params:{...t},pathname:n}))}function createRouteContext(e,t,n,r,i){return{hash:e.hash,historyState:e.historyState,locals:{},matches:r,navigate:i,params:n,pathname:e.pathname,query:t}}async function executeMiddlewarePipeline(t,n,r,i){let a=!1;async function dispatch(o){if(o<n.length){let r=!1;try{await n[o]?.(t,async()=>{if(r)throw new e.WayfinderApiError(`next() called multiple times`);r=!0,await dispatch(o+1)})}catch(e){throw i?.(e)??e}}else a=!0,await r()}return await dispatch(0),a}function reportError(e,t,n){n&&n(e,t)}exports.buildMatchBranch=buildMatchBranch,exports.createRouteContext=createRouteContext,exports.createRouteState=createRouteState,exports.executeMiddlewarePipeline=executeMiddlewarePipeline,exports.reportError=reportError;
|
|
2
2
|
//# sourceMappingURL=context.cjs.map
|
package/dist/context.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.cjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["import { error as logError } from './_dev';\nimport { WayfinderApiError } from './errors';\nimport type {\n Middleware,\n NavigationStatus,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatch,\n RouteMatchBranch,\n RouteParams,\n RouterErrorContext,\n RouteState,\n RouteTable,\n} from './types';\n\n// ─── Route state ──────────────────────────────────────────────────────────────\n\n/** No defensive deep-copy: RouteState is typed readonly; callers always pass fresh objects. */\nexport function createRouteState(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch;\n status: NavigationStatus;\n}): RouteState {\n return {\n error: input.error,\n location: input.location,\n matches: input.matches,\n status: input.status,\n };\n}\n\n/**\n * Build a RouteMatchBranch from compiled defs and data results.\n */\nexport function buildMatchBranch(\n branchDefs: readonly RouteBranchDef[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n): RouteMatchBranch {\n return branchDefs.map(\n (def, i): RouteMatch => ({\n data: dataResults[i],\n name: def.name,\n params: { ...params },\n pathname,\n }),\n );\n}\n\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function createRouteContext<TRoutes extends RouteTable>(\n location: RouteLocation,\n resolvedQuery: ResolvedQueryParams,\n params: RouteParams,\n matches: RouteMatchBranch,\n navigate: RouteContext<RouteParams, TRoutes>['navigate'],\n): RouteContext<RouteParams, TRoutes> {\n return {\n hash: location.hash,\n historyState: location.historyState,\n locals: {},\n matches,\n navigate,\n params,\n pathname: location.pathname,\n query: resolvedQuery,\n };\n}\n\n// ─── Middleware pipeline ──────────────────────────────────────────────────────\n\nexport async function executeMiddlewarePipeline<TRoutes extends RouteTable>(\n context: RouteContext<RouteParams, TRoutes>,\n middleware: readonly Middleware<TRoutes>[],\n terminal: () => Promise<void>,\n wrapMiddlewareError?: (error: unknown) => unknown,\n): Promise<boolean> {\n let terminalRan = false;\n\n async function dispatch(index: number): Promise<void> {\n if (index < middleware.length) {\n let called = false;\n\n try {\n await middleware[index]?.(context, async () => {\n if (called) throw new WayfinderApiError('next() called multiple times');\n\n called = true;\n await dispatch(index + 1);\n });\n } catch (error) {\n throw wrapMiddlewareError?.(error) ?? error;\n }\n\n return;\n }\n\n terminalRan = true;\n await terminal();\n }\n\n await dispatch(0);\n\n return terminalRan;\n}\n\n// ─── Error reporting ──────────────────────────────────────────────────────────\n\nexport function reportError(\n error: unknown,\n context: RouterErrorContext,\n onError?: (e: unknown, ctx: RouterErrorContext) => void,\n): void {\n if (onError) {\n onError(error, context);\n\n return;\n }\n\n logError('Unhandled router error. Provide an onError callback to handle errors explicitly:', error);\n}\n"],"mappings":"sDAoBA,SAAgB,iBAAiB,EAKlB,CACb,MAAO,CACL,
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["WayfinderApiError","error","require_errors","input","branchDefs","dataResults","def","params","location","resolvedQuery","terminalRan","index","middleware","called","context","error","wrapMiddlewareError","terminal","onError","error$1"],"sources":["../src/context.ts"],"sourcesContent":["import { error as logError } from './_dev';\nimport { WayfinderApiError } from './errors';\nimport type {\n Middleware,\n NavigationStatus,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatch,\n RouteMatchBranch,\n RouteParams,\n RouterErrorContext,\n RouteState,\n RouteTable,\n} from './types';\n\n// ─── Route state ──────────────────────────────────────────────────────────────\n\n/** No defensive deep-copy: RouteState is typed readonly; callers always pass fresh objects. */\nexport function createRouteState(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch;\n status: NavigationStatus;\n}): RouteState {\n return {\n error: input.error,\n location: input.location,\n matches: input.matches,\n status: input.status,\n };\n}\n\n/**\n * Build a RouteMatchBranch from compiled defs and data results.\n */\nexport function buildMatchBranch(\n branchDefs: readonly RouteBranchDef[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n): RouteMatchBranch {\n return branchDefs.map(\n (def, i): RouteMatch => ({\n data: dataResults[i],\n name: def.name,\n params: { ...params },\n pathname,\n }),\n );\n}\n\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function createRouteContext<TRoutes extends RouteTable>(\n location: RouteLocation,\n resolvedQuery: ResolvedQueryParams,\n params: RouteParams,\n matches: RouteMatchBranch,\n navigate: RouteContext<RouteParams, TRoutes>['navigate'],\n): RouteContext<RouteParams, TRoutes> {\n return {\n hash: location.hash,\n historyState: location.historyState,\n locals: {},\n matches,\n navigate,\n params,\n pathname: location.pathname,\n query: resolvedQuery,\n };\n}\n\n// ─── Middleware pipeline ──────────────────────────────────────────────────────\n\nexport async function executeMiddlewarePipeline<TRoutes extends RouteTable>(\n context: RouteContext<RouteParams, TRoutes>,\n middleware: readonly Middleware<TRoutes>[],\n terminal: () => Promise<void>,\n wrapMiddlewareError?: (error: unknown) => unknown,\n): Promise<boolean> {\n let terminalRan = false;\n\n async function dispatch(index: number): Promise<void> {\n if (index < middleware.length) {\n let called = false;\n\n try {\n await middleware[index]?.(context, async () => {\n if (called) throw new WayfinderApiError('next() called multiple times');\n\n called = true;\n await dispatch(index + 1);\n });\n } catch (error) {\n throw wrapMiddlewareError?.(error) ?? error;\n }\n\n return;\n }\n\n terminalRan = true;\n await terminal();\n }\n\n await dispatch(0);\n\n return terminalRan;\n}\n\n// ─── Error reporting ──────────────────────────────────────────────────────────\n\nexport function reportError(\n error: unknown,\n context: RouterErrorContext,\n onError?: (e: unknown, ctx: RouterErrorContext) => void,\n): void {\n if (onError) {\n onError(error, context);\n\n return;\n }\n\n logError('Unhandled router error. Provide an onError callback to handle errors explicitly:', error);\n}\n"],"mappings":"A,sDAoBA,SAAgB,iBAAiB,EAKlB,CACb,MAAO,CACL,MAAOG,EAAM,MACb,SAAUA,EAAM,SAChB,QAASA,EAAM,QACf,OAAQA,EAAM,MAChB,CACF,CAKA,SAAgB,iBACd,EACA,EACA,EACA,EACkB,CAClB,OAAOC,EAAW,KACf,EAAK,KAAmB,CACvB,KAAMC,EAAY,GAClB,KAAMC,EAAI,KACV,OAAQ,CAAE,GAAGC,CAAO,EACpB,UACF,EACF,CACF,CAIA,SAAgB,mBACd,EACA,EACA,EACA,EACA,EACoC,CACpC,MAAO,CACL,KAAMC,EAAS,KACf,aAAcA,EAAS,aACvB,OAAQ,CAAC,EACT,UACA,WACA,SACA,SAAUA,EAAS,SACnB,MAAOC,CACT,CACF,CAIA,eAAsB,0BACpB,EACA,EACA,EACA,EACkB,CAClB,IAAIC,EAAc,GAElB,eAAe,SAAS,EAA8B,CACpD,GAAIC,EAAQC,EAAW,OAAQ,CAC7B,IAAIC,EAAS,GAEb,GAAI,CACF,MAAMD,EAAWD,EAAM,GAAGG,EAAS,SAAY,CAC7C,GAAID,EAAQ,MAAM,IAAIb,EAAAA,kBAAkB,8BAA8B,EAEtE,EAAS,GACT,MAAM,SAASW,EAAQ,CAAC,CAC1B,CAAC,CACH,OAASI,EAAO,CACd,MAAMC,IAAsBD,CAAK,GAAKA,CACxC,CAGF,KAEA,GAAc,GACd,MAAME,EAAS,CACjB,CAIA,OAFA,MAAM,SAAS,CAAC,EAETP,CACT,CAIA,SAAgB,YACd,EACA,EACA,EACM,CACFQ,GACFA,EAAQjB,EAAOa,CAAO,CAM1B,C"}
|
package/dist/context.js
CHANGED
|
@@ -1,2 +1,55 @@
|
|
|
1
|
-
import{WayfinderApiError as e}from"./errors.js";
|
|
1
|
+
import { WayfinderApiError as e } from "./errors.js";
|
|
2
|
+
import "./_dev.js";
|
|
3
|
+
//#region src/context.ts
|
|
4
|
+
function createRouteState(e) {
|
|
5
|
+
return {
|
|
6
|
+
error: e.error,
|
|
7
|
+
location: e.location,
|
|
8
|
+
matches: e.matches,
|
|
9
|
+
status: e.status
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function buildMatchBranch(e, t, n, r) {
|
|
13
|
+
return e.map((e, i) => ({
|
|
14
|
+
data: r[i],
|
|
15
|
+
name: e.name,
|
|
16
|
+
params: { ...t },
|
|
17
|
+
pathname: n
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
function createRouteContext(e, t, n, r, i) {
|
|
21
|
+
return {
|
|
22
|
+
hash: e.hash,
|
|
23
|
+
historyState: e.historyState,
|
|
24
|
+
locals: {},
|
|
25
|
+
matches: r,
|
|
26
|
+
navigate: i,
|
|
27
|
+
params: n,
|
|
28
|
+
pathname: e.pathname,
|
|
29
|
+
query: t
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
async function executeMiddlewarePipeline(t, n, r, i) {
|
|
33
|
+
let a = !1;
|
|
34
|
+
async function dispatch(o) {
|
|
35
|
+
if (o < n.length) {
|
|
36
|
+
let r = !1;
|
|
37
|
+
try {
|
|
38
|
+
await n[o]?.(t, async () => {
|
|
39
|
+
if (r) throw new e("next() called multiple times");
|
|
40
|
+
r = !0, await dispatch(o + 1);
|
|
41
|
+
});
|
|
42
|
+
} catch (e) {
|
|
43
|
+
throw i?.(e) ?? e;
|
|
44
|
+
}
|
|
45
|
+
} else a = !0, await r();
|
|
46
|
+
}
|
|
47
|
+
return await dispatch(0), a;
|
|
48
|
+
}
|
|
49
|
+
function reportError(e, t, n) {
|
|
50
|
+
n && n(e, t);
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { buildMatchBranch, createRouteContext, createRouteState, executeMiddlewarePipeline, reportError };
|
|
54
|
+
|
|
2
55
|
//# sourceMappingURL=context.js.map
|
package/dist/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["import { error as logError } from './_dev';\nimport { WayfinderApiError } from './errors';\nimport type {\n Middleware,\n NavigationStatus,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatch,\n RouteMatchBranch,\n RouteParams,\n RouterErrorContext,\n RouteState,\n RouteTable,\n} from './types';\n\n// ─── Route state ──────────────────────────────────────────────────────────────\n\n/** No defensive deep-copy: RouteState is typed readonly; callers always pass fresh objects. */\nexport function createRouteState(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch;\n status: NavigationStatus;\n}): RouteState {\n return {\n error: input.error,\n location: input.location,\n matches: input.matches,\n status: input.status,\n };\n}\n\n/**\n * Build a RouteMatchBranch from compiled defs and data results.\n */\nexport function buildMatchBranch(\n branchDefs: readonly RouteBranchDef[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n): RouteMatchBranch {\n return branchDefs.map(\n (def, i): RouteMatch => ({\n data: dataResults[i],\n name: def.name,\n params: { ...params },\n pathname,\n }),\n );\n}\n\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function createRouteContext<TRoutes extends RouteTable>(\n location: RouteLocation,\n resolvedQuery: ResolvedQueryParams,\n params: RouteParams,\n matches: RouteMatchBranch,\n navigate: RouteContext<RouteParams, TRoutes>['navigate'],\n): RouteContext<RouteParams, TRoutes> {\n return {\n hash: location.hash,\n historyState: location.historyState,\n locals: {},\n matches,\n navigate,\n params,\n pathname: location.pathname,\n query: resolvedQuery,\n };\n}\n\n// ─── Middleware pipeline ──────────────────────────────────────────────────────\n\nexport async function executeMiddlewarePipeline<TRoutes extends RouteTable>(\n context: RouteContext<RouteParams, TRoutes>,\n middleware: readonly Middleware<TRoutes>[],\n terminal: () => Promise<void>,\n wrapMiddlewareError?: (error: unknown) => unknown,\n): Promise<boolean> {\n let terminalRan = false;\n\n async function dispatch(index: number): Promise<void> {\n if (index < middleware.length) {\n let called = false;\n\n try {\n await middleware[index]?.(context, async () => {\n if (called) throw new WayfinderApiError('next() called multiple times');\n\n called = true;\n await dispatch(index + 1);\n });\n } catch (error) {\n throw wrapMiddlewareError?.(error) ?? error;\n }\n\n return;\n }\n\n terminalRan = true;\n await terminal();\n }\n\n await dispatch(0);\n\n return terminalRan;\n}\n\n// ─── Error reporting ──────────────────────────────────────────────────────────\n\nexport function reportError(\n error: unknown,\n context: RouterErrorContext,\n onError?: (e: unknown, ctx: RouterErrorContext) => void,\n): void {\n if (onError) {\n onError(error, context);\n\n return;\n }\n\n logError('Unhandled router error. Provide an onError callback to handle errors explicitly:', error);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"context.js","names":["error","input","branchDefs","dataResults","def","params","location","resolvedQuery","terminalRan","index","middleware","called","context","WayfinderApiError","error","wrapMiddlewareError","terminal","onError","error$1"],"sources":["../src/context.ts"],"sourcesContent":["import { error as logError } from './_dev';\nimport { WayfinderApiError } from './errors';\nimport type {\n Middleware,\n NavigationStatus,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatch,\n RouteMatchBranch,\n RouteParams,\n RouterErrorContext,\n RouteState,\n RouteTable,\n} from './types';\n\n// ─── Route state ──────────────────────────────────────────────────────────────\n\n/** No defensive deep-copy: RouteState is typed readonly; callers always pass fresh objects. */\nexport function createRouteState(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch;\n status: NavigationStatus;\n}): RouteState {\n return {\n error: input.error,\n location: input.location,\n matches: input.matches,\n status: input.status,\n };\n}\n\n/**\n * Build a RouteMatchBranch from compiled defs and data results.\n */\nexport function buildMatchBranch(\n branchDefs: readonly RouteBranchDef[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n): RouteMatchBranch {\n return branchDefs.map(\n (def, i): RouteMatch => ({\n data: dataResults[i],\n name: def.name,\n params: { ...params },\n pathname,\n }),\n );\n}\n\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function createRouteContext<TRoutes extends RouteTable>(\n location: RouteLocation,\n resolvedQuery: ResolvedQueryParams,\n params: RouteParams,\n matches: RouteMatchBranch,\n navigate: RouteContext<RouteParams, TRoutes>['navigate'],\n): RouteContext<RouteParams, TRoutes> {\n return {\n hash: location.hash,\n historyState: location.historyState,\n locals: {},\n matches,\n navigate,\n params,\n pathname: location.pathname,\n query: resolvedQuery,\n };\n}\n\n// ─── Middleware pipeline ──────────────────────────────────────────────────────\n\nexport async function executeMiddlewarePipeline<TRoutes extends RouteTable>(\n context: RouteContext<RouteParams, TRoutes>,\n middleware: readonly Middleware<TRoutes>[],\n terminal: () => Promise<void>,\n wrapMiddlewareError?: (error: unknown) => unknown,\n): Promise<boolean> {\n let terminalRan = false;\n\n async function dispatch(index: number): Promise<void> {\n if (index < middleware.length) {\n let called = false;\n\n try {\n await middleware[index]?.(context, async () => {\n if (called) throw new WayfinderApiError('next() called multiple times');\n\n called = true;\n await dispatch(index + 1);\n });\n } catch (error) {\n throw wrapMiddlewareError?.(error) ?? error;\n }\n\n return;\n }\n\n terminalRan = true;\n await terminal();\n }\n\n await dispatch(0);\n\n return terminalRan;\n}\n\n// ─── Error reporting ──────────────────────────────────────────────────────────\n\nexport function reportError(\n error: unknown,\n context: RouterErrorContext,\n onError?: (e: unknown, ctx: RouterErrorContext) => void,\n): void {\n if (onError) {\n onError(error, context);\n\n return;\n }\n\n logError('Unhandled router error. Provide an onError callback to handle errors explicitly:', error);\n}\n"],"mappings":";;;AAoBA,SAAgB,iBAAiB,GAKlB;CACb,OAAO;EACL,OAAOC,EAAM;EACb,UAAUA,EAAM;EAChB,SAASA,EAAM;EACf,QAAQA,EAAM;CAChB;AACF;AAKA,SAAgB,iBACd,GACA,GACA,GACA,GACkB;CAClB,OAAOC,EAAW,KACf,GAAK,OAAmB;EACvB,MAAMC,EAAY;EAClB,MAAMC,EAAI;EACV,QAAQ,EAAE,GAAGC,EAAO;EACpB;CACF,EACF;AACF;AAIA,SAAgB,mBACd,GACA,GACA,GACA,GACA,GACoC;CACpC,OAAO;EACL,MAAMC,EAAS;EACf,cAAcA,EAAS;EACvB,QAAQ,CAAC;EACT;EACA;EACA;EACA,UAAUA,EAAS;EACnB,OAAOC;CACT;AACF;AAIA,eAAsB,0BACpB,GACA,GACA,GACA,GACkB;CAClB,IAAIC,IAAc;CAElB,eAAe,SAAS,GAA8B;EACpD,IAAIC,IAAQC,EAAW,QAAQ;GAC7B,IAAIC,IAAS;GAEb,IAAI;IACF,MAAMD,EAAWD,EAAM,GAAGG,GAAS,YAAY;KAC7C,IAAID,GAAQ,MAAM,IAAIE,EAAkB,8BAA8B;KAGtE,AADA,IAAS,IACT,MAAM,SAASJ,IAAQ,CAAC;IAC1B,CAAC;GACH,SAASK,GAAO;IACd,MAAMC,IAAsBD,CAAK,KAAKA;GACxC;EAGF,OAGA,AADA,IAAc,IACd,MAAME,EAAS;CACjB;CAIA,OAFA,MAAM,SAAS,CAAC,GAETR;AACT;AAIA,SAAgB,YACd,GACA,GACA,GACM;CACN,AAAIS,KACFA,EAAQjB,GAAOY,CAAO;AAM1B"}
|
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */\nexport class WayfinderError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when any router method is called after the router has been disposed. */\nexport class WayfinderDisposedError extends WayfinderError {\n constructor() {\n super('Router is disposed');\n }\n}\n\n/** Thrown when a route or path definition is malformed at `createRouter()` time. */\nexport class WayfinderConfigError extends WayfinderError {}\n\n/** Thrown when a route or path is malformed at navigation time (unknown name, missing param). */\nexport class WayfinderRouteError extends WayfinderError {}\n\n/** Thrown when the router detects an infinite redirect loop. */\nexport class WayfinderRedirectLoopError extends WayfinderError {\n constructor() {\n super('Redirect loop detected');\n }\n}\n\n/** Thrown on API misuse (e.g. calling next() multiple times). */\nexport class WayfinderApiError extends WayfinderError {}\n"],"mappings":"AACA,IAAa,eAAb,cAAoC,KAAM,CACxC,YAAY,EAAiB,EAAqB,CAChD,
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":["message","opts"],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */\nexport class WayfinderError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when any router method is called after the router has been disposed. */\nexport class WayfinderDisposedError extends WayfinderError {\n constructor() {\n super('Router is disposed');\n }\n}\n\n/** Thrown when a route or path definition is malformed at `createRouter()` time. */\nexport class WayfinderConfigError extends WayfinderError {}\n\n/** Thrown when a route or path is malformed at navigation time (unknown name, missing param). */\nexport class WayfinderRouteError extends WayfinderError {}\n\n/** Thrown when the router detects an infinite redirect loop. */\nexport class WayfinderRedirectLoopError extends WayfinderError {\n constructor() {\n super('Redirect loop detected');\n }\n}\n\n/** Thrown on API misuse (e.g. calling next() multiple times). */\nexport class WayfinderApiError extends WayfinderError {}\n"],"mappings":"AACA,IAAa,eAAb,cAAoC,KAAM,CACxC,YAAY,EAAiB,EAAqB,CAChD,MAAMA,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,uBAAb,cAA4C,cAAe,CACzD,aAAc,CACZ,MAAM,oBAAoB,CAC5B,CACF,EAGa,qBAAb,cAA0C,cAAe,CAAC,EAG7C,oBAAb,cAAyC,cAAe,CAAC,EAG5C,2BAAb,cAAgD,cAAe,CAC7D,aAAc,CACZ,MAAM,wBAAwB,CAChC,CACF,EAGa,kBAAb,cAAuC,cAAe,CAAC,E"}
|
package/dist/errors.js
CHANGED
|
@@ -1,2 +1,18 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
var WayfinderError = class extends Error {
|
|
3
|
+
constructor(e, t) {
|
|
4
|
+
super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
|
|
5
|
+
}
|
|
6
|
+
}, WayfinderDisposedError = class extends WayfinderError {
|
|
7
|
+
constructor() {
|
|
8
|
+
super("Router is disposed");
|
|
9
|
+
}
|
|
10
|
+
}, WayfinderConfigError = class extends WayfinderError {}, WayfinderRouteError = class extends WayfinderError {}, WayfinderRedirectLoopError = class extends WayfinderError {
|
|
11
|
+
constructor() {
|
|
12
|
+
super("Redirect loop detected");
|
|
13
|
+
}
|
|
14
|
+
}, WayfinderApiError = class extends WayfinderError {};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { WayfinderApiError, WayfinderConfigError, WayfinderDisposedError, WayfinderError, WayfinderRedirectLoopError, WayfinderRouteError };
|
|
17
|
+
|
|
2
18
|
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */\nexport class WayfinderError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when any router method is called after the router has been disposed. */\nexport class WayfinderDisposedError extends WayfinderError {\n constructor() {\n super('Router is disposed');\n }\n}\n\n/** Thrown when a route or path definition is malformed at `createRouter()` time. */\nexport class WayfinderConfigError extends WayfinderError {}\n\n/** Thrown when a route or path is malformed at navigation time (unknown name, missing param). */\nexport class WayfinderRouteError extends WayfinderError {}\n\n/** Thrown when the router detects an infinite redirect loop. */\nexport class WayfinderRedirectLoopError extends WayfinderError {\n constructor() {\n super('Redirect loop detected');\n }\n}\n\n/** Thrown on API misuse (e.g. calling next() multiple times). */\nexport class WayfinderApiError extends WayfinderError {}\n"],"mappings":"AACA,IAAa,
|
|
1
|
+
{"version":3,"file":"errors.js","names":["message","opts"],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */\nexport class WayfinderError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when any router method is called after the router has been disposed. */\nexport class WayfinderDisposedError extends WayfinderError {\n constructor() {\n super('Router is disposed');\n }\n}\n\n/** Thrown when a route or path definition is malformed at `createRouter()` time. */\nexport class WayfinderConfigError extends WayfinderError {}\n\n/** Thrown when a route or path is malformed at navigation time (unknown name, missing param). */\nexport class WayfinderRouteError extends WayfinderError {}\n\n/** Thrown when the router detects an infinite redirect loop. */\nexport class WayfinderRedirectLoopError extends WayfinderError {\n constructor() {\n super('Redirect loop detected');\n }\n}\n\n/** Thrown on API misuse (e.g. calling next() multiple times). */\nexport class WayfinderApiError extends WayfinderError {}\n"],"mappings":";AACA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,yBAAb,cAA4C,eAAe;CACzD,cAAc;EACZ,MAAM,oBAAoB;CAC5B;AACF,GAGa,uBAAb,cAA0C,eAAe,CAAC,GAG7C,sBAAb,cAAyC,eAAe,CAAC,GAG5C,6BAAb,cAAgD,eAAe;CAC7D,cAAc;EACZ,MAAM,wBAAwB;CAChC;AACF,GAGa,oBAAb,cAAuC,eAAe,CAAC"}
|
package/dist/guards.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guards.cjs","names":[],"sources":["../src/guards.ts"],"sourcesContent":["import type { BeforeLeaveBlocker, NavigationDestination } from './types';\n\n/**\n * A registered leave guard. `routes` scopes the guard to navigations that depart from\n * any route whose name appears in the array (matched against any node in the active branch,\n * not just the leaf). When `routes` is omitted the guard fires on every navigation.\n */\nexport type RegisteredBlocker = {\n handler: BeforeLeaveBlocker;\n routes?: string[];\n};\n\n/**\n * Run all registered leave blockers in registration order.\n * Guards whose `routes` filter does not overlap the current active match names are skipped.\n * Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.\n *\n * A snapshot of the blocker set is taken before iteration so that guards added or removed\n * during execution do not affect the current run.\n *\n * `destination` is passed to each blocker so guards can make context-aware decisions.\n */\nexport async function runLeaveBlockers(\n blockers: ReadonlySet<RegisteredBlocker>,\n activeMatchNames: readonly string[],\n destination: NavigationDestination,\n): Promise<boolean> {\n const activeNames = new Set(activeMatchNames);\n // Snapshot so that removals during iteration don't skip entries.\n const snapshot = [...blockers];\n\n for (const { handler, routes } of snapshot) {\n if (routes !== undefined && !routes.some((name) => activeNames.has(name))) continue;\n\n const allowed = await handler(destination);\n\n if (!allowed) return false;\n }\n\n return true;\n}\n"],"mappings":"AAsBA,eAAsB,iBACpB,EACA,EACA,EACkB,CAClB,
|
|
1
|
+
{"version":3,"file":"guards.cjs","names":["activeNames","activeMatchNames","snapshot","blockers","routes","name","handler","destination"],"sources":["../src/guards.ts"],"sourcesContent":["import type { BeforeLeaveBlocker, NavigationDestination } from './types';\n\n/**\n * A registered leave guard. `routes` scopes the guard to navigations that depart from\n * any route whose name appears in the array (matched against any node in the active branch,\n * not just the leaf). When `routes` is omitted the guard fires on every navigation.\n */\nexport type RegisteredBlocker = {\n handler: BeforeLeaveBlocker;\n routes?: string[];\n};\n\n/**\n * Run all registered leave blockers in registration order.\n * Guards whose `routes` filter does not overlap the current active match names are skipped.\n * Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.\n *\n * A snapshot of the blocker set is taken before iteration so that guards added or removed\n * during execution do not affect the current run.\n *\n * `destination` is passed to each blocker so guards can make context-aware decisions.\n */\nexport async function runLeaveBlockers(\n blockers: ReadonlySet<RegisteredBlocker>,\n activeMatchNames: readonly string[],\n destination: NavigationDestination,\n): Promise<boolean> {\n const activeNames = new Set(activeMatchNames);\n // Snapshot so that removals during iteration don't skip entries.\n const snapshot = [...blockers];\n\n for (const { handler, routes } of snapshot) {\n if (routes !== undefined && !routes.some((name) => activeNames.has(name))) continue;\n\n const allowed = await handler(destination);\n\n if (!allowed) return false;\n }\n\n return true;\n}\n"],"mappings":"AAsBA,eAAsB,iBACpB,EACA,EACA,EACkB,CAClB,IAAMA,EAAc,IAAI,IAAIC,CAAgB,EAEtCC,EAAW,CAAC,GAAGC,CAAQ,EAE7B,IAAK,GAAM,CAAE,UAAS,YAAYD,EAChC,IAAIE,IAAW,IAAA,IAAcA,EAAO,KAAM,GAASJ,EAAY,IAAIK,CAAI,CAAC,IAIpE,CAAC,MAFiBC,EAAQC,CAAW,EAE3B,MAAO,GAGvB,MAAO,EACT,C"}
|
package/dist/guards.js
CHANGED
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/guards.ts
|
|
2
|
+
async function runLeaveBlockers(e, t, n) {
|
|
3
|
+
let r = new Set(t), i = [...e];
|
|
4
|
+
for (let { handler: e, routes: t } of i) if ((t === void 0 || t.some((e) => r.has(e))) && !await e(n)) return !1;
|
|
5
|
+
return !0;
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
export { runLeaveBlockers };
|
|
9
|
+
|
|
2
10
|
//# sourceMappingURL=guards.js.map
|
package/dist/guards.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guards.js","names":[],"sources":["../src/guards.ts"],"sourcesContent":["import type { BeforeLeaveBlocker, NavigationDestination } from './types';\n\n/**\n * A registered leave guard. `routes` scopes the guard to navigations that depart from\n * any route whose name appears in the array (matched against any node in the active branch,\n * not just the leaf). When `routes` is omitted the guard fires on every navigation.\n */\nexport type RegisteredBlocker = {\n handler: BeforeLeaveBlocker;\n routes?: string[];\n};\n\n/**\n * Run all registered leave blockers in registration order.\n * Guards whose `routes` filter does not overlap the current active match names are skipped.\n * Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.\n *\n * A snapshot of the blocker set is taken before iteration so that guards added or removed\n * during execution do not affect the current run.\n *\n * `destination` is passed to each blocker so guards can make context-aware decisions.\n */\nexport async function runLeaveBlockers(\n blockers: ReadonlySet<RegisteredBlocker>,\n activeMatchNames: readonly string[],\n destination: NavigationDestination,\n): Promise<boolean> {\n const activeNames = new Set(activeMatchNames);\n // Snapshot so that removals during iteration don't skip entries.\n const snapshot = [...blockers];\n\n for (const { handler, routes } of snapshot) {\n if (routes !== undefined && !routes.some((name) => activeNames.has(name))) continue;\n\n const allowed = await handler(destination);\n\n if (!allowed) return false;\n }\n\n return true;\n}\n"],"mappings":"AAsBA,eAAsB,iBACpB,
|
|
1
|
+
{"version":3,"file":"guards.js","names":["activeNames","activeMatchNames","snapshot","blockers","routes","name","handler","destination"],"sources":["../src/guards.ts"],"sourcesContent":["import type { BeforeLeaveBlocker, NavigationDestination } from './types';\n\n/**\n * A registered leave guard. `routes` scopes the guard to navigations that depart from\n * any route whose name appears in the array (matched against any node in the active branch,\n * not just the leaf). When `routes` is omitted the guard fires on every navigation.\n */\nexport type RegisteredBlocker = {\n handler: BeforeLeaveBlocker;\n routes?: string[];\n};\n\n/**\n * Run all registered leave blockers in registration order.\n * Guards whose `routes` filter does not overlap the current active match names are skipped.\n * Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.\n *\n * A snapshot of the blocker set is taken before iteration so that guards added or removed\n * during execution do not affect the current run.\n *\n * `destination` is passed to each blocker so guards can make context-aware decisions.\n */\nexport async function runLeaveBlockers(\n blockers: ReadonlySet<RegisteredBlocker>,\n activeMatchNames: readonly string[],\n destination: NavigationDestination,\n): Promise<boolean> {\n const activeNames = new Set(activeMatchNames);\n // Snapshot so that removals during iteration don't skip entries.\n const snapshot = [...blockers];\n\n for (const { handler, routes } of snapshot) {\n if (routes !== undefined && !routes.some((name) => activeNames.has(name))) continue;\n\n const allowed = await handler(destination);\n\n if (!allowed) return false;\n }\n\n return true;\n}\n"],"mappings":";AAsBA,eAAsB,iBACpB,GACA,GACA,GACkB;CAClB,IAAMA,IAAc,IAAI,IAAIC,CAAgB,GAEtCC,IAAW,CAAC,GAAGC,CAAQ;CAE7B,KAAK,IAAM,EAAE,YAAS,eAAYD,GAChC,KAAIE,MAAW,KAAA,KAAcA,EAAO,MAAM,MAASJ,EAAY,IAAIK,CAAI,CAAC,MAIpE,CAAC,MAFiBC,EAAQC,CAAW,GAE3B,OAAO;CAGvB,OAAO;AACT"}
|
package/dist/history.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"history.cjs","names":[],"sources":["../src/history.ts"],"sourcesContent":["import { joinPaths, normalizePath, stripBase } from './path';\nimport type { HistoryDriver } from './types';\n\n/** Creates a history driver backed by the browser History API. */\nexport function createBrowserHistory(): HistoryDriver {\n return {\n back() {\n window.history.back();\n },\n get location() {\n return {\n hash: window.location.hash,\n pathname: window.location.pathname,\n search: window.location.search,\n // State lives on window.history.state, not window.location.\n state: window.history.state,\n };\n },\n onPopstate(listener) {\n window.addEventListener('popstate', listener);\n\n return () => window.removeEventListener('popstate', listener);\n },\n push(url, state) {\n window.history.pushState(state, '', url);\n },\n replace(url, state) {\n window.history.replaceState(state, '', url);\n },\n };\n}\n\nexport type HashHistoryOptions = { base?: string };\n\nexport function createHashHistory(options: HashHistoryOptions = {}): HistoryDriver {\n const base = normalizePath(options.base ?? '/');\n const baseRoot = base === '/' ? '/' : `${base}/`;\n const location = () => {\n const parsed = new URL(window.location.hash.slice(1) || '/', 'http://localhost');\n\n return {\n hash: parsed.hash,\n pathname: joinPaths(base, parsed.pathname),\n search: parsed.search,\n state: window.history.state,\n };\n };\n const destination = (url: string) => {\n const parsed = new URL(url, 'http://localhost');\n const pathname = stripBase(parsed.pathname, base);\n\n return `${baseRoot}#${pathname}${parsed.search}${parsed.hash}`;\n };\n\n return {\n back() {\n window.history.back();\n },\n /** Anchor-ready form of an internal URL: the hash driver stores routes behind `#`. */\n href: destination,\n get location() {\n return location();\n },\n onPopstate(listener) {\n window.addEventListener('popstate', listener);\n\n return () => window.removeEventListener('popstate', listener);\n },\n push(url, state) {\n window.history.pushState(state, '', destination(url));\n },\n replace(url, state) {\n window.history.replaceState(state, '', destination(url));\n },\n };\n}\n\n/**\n * Picks the history driver for a deployment base path: a site at the origin root\n * (`'/'`) gets real History-API paths; an app deployed under a sub-path\n * (`import.meta.env.BASE_URL` like `'/demos/voyage/'`) gets the hash driver, so\n * deep links survive a static host that cannot rewrite the base path to the app.\n */\nexport function createHistoryForBase(base: string): HistoryDriver {\n return base === '/' ? createBrowserHistory() : createHashHistory({ base });\n}\n\ntype MemoryLocation = { hash: string; pathname: string; search: string; state: unknown };\n\n/**\n * Creates an in-memory history driver. Suitable for SSR, tests, and non-browser environments.\n *\n * Semantics mirror the browser History API:\n * - `push()` and `replace()` update the location silently (no listener notification),\n * matching `pushState`/`replaceState` which do not fire `popstate`.\n * - `back()` moves one entry back and notifies subscribers, matching a browser back-button press.\n */\nexport function createMemoryHistory(initialPath = '/'): HistoryDriver {\n const parsed = new URL(initialPath, 'http://localhost');\n const stack: MemoryLocation[] = [\n { hash: parsed.hash, pathname: parsed.pathname, search: parsed.search, state: null },\n ];\n let cursor = 0;\n const listeners = new Set<() => void>();\n\n return {\n back() {\n if (cursor <= 0) return;\n\n cursor -= 1;\n listeners.forEach((l) => {\n l();\n });\n },\n get location(): MemoryLocation {\n return stack[cursor]!;\n },\n onPopstate(listener) {\n listeners.add(listener);\n\n return () => listeners.delete(listener);\n },\n push(url, state = null) {\n const p = new URL(url, 'http://localhost');\n\n stack.splice(cursor + 1);\n stack.push({ hash: p.hash, pathname: p.pathname, search: p.search, state });\n cursor = stack.length - 1;\n // Silent: mirrors browser pushState semantics. Router drives navigation via #handleRoute directly.\n },\n replace(url, state = null) {\n const p = new URL(url, 'http://localhost');\n\n stack[cursor] = { hash: p.hash, pathname: p.pathname, search: p.search, state };\n // Silent: mirrors browser replaceState semantics.\n },\n };\n}\n"],"mappings":"8BAIA,SAAgB,sBAAsC,CACpD,MAAO,CACL,MAAO,CACL,OAAO,QAAQ,KAAK,CACtB,EACA,IAAI,UAAW,CACb,MAAO,CACL,KAAM,OAAO,SAAS,KACtB,SAAU,OAAO,SAAS,SAC1B,OAAQ,OAAO,SAAS,OAExB,MAAO,OAAO,QAAQ,KACxB,CACF,EACA,WAAW,EAAU,CAGnB,OAFA,OAAO,iBAAiB,
|
|
1
|
+
{"version":3,"file":"history.cjs","names":["normalizePath","joinPaths","stripBase","require_path","listener","state","url","base","options","baseRoot","parsed","pathname","initialPath","stack","cursor","listeners","l","p"],"sources":["../src/history.ts"],"sourcesContent":["import { joinPaths, normalizePath, stripBase } from './path';\nimport type { HistoryDriver } from './types';\n\n/** Creates a history driver backed by the browser History API. */\nexport function createBrowserHistory(): HistoryDriver {\n return {\n back() {\n window.history.back();\n },\n get location() {\n return {\n hash: window.location.hash,\n pathname: window.location.pathname,\n search: window.location.search,\n // State lives on window.history.state, not window.location.\n state: window.history.state,\n };\n },\n onPopstate(listener) {\n window.addEventListener('popstate', listener);\n\n return () => window.removeEventListener('popstate', listener);\n },\n push(url, state) {\n window.history.pushState(state, '', url);\n },\n replace(url, state) {\n window.history.replaceState(state, '', url);\n },\n };\n}\n\nexport type HashHistoryOptions = { base?: string };\n\nexport function createHashHistory(options: HashHistoryOptions = {}): HistoryDriver {\n const base = normalizePath(options.base ?? '/');\n const baseRoot = base === '/' ? '/' : `${base}/`;\n const location = () => {\n const parsed = new URL(window.location.hash.slice(1) || '/', 'http://localhost');\n\n return {\n hash: parsed.hash,\n pathname: joinPaths(base, parsed.pathname),\n search: parsed.search,\n state: window.history.state,\n };\n };\n const destination = (url: string) => {\n const parsed = new URL(url, 'http://localhost');\n const pathname = stripBase(parsed.pathname, base);\n\n return `${baseRoot}#${pathname}${parsed.search}${parsed.hash}`;\n };\n\n return {\n back() {\n window.history.back();\n },\n /** Anchor-ready form of an internal URL: the hash driver stores routes behind `#`. */\n href: destination,\n get location() {\n return location();\n },\n onPopstate(listener) {\n window.addEventListener('popstate', listener);\n\n return () => window.removeEventListener('popstate', listener);\n },\n push(url, state) {\n window.history.pushState(state, '', destination(url));\n },\n replace(url, state) {\n window.history.replaceState(state, '', destination(url));\n },\n };\n}\n\n/**\n * Picks the history driver for a deployment base path: a site at the origin root\n * (`'/'`) gets real History-API paths; an app deployed under a sub-path\n * (`import.meta.env.BASE_URL` like `'/demos/voyage/'`) gets the hash driver, so\n * deep links survive a static host that cannot rewrite the base path to the app.\n */\nexport function createHistoryForBase(base: string): HistoryDriver {\n return base === '/' ? createBrowserHistory() : createHashHistory({ base });\n}\n\ntype MemoryLocation = { hash: string; pathname: string; search: string; state: unknown };\n\n/**\n * Creates an in-memory history driver. Suitable for SSR, tests, and non-browser environments.\n *\n * Semantics mirror the browser History API:\n * - `push()` and `replace()` update the location silently (no listener notification),\n * matching `pushState`/`replaceState` which do not fire `popstate`.\n * - `back()` moves one entry back and notifies subscribers, matching a browser back-button press.\n */\nexport function createMemoryHistory(initialPath = '/'): HistoryDriver {\n const parsed = new URL(initialPath, 'http://localhost');\n const stack: MemoryLocation[] = [\n { hash: parsed.hash, pathname: parsed.pathname, search: parsed.search, state: null },\n ];\n let cursor = 0;\n const listeners = new Set<() => void>();\n\n return {\n back() {\n if (cursor <= 0) return;\n\n cursor -= 1;\n listeners.forEach((l) => {\n l();\n });\n },\n get location(): MemoryLocation {\n return stack[cursor]!;\n },\n onPopstate(listener) {\n listeners.add(listener);\n\n return () => listeners.delete(listener);\n },\n push(url, state = null) {\n const p = new URL(url, 'http://localhost');\n\n stack.splice(cursor + 1);\n stack.push({ hash: p.hash, pathname: p.pathname, search: p.search, state });\n cursor = stack.length - 1;\n // Silent: mirrors browser pushState semantics. Router drives navigation via #handleRoute directly.\n },\n replace(url, state = null) {\n const p = new URL(url, 'http://localhost');\n\n stack[cursor] = { hash: p.hash, pathname: p.pathname, search: p.search, state };\n // Silent: mirrors browser replaceState semantics.\n },\n };\n}\n"],"mappings":"A,8BAIA,SAAgB,sBAAsC,CACpD,MAAO,CACL,MAAO,CACL,OAAO,QAAQ,KAAK,CACtB,EACA,IAAI,UAAW,CACb,MAAO,CACL,KAAM,OAAO,SAAS,KACtB,SAAU,OAAO,SAAS,SAC1B,OAAQ,OAAO,SAAS,OAExB,MAAO,OAAO,QAAQ,KACxB,CACF,EACA,WAAW,EAAU,CAGnB,OAFA,OAAO,iBAAiB,WAAYI,CAAQ,MAE/B,OAAO,oBAAoB,WAAYA,CAAQ,CAC9D,EACA,KAAK,EAAK,EAAO,CACf,OAAO,QAAQ,UAAUC,EAAO,GAAIC,CAAG,CACzC,EACA,QAAQ,EAAK,EAAO,CAClB,OAAO,QAAQ,aAAaD,EAAO,GAAIC,CAAG,CAC5C,CACF,CACF,CAIA,SAAgB,kBAAkB,EAA8B,CAAC,EAAkB,CACjF,IAAMC,EAAOP,EAAAA,cAAcQ,EAAQ,MAAQ,GAAG,EACxCC,EAAWF,IAAS,IAAM,IAAM,GAAGA,EAAK,GACxC,aAAiB,CACrB,IAAMG,EAAS,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,GAAK,IAAK,kBAAkB,EAE/E,MAAO,CACL,KAAMA,EAAO,KACb,SAAUT,EAAAA,UAAUM,EAAMG,EAAO,QAAQ,EACzC,OAAQA,EAAO,OACf,MAAO,OAAO,QAAQ,KACxB,CACF,EACM,YAAe,GAAgB,CACnC,IAAMA,EAAS,IAAI,IAAIJ,EAAK,kBAAkB,EACxCK,EAAWT,EAAAA,UAAUQ,EAAO,SAAUH,CAAI,EAEhD,MAAO,GAAGE,EAAS,GAAGE,IAAWD,EAAO,SAASA,EAAO,MAC1D,EAEA,MAAO,CACL,MAAO,CACL,OAAO,QAAQ,KAAK,CACtB,EAEA,KAAM,YACN,IAAI,UAAW,CACb,OAAO,SAAS,CAClB,EACA,WAAW,EAAU,CAGnB,OAFA,OAAO,iBAAiB,WAAYN,CAAQ,MAE/B,OAAO,oBAAoB,WAAYA,CAAQ,CAC9D,EACA,KAAK,EAAK,EAAO,CACf,OAAO,QAAQ,UAAUC,EAAO,GAAI,YAAYC,CAAG,CAAC,CACtD,EACA,QAAQ,EAAK,EAAO,CAClB,OAAO,QAAQ,aAAaD,EAAO,GAAI,YAAYC,CAAG,CAAC,CACzD,CACF,CACF,CAQA,SAAgB,qBAAqB,EAA6B,CAChE,OAAOC,IAAS,IAAM,qBAAqB,EAAI,kBAAkB,CAAE,MAAK,CAAC,CAC3E,CAYA,SAAgB,oBAAoB,EAAc,IAAoB,CACpE,IAAMG,EAAS,IAAI,IAAIE,EAAa,kBAAkB,EAChDC,EAA0B,CAC9B,CAAE,KAAMH,EAAO,KAAM,SAAUA,EAAO,SAAU,OAAQA,EAAO,OAAQ,MAAO,IAAK,CACrF,EACII,EAAS,EACPC,EAAY,IAAI,IAEtB,MAAO,CACL,MAAO,CACDD,GAAU,IAEd,IACAC,EAAU,QAAS,GAAM,CACvBC,EAAE,CACJ,CAAC,EACH,EACA,IAAI,UAA2B,CAC7B,OAAOH,EAAMC,EACf,EACA,WAAW,EAAU,CAGnB,OAFAC,EAAU,IAAIX,CAAQ,MAETW,EAAU,OAAOX,CAAQ,CACxC,EACA,KAAK,EAAK,EAAQ,KAAM,CACtB,IAAMa,EAAI,IAAI,IAAIX,EAAK,kBAAkB,EAEzCO,EAAM,OAAOC,EAAS,CAAC,EACvBD,EAAM,KAAK,CAAE,KAAMI,EAAE,KAAM,SAAUA,EAAE,SAAU,OAAQA,EAAE,OAAQ,OAAM,CAAC,EAC1E,EAASJ,EAAM,OAAS,CAE1B,EACA,QAAQ,EAAK,EAAQ,KAAM,CACzB,IAAMI,EAAI,IAAI,IAAIX,EAAK,kBAAkB,EAEzC,EAAMQ,GAAU,CAAE,KAAMG,EAAE,KAAM,SAAUA,EAAE,SAAU,OAAQA,EAAE,OAAQ,OAAM,CAEhF,CACF,CACF,C"}
|
package/dist/history.js
CHANGED
|
@@ -1,2 +1,104 @@
|
|
|
1
|
-
import{joinPaths as e,normalizePath as t,stripBase as n}from"./path.js";
|
|
1
|
+
import { joinPaths as e, normalizePath as t, stripBase as n } from "./path.js";
|
|
2
|
+
//#region src/history.ts
|
|
3
|
+
function createBrowserHistory() {
|
|
4
|
+
return {
|
|
5
|
+
back() {
|
|
6
|
+
window.history.back();
|
|
7
|
+
},
|
|
8
|
+
get location() {
|
|
9
|
+
return {
|
|
10
|
+
hash: window.location.hash,
|
|
11
|
+
pathname: window.location.pathname,
|
|
12
|
+
search: window.location.search,
|
|
13
|
+
state: window.history.state
|
|
14
|
+
};
|
|
15
|
+
},
|
|
16
|
+
onPopstate(e) {
|
|
17
|
+
return window.addEventListener("popstate", e), () => window.removeEventListener("popstate", e);
|
|
18
|
+
},
|
|
19
|
+
push(e, t) {
|
|
20
|
+
window.history.pushState(t, "", e);
|
|
21
|
+
},
|
|
22
|
+
replace(e, t) {
|
|
23
|
+
window.history.replaceState(t, "", e);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function createHashHistory(r = {}) {
|
|
28
|
+
let i = t(r.base ?? "/"), a = i === "/" ? "/" : `${i}/`, location = () => {
|
|
29
|
+
let t = new URL(window.location.hash.slice(1) || "/", "http://localhost");
|
|
30
|
+
return {
|
|
31
|
+
hash: t.hash,
|
|
32
|
+
pathname: e(i, t.pathname),
|
|
33
|
+
search: t.search,
|
|
34
|
+
state: window.history.state
|
|
35
|
+
};
|
|
36
|
+
}, destination = (e) => {
|
|
37
|
+
let t = new URL(e, "http://localhost"), r = n(t.pathname, i);
|
|
38
|
+
return `${a}#${r}${t.search}${t.hash}`;
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
back() {
|
|
42
|
+
window.history.back();
|
|
43
|
+
},
|
|
44
|
+
href: destination,
|
|
45
|
+
get location() {
|
|
46
|
+
return location();
|
|
47
|
+
},
|
|
48
|
+
onPopstate(e) {
|
|
49
|
+
return window.addEventListener("popstate", e), () => window.removeEventListener("popstate", e);
|
|
50
|
+
},
|
|
51
|
+
push(e, t) {
|
|
52
|
+
window.history.pushState(t, "", destination(e));
|
|
53
|
+
},
|
|
54
|
+
replace(e, t) {
|
|
55
|
+
window.history.replaceState(t, "", destination(e));
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function createHistoryForBase(e) {
|
|
60
|
+
return e === "/" ? createBrowserHistory() : createHashHistory({ base: e });
|
|
61
|
+
}
|
|
62
|
+
function createMemoryHistory(e = "/") {
|
|
63
|
+
let t = new URL(e, "http://localhost"), n = [{
|
|
64
|
+
hash: t.hash,
|
|
65
|
+
pathname: t.pathname,
|
|
66
|
+
search: t.search,
|
|
67
|
+
state: null
|
|
68
|
+
}], r = 0, i = /* @__PURE__ */ new Set();
|
|
69
|
+
return {
|
|
70
|
+
back() {
|
|
71
|
+
r <= 0 || (--r, i.forEach((e) => {
|
|
72
|
+
e();
|
|
73
|
+
}));
|
|
74
|
+
},
|
|
75
|
+
get location() {
|
|
76
|
+
return n[r];
|
|
77
|
+
},
|
|
78
|
+
onPopstate(e) {
|
|
79
|
+
return i.add(e), () => i.delete(e);
|
|
80
|
+
},
|
|
81
|
+
push(e, t = null) {
|
|
82
|
+
let i = new URL(e, "http://localhost");
|
|
83
|
+
n.splice(r + 1), n.push({
|
|
84
|
+
hash: i.hash,
|
|
85
|
+
pathname: i.pathname,
|
|
86
|
+
search: i.search,
|
|
87
|
+
state: t
|
|
88
|
+
}), r = n.length - 1;
|
|
89
|
+
},
|
|
90
|
+
replace(e, t = null) {
|
|
91
|
+
let i = new URL(e, "http://localhost");
|
|
92
|
+
n[r] = {
|
|
93
|
+
hash: i.hash,
|
|
94
|
+
pathname: i.pathname,
|
|
95
|
+
search: i.search,
|
|
96
|
+
state: t
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
export { createBrowserHistory, createHashHistory, createHistoryForBase, createMemoryHistory };
|
|
103
|
+
|
|
2
104
|
//# sourceMappingURL=history.js.map
|