@vielzeug/wayfinder 2.2.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +3 -41
  2. package/dist/compile.cjs +1 -1
  3. package/dist/compile.cjs.map +1 -1
  4. package/dist/compile.d.ts +4 -4
  5. package/dist/compile.d.ts.map +1 -1
  6. package/dist/compile.js +2 -5
  7. package/dist/compile.js.map +1 -1
  8. package/dist/context.cjs +1 -1
  9. package/dist/context.cjs.map +1 -1
  10. package/dist/context.d.ts +6 -7
  11. package/dist/context.d.ts.map +1 -1
  12. package/dist/context.js +18 -17
  13. package/dist/context.js.map +1 -1
  14. package/dist/guards.cjs +1 -1
  15. package/dist/guards.cjs.map +1 -1
  16. package/dist/guards.js +1 -1
  17. package/dist/guards.js.map +1 -1
  18. package/dist/history.cjs +1 -1
  19. package/dist/history.cjs.map +1 -1
  20. package/dist/history.d.ts +4 -0
  21. package/dist/history.d.ts.map +1 -1
  22. package/dist/history.js +35 -3
  23. package/dist/history.js.map +1 -1
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -4
  28. package/dist/path.cjs +1 -1
  29. package/dist/path.cjs.map +1 -1
  30. package/dist/path.d.ts +4 -5
  31. package/dist/path.d.ts.map +1 -1
  32. package/dist/path.js +1 -10
  33. package/dist/path.js.map +1 -1
  34. package/dist/router.cjs +1 -1
  35. package/dist/router.cjs.map +1 -1
  36. package/dist/router.d.ts +14 -22
  37. package/dist/router.d.ts.map +1 -1
  38. package/dist/router.js +197 -245
  39. package/dist/router.js.map +1 -1
  40. package/dist/types.d.ts +27 -39
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/wayfinder.cjs +1 -1
  43. package/dist/wayfinder.cjs.map +1 -1
  44. package/dist/wayfinder.iife.js +1 -1
  45. package/dist/wayfinder.iife.js.map +1 -1
  46. package/dist/wayfinder.js +1 -1
  47. package/dist/wayfinder.js.map +1 -1
  48. package/package.json +6 -6
  49. package/dist/hydration.cjs +0 -2
  50. package/dist/hydration.cjs.map +0 -1
  51. package/dist/hydration.d.ts +0 -7
  52. package/dist/hydration.d.ts.map +0 -1
  53. package/dist/hydration.js +0 -55
  54. package/dist/hydration.js.map +0 -1
  55. package/dist/preload.cjs +0 -2
  56. package/dist/preload.cjs.map +0 -1
  57. package/dist/preload.d.ts +0 -18
  58. package/dist/preload.d.ts.map +0 -1
  59. package/dist/preload.js +0 -30
  60. package/dist/preload.js.map +0 -1
package/README.md CHANGED
@@ -1,39 +1,6 @@
1
1
  # @vielzeug/wayfinder
2
2
 
3
- > Lightweight, type-safe client-side router with nested routes, data loading, middleware, and named navigation.
4
-
5
- [![npm version](https://img.shields.io/npm/v/@vielzeug/wayfinder)](https://www.npmjs.com/package/@vielzeug/wayfinder) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
-
7
- <details>
8
- <summary>Quick Reference</summary>
9
-
10
- **Package:** `@vielzeug/wayfinder` &nbsp;&nbsp; **Category:** Routing
11
-
12
- **Key exports:** `createRouter`, `createBrowserHistory`, `createMemoryHistory`, `redirectTo`
13
-
14
- **When to use:** Framework-agnostic client-side router with typed params, async data loading, middleware, leave guards, and View Transitions support.
15
-
16
- **Related:** [@vielzeug/ripple](https://vielzeug.dev/ripple/) · [@vielzeug/ward](https://vielzeug.dev/ward/) · [@vielzeug/herald](https://vielzeug.dev/herald/)
17
-
18
- </details>
19
-
20
- `@vielzeug/wayfinder` is part of Vielzeug and ships as a zero-dependency TypeScript package with ESM+CJS output.
21
-
22
- ## What You Get
23
-
24
- - Declarative route tables with nested names (`dashboard.settings`)
25
- - Named and raw-path navigation through one `navigate()` API
26
- - Route middleware, data loaders, and lazy route modules
27
- - Global `beforeLeave` leave guards with optional route scoping
28
- - `component` + `meta` + `data` payloads on matched branch state
29
- - Per-match `status` for granular loading/streaming feedback in nested layouts
30
- - Streaming data loaders via async generators
31
- - Declarative `notFound` fallback route
32
- - Browser and memory history drivers
33
- - `redirectTo()` middleware helper
34
- - SSR-compatible `load()` for data prefetching without side effects
35
- - `match()` for synchronous route inspection
36
- - `ready` and `waitFor(name)` for lifecycle coordination
3
+ > Client-side router with middleware and guards
37
4
 
38
5
  ## Installation
39
6
 
@@ -45,8 +12,6 @@ yarn add @vielzeug/wayfinder
45
12
 
46
13
  ## Quick Start
47
14
 
48
- Create a memory-backed router, await initial routing, then navigate by route name.
49
-
50
15
  ```ts
51
16
  import { createRouter } from '@vielzeug/wayfinder';
52
17
 
@@ -65,7 +30,7 @@ const router = createRouter({
65
30
  },
66
31
  },
67
32
  notFound: {
68
- component: NotFoundPage,
33
+ data: () => ({ message: 'Not found' }),
69
34
  },
70
35
  });
71
36
 
@@ -74,7 +39,7 @@ await router.ready;
74
39
  // React to state changes:
75
40
  router.subscribe((state) => {
76
41
  const leaf = state.matches.at(-1);
77
- render(leaf?.component, leaf?.data);
42
+ render(leaf?.name, leaf?.data);
78
43
  });
79
44
 
80
45
  await router.navigate({ name: 'dashboard.settings' });
@@ -87,9 +52,6 @@ await router.navigate({ name: 'dashboard.settings' });
87
52
  - [API Reference](https://vielzeug.dev/wayfinder/api)
88
53
  - [Examples](https://vielzeug.dev/wayfinder/examples)
89
54
  - [Migration Guide](https://vielzeug.dev/wayfinder/migration)
90
- - [React Integration Example](https://vielzeug.dev/wayfinder/examples/react-integration)
91
- - [Vue Integration Example](https://vielzeug.dev/wayfinder/examples/vue-integration)
92
- - [Svelte Integration Example](https://vielzeug.dev/wayfinder/examples/svelte-integration)
93
55
 
94
56
  ## License
95
57
 
package/dist/compile.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs");require("./_dev.cjs");const t=require("./path.cjs");function n(n){let r=[],i=(n,a,o,s,c)=>{if(a.index&&a.path!==void 0)throw new e.WayfinderRouteError(`Route "${n}" cannot define both index and path`);if(!a.index&&a.path===void 0)throw new e.WayfinderRouteError(`Route "${n}" must define path or set index: true`);let l=a.index?o:t.normalizePath(a.path?t.joinPaths(o,a.path):o),u=[...s,{component:a.component,dataFn:a.data,lazy:a.lazy,meta:a.meta,name:n,onError:a.onError}],d=[...c,...a.middleware??[]];if(a.children)for(let[e,t]of Object.entries(a.children))i(`${n}.${e}`,t,l,u,d);if(a.lazy!==void 0||a.redirect!==void 0||!a.children||a.data!==void 0){let e=u[u.length-1];r.push({branchDefs:u,coerceSearch:a.coerceSearch,leaf:e,matcher:t.compilePathMatcher(l),ownMiddleware:d,path:l,redirect:a.redirect})}};for(let[e,t]of Object.entries(n.routes))i(e,t,`/`,[],[]);let a=new Set;for(let t of r){if(a.has(t.leaf.name))throw new e.WayfinderRouteError(`Duplicate route name: "${t.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);a.add(t.leaf.name)}let o=!1;for(let e of r){let t=e.path===`/*`||e.path.endsWith(`/*`)||e.path.includes(`:`)&&e.path.endsWith(`*`);o&&!t&&`${e.leaf.name}${e.path}`,t&&(o=!0)}return{records:r,routesByName:new Map(r.map(e=>[e.leaf.name,e]))}}exports.compileRoutes=n;
1
+ const e=require("./errors.cjs"),t=require("./path.cjs");require("./_dev.cjs");function n(n){let r=[],i=(n,a,o,s,c)=>{if(a.index&&a.path!==void 0)throw new e.WayfinderRouteError(`Route "${n}" cannot define both index and path`);if(!a.index&&a.path===void 0)throw new e.WayfinderRouteError(`Route "${n}" must define path or set index: true`);let l=a.index?o:t.normalizePath(a.path?t.joinPaths(o,a.path):o),u=[...s,{dataFn:a.data,name:n,onError:a.onError}],d=[...c,...a.middleware??[]];if(a.children)for(let[e,t]of Object.entries(a.children))i(`${n}.${e}`,t,l,u,d);if(a.redirect!==void 0||!a.children||a.data!==void 0){let e=u[u.length-1];r.push({branchDefs:u,coerceSearch:a.coerceSearch,leaf:e,matcher:t.compilePathMatcher(l),ownMiddleware:d,path:l,redirect:a.redirect})}};for(let[e,t]of Object.entries(n.routes))i(e,t,`/`,[],[]);let a=new Set;for(let t of r){if(a.has(t.leaf.name))throw new e.WayfinderRouteError(`Duplicate route name: "${t.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);a.add(t.leaf.name)}let o=!1;for(let e of r){let t=e.path===`/*`||e.path.endsWith(`/*`)||e.path.includes(`:`)&&e.path.endsWith(`*`);o&&!t&&`${e.leaf.name}${e.path}`,t&&(o=!0)}return{records:r,routesByName:new Map(r.map(e=>[e.leaf.name,e]))}}exports.compileRoutes=n;
2
2
  //# sourceMappingURL=compile.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile.cjs","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderRouteError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\nimport type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nexport type CompiledRoutes<TMeta = unknown, TComponent = unknown> = {\n records: readonly RouteRecord<TMeta, TComponent>[];\n routesByName: ReadonlyMap<string, RouteRecord<TMeta, TComponent>>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable, TMeta, TComponent>(\n options: RouterOptions<TRoutes, TMeta, TComponent>,\n): CompiledRoutes<TMeta, TComponent> {\n const records: RouteRecord<TMeta, TComponent>[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef<TMeta, TComponent>[],\n ancestorMiddleware: RouteRecord<TMeta, TComponent>['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderRouteError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderRouteError(`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<TMeta, TComponent>[] = [\n ...ancestorBranchDefs,\n {\n component: route.component as TComponent | undefined,\n dataFn: route.data,\n lazy: route.lazy as RouteBranchDef<TMeta, TComponent>['lazy'],\n meta: route.meta as TMeta | undefined,\n name,\n onError: route.onError as RouteBranchDef<TMeta, TComponent>['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), redirects, lazy routes, and routes with data.\n // A bare parent-only route (children but no data/lazy/redirect) is not emitted as a leaf.\n if (route.lazy !== undefined || 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 WayfinderRouteError(\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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,KAAK,IAAI,EAChC,MAAM,IAAI,EAAA,oBACR,0BAA0B,EAAO,KAAK,KAAK,oFAC7C,EAGF,EAAU,IAAI,EAAO,KAAK,IAAI,CAChC,CAIA,IAAI,EAAe,GAEnB,IAAK,IAAM,KAAU,EAAS,CAC5B,IAAM,EACJ,EAAO,OAAS,MAAQ,EAAO,KAAK,SAAS,IAAI,GAAM,EAAO,KAAK,SAAS,GAAG,GAAK,EAAO,KAAK,SAAS,GAAG,EAE1G,GAAgB,CAAC,GAEjB,GAAU,EAAO,KAAK,KAAtB,EAAgC,EAAO,KAAvC,EAIA,IAAY,EAAe,GACjC,CAEA,MAAO,CACL,UACA,aAAc,IAAI,IAAI,EAAQ,IAAK,GAAM,CAAC,EAAE,KAAK,KAAM,CAAC,CAAC,CAAC,CAC5D,CACF"}
1
+ {"version":3,"file":"compile.cjs","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderRouteError } 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 WayfinderRouteError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderRouteError(`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 WayfinderRouteError(\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,EAA0C,EAAiD,CACzG,IAAM,EAAyB,CAAC,EAE1B,GACJ,EACA,EACA,EACA,EACA,IACS,CACT,GAAI,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AQ,EAAO,KAAK,SAAS,IAAI,GAAM,EAAO,KAAK,SAAS,GAAG,GAAK,EAAO,KAAK,SAAS,GAAG,EAE1G,GAAgB,CAAC,GAEjB,GAAU,EAAO,KAAK,KAAtB,EAAgC,EAAO,KAAvC,EAIA,IAAY,EAAe,GACjC,CAEA,MAAO,CACL,UACA,aAAc,IAAI,IAAI,EAAQ,IAAK,GAAM,CAAC,EAAE,KAAK,KAAM,CAAC,CAAC,CAAC,CAC5D,CACF"}
package/dist/compile.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { RouteRecord, RouterOptions, RouteTable } from './types';
2
- export type CompiledRoutes<TMeta = unknown, TComponent = unknown> = {
3
- records: readonly RouteRecord<TMeta, TComponent>[];
4
- routesByName: ReadonlyMap<string, RouteRecord<TMeta, TComponent>>;
2
+ export type CompiledRoutes = {
3
+ records: readonly RouteRecord[];
4
+ routesByName: ReadonlyMap<string, RouteRecord>;
5
5
  };
6
- export declare function compileRoutes<TRoutes extends RouteTable, TMeta, TComponent>(options: RouterOptions<TRoutes, TMeta, TComponent>): CompiledRoutes<TMeta, TComponent>;
6
+ export declare function compileRoutes<TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): CompiledRoutes;
7
7
  //# sourceMappingURL=compile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAA+C,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAEnH,MAAM,MAAM,cAAc,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,IAAI;IAClE,OAAO,EAAE,SAAS,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;IACnD,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;CACnE,CAAC;AAEF,wBAAgB,aAAa,CAAC,OAAO,SAAS,UAAU,EAAE,KAAK,EAAE,UAAU,EACzE,OAAO,EAAE,aAAa,CAAC,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,GACjD,cAAc,CAAC,KAAK,EAAE,UAAU,CAAC,CAoGnC"}
1
+ {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAA+C,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAEnH,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;CAChD,CAAC;AAEF,wBAAgB,aAAa,CAAC,OAAO,SAAS,UAAU,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC,GAAG,cAAc,CAiGzG"}
package/dist/compile.js CHANGED
@@ -1,21 +1,18 @@
1
1
  import { WayfinderRouteError as e } from "./errors.js";
2
- import "./_dev.js";
3
2
  import { compilePathMatcher as t, joinPaths as n, normalizePath as r } from "./path.js";
3
+ import "./_dev.js";
4
4
  //#region src/compile.ts
5
5
  function i(i) {
6
6
  let a = [], o = (i, s, c, l, u) => {
7
7
  if (s.index && s.path !== void 0) throw new e(`Route "${i}" cannot define both index and path`);
8
8
  if (!s.index && s.path === void 0) throw new e(`Route "${i}" must define path or set index: true`);
9
9
  let d = s.index ? c : r(s.path ? n(c, s.path) : c), f = [...l, {
10
- component: s.component,
11
10
  dataFn: s.data,
12
- lazy: s.lazy,
13
- meta: s.meta,
14
11
  name: i,
15
12
  onError: s.onError
16
13
  }], p = [...u, ...s.middleware ?? []];
17
14
  if (s.children) for (let [e, t] of Object.entries(s.children)) o(`${i}.${e}`, t, d, f, p);
18
- if (s.lazy !== void 0 || s.redirect !== void 0 || !s.children || s.data !== void 0) {
15
+ if (s.redirect !== void 0 || !s.children || s.data !== void 0) {
19
16
  let e = f[f.length - 1];
20
17
  a.push({
21
18
  branchDefs: f,
@@ -1 +1 @@
1
- {"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderRouteError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\nimport type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nexport type CompiledRoutes<TMeta = unknown, TComponent = unknown> = {\n records: readonly RouteRecord<TMeta, TComponent>[];\n routesByName: ReadonlyMap<string, RouteRecord<TMeta, TComponent>>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable, TMeta, TComponent>(\n options: RouterOptions<TRoutes, TMeta, TComponent>,\n): CompiledRoutes<TMeta, TComponent> {\n const records: RouteRecord<TMeta, TComponent>[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef<TMeta, TComponent>[],\n ancestorMiddleware: RouteRecord<TMeta, TComponent>['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderRouteError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderRouteError(`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<TMeta, TComponent>[] = [\n ...ancestorBranchDefs,\n {\n component: route.component as TComponent | undefined,\n dataFn: route.data,\n lazy: route.lazy as RouteBranchDef<TMeta, TComponent>['lazy'],\n meta: route.meta as TMeta | undefined,\n name,\n onError: route.onError as RouteBranchDef<TMeta, TComponent>['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), redirects, lazy routes, and routes with data.\n // A bare parent-only route (children but no data/lazy/redirect) is not emitted as a leaf.\n if (route.lazy !== undefined || 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 WayfinderRouteError(\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,EACd,GACmC;CACnC,IAAM,IAA4C,CAAC,GAE7C,KACJ,GACA,GACA,GACA,GACA,MACS;EACT,IAAI,EAAM,SAAS,EAAM,SAAS,KAAA,GAChC,MAAM,IAAI,EAAoB,UAAU,EAAK,oCAAoC;EAGnF,IAAI,CAAC,EAAM,SAAS,EAAM,SAAS,KAAA,GACjC,MAAM,IAAI,EAAoB,UAAU,EAAK,sCAAsC;EAGrF,IAAM,IAAU,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EAAgC,EAAO,KAAvC,GAIA,MAAY,IAAe;CACjC;CAEA,OAAO;EACL;EACA,cAAc,IAAI,IAAI,EAAQ,KAAK,MAAM,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D;AACF"}
1
+ {"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { warn } from './_dev';\nimport { WayfinderRouteError } 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 WayfinderRouteError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderRouteError(`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 WayfinderRouteError(\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,EAA0C,GAAiD;CACzG,IAAM,IAAyB,CAAC,GAE1B,KACJ,GACA,GACA,GACA,GACA,MACS;EACT,IAAI,EAAM,SAAS,EAAM,SAAS,KAAA,GAChC,MAAM,IAAI,EAAoB,UAAU,EAAK,oCAAoC;EAGnF,IAAI,CAAC,EAAM,SAAS,EAAM,SAAS,KAAA,GACjC,MAAM,IAAI,EAAoB,UAAU,EAAK,sCAAsC;EAGrF,IAAM,IAAU,EAAM,QAClB,IACA,EAAc,EAAM,OAAO,EAAU,GAAc,EAAM,IAAI,IAAI,CAAY,GAE3E,IAA+B,CACnC,GAAG,GACH;GACE,QAAQ,EAAM;GACd;GACA,SAAS,EAAM;EACjB,CACF,GA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(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function n(e,t,n,r,i){return e.map((e,a)=>({component:e.component,data:r[a],meta:e.meta,name:e.name,params:{...t},pathname:n,status:i?.[a]??`idle`}))}function r(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 i(t,n,r){let i=!1;async function a(o){if(o<n.length){let r=!1;await n[o]?.(t,async()=>{if(r)throw new e.WayfinderApiError(`next() called multiple times`);r=!0,await a(o+1)});return}i=!0,await r()}return await a(0),i}function a(e,t,n){if(n){n(e,t);return}}exports.buildMatchBranch=n,exports.createRouteContext=r,exports.createRouteState=t,exports.executeMiddlewarePipeline=i,exports.reportError=a;
1
+ const e=require("./errors.cjs");require("./_dev.cjs");function t(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function n(e,t,n,r){return e.map((e,i)=>({data:r[i],name:e.name,params:{...t},pathname:n}))}function r(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 i(t,n,r,i){let a=!1;async function o(s){if(s<n.length){let r=!1;try{await n[s]?.(t,async()=>{if(r)throw new e.WayfinderApiError(`next() called multiple times`);r=!0,await o(s+1)})}catch(e){throw i?.(e)??e}return}a=!0,await r()}return await o(0),a}function a(e,t,n){if(n){n(e,t);return}}exports.buildMatchBranch=n,exports.createRouteContext=r,exports.createRouteState=t,exports.executeMiddlewarePipeline=i,exports.reportError=a;
2
2
  //# sourceMappingURL=context.cjs.map
@@ -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 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<TMeta = unknown, TComponent = unknown>(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch<TMeta, TComponent>;\n status: NavigationStatus;\n}): RouteState<TMeta, TComponent> {\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, data results, and optional per-node statuses.\n * Each node carries its own `status` for fine-grained nested layout feedback.\n */\nexport function buildMatchBranch<TMeta = unknown, TComponent = unknown>(\n branchDefs: readonly RouteBranchDef<TMeta, TComponent>[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n statuses?: readonly NavigationStatus[],\n): RouteMatchBranch<TMeta, TComponent> {\n return branchDefs.map((def, i): RouteMatchBranch<TMeta, TComponent>[number] => ({\n component: def.component as TComponent,\n data: dataResults[i],\n meta: def.meta as TMeta,\n name: def.name,\n params: { ...params },\n pathname,\n status: statuses?.[i] ?? 'idle',\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): 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 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\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":"sDAmBA,SAAgB,EAAwD,EAKtC,CAChC,MAAO,CACL,MAAO,EAAM,MACb,SAAU,EAAM,SAChB,QAAS,EAAM,QACf,OAAQ,EAAM,MAChB,CACF,CAMA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACqC,CACrC,OAAO,EAAW,KAAK,EAAK,KAAoD,CAC9E,UAAW,EAAI,UACf,KAAM,EAAY,GAClB,KAAM,EAAI,KACV,KAAM,EAAI,KACV,OAAQ,CAAE,GAAG,CAAO,EACpB,WACA,OAAQ,IAAW,IAAM,MAC3B,EAAE,CACJ,CAIA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACoC,CACpC,MAAO,CACL,KAAM,EAAS,KACf,aAAc,EAAS,aACvB,OAAQ,CAAC,EACT,UACA,WACA,SACA,SAAU,EAAS,SACnB,MAAO,CACT,CACF,CAIA,eAAsB,EACpB,EACA,EACA,EACkB,CAClB,IAAI,EAAc,GAElB,eAAe,EAAS,EAA8B,CACpD,GAAI,EAAQ,EAAW,OAAQ,CAC7B,IAAI,EAAS,GAEb,MAAM,EAAW,EAAM,GAAG,EAAS,SAAY,CAC7C,GAAI,EAAQ,MAAM,IAAI,EAAA,kBAAkB,8BAA8B,EAEtE,EAAS,GACT,MAAM,EAAS,EAAQ,CAAC,CAC1B,CAAC,EAED,MACF,CAEA,EAAc,GACd,MAAM,EAAS,CACjB,CAIA,OAFA,MAAM,EAAS,CAAC,EAET,CACT,CAIA,SAAgB,EACd,EACA,EACA,EACM,CACN,GAAI,EAAS,CACX,EAAQ,EAAO,CAAO,EAEtB,MACF,CAGF"}
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,EAAiB,EAKlB,CACb,MAAO,CACL,MAAO,EAAM,MACb,SAAU,EAAM,SAChB,QAAS,EAAM,QACf,OAAQ,EAAM,MAChB,CACF,CAKA,SAAgB,EACd,EACA,EACA,EACA,EACkB,CAClB,OAAO,EAAW,KACf,EAAK,KAAmB,CACvB,KAAM,EAAY,GAClB,KAAM,EAAI,KACV,OAAQ,CAAE,GAAG,CAAO,EACpB,UACF,EACF,CACF,CAIA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACoC,CACpC,MAAO,CACL,KAAM,EAAS,KACf,aAAc,EAAS,aACvB,OAAQ,CAAC,EACT,UACA,WACA,SACA,SAAU,EAAS,SACnB,MAAO,CACT,CACF,CAIA,eAAsB,EACpB,EACA,EACA,EACA,EACkB,CAClB,IAAI,EAAc,GAElB,eAAe,EAAS,EAA8B,CACpD,GAAI,EAAQ,EAAW,OAAQ,CAC7B,IAAI,EAAS,GAEb,GAAI,CACF,MAAM,EAAW,EAAM,GAAG,EAAS,SAAY,CAC7C,GAAI,EAAQ,MAAM,IAAI,EAAA,kBAAkB,8BAA8B,EAEtE,EAAS,GACT,MAAM,EAAS,EAAQ,CAAC,CAC1B,CAAC,CACH,OAAS,EAAO,CACd,MAAM,IAAsB,CAAK,GAAK,CACxC,CAEA,MACF,CAEA,EAAc,GACd,MAAM,EAAS,CACjB,CAIA,OAFA,MAAM,EAAS,CAAC,EAET,CACT,CAIA,SAAgB,EACd,EACA,EACA,EACM,CACN,GAAI,EAAS,CACX,EAAQ,EAAO,CAAO,EAEtB,MACF,CAGF"}
package/dist/context.d.ts CHANGED
@@ -1,17 +1,16 @@
1
1
  import type { Middleware, NavigationStatus, ResolvedQueryParams, RouteBranchDef, RouteContext, RouteLocation, RouteMatchBranch, RouteParams, RouterErrorContext, RouteState, RouteTable } from './types';
2
2
  /** No defensive deep-copy — RouteState is typed readonly; callers always pass fresh objects. */
3
- export declare function createRouteState<TMeta = unknown, TComponent = unknown>(input: {
3
+ export declare function createRouteState(input: {
4
4
  error?: unknown;
5
5
  location: RouteLocation;
6
- matches: RouteMatchBranch<TMeta, TComponent>;
6
+ matches: RouteMatchBranch;
7
7
  status: NavigationStatus;
8
- }): RouteState<TMeta, TComponent>;
8
+ }): RouteState;
9
9
  /**
10
- * Build a RouteMatchBranch from compiled defs, data results, and optional per-node statuses.
11
- * Each node carries its own `status` for fine-grained nested layout feedback.
10
+ * Build a RouteMatchBranch from compiled defs and data results.
12
11
  */
13
- export declare function buildMatchBranch<TMeta = unknown, TComponent = unknown>(branchDefs: readonly RouteBranchDef<TMeta, TComponent>[], params: RouteParams, pathname: string, dataResults: unknown[], statuses?: readonly NavigationStatus[]): RouteMatchBranch<TMeta, TComponent>;
12
+ export declare function buildMatchBranch(branchDefs: readonly RouteBranchDef[], params: RouteParams, pathname: string, dataResults: unknown[]): RouteMatchBranch;
14
13
  export declare function createRouteContext<TRoutes extends RouteTable>(location: RouteLocation, resolvedQuery: ResolvedQueryParams, params: RouteParams, matches: RouteMatchBranch, navigate: RouteContext<RouteParams, TRoutes>['navigate']): RouteContext<RouteParams, TRoutes>;
15
- export declare function executeMiddlewarePipeline<TRoutes extends RouteTable>(context: RouteContext<RouteParams, TRoutes>, middleware: readonly Middleware<TRoutes>[], terminal: () => Promise<void>): Promise<boolean>;
14
+ export declare function executeMiddlewarePipeline<TRoutes extends RouteTable>(context: RouteContext<RouteParams, TRoutes>, middleware: readonly Middleware<TRoutes>[], terminal: () => Promise<void>, wrapMiddlewareError?: (error: unknown) => unknown): Promise<boolean>;
16
15
  export declare function reportError(error: unknown, context: RouterErrorContext, onError?: (e: unknown, ctx: RouterErrorContext) => void): void;
17
16
  //# sourceMappingURL=context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,UAAU,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,UAAU,EACX,MAAM,SAAS,CAAC;AAIjB,gGAAgG;AAChG,wBAAgB,gBAAgB,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,EAAE,KAAK,EAAE;IAC7E,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,aAAa,CAAC;IACxB,OAAO,EAAE,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAC7C,MAAM,EAAE,gBAAgB,CAAC;CAC1B,GAAG,UAAU,CAAC,KAAK,EAAE,UAAU,CAAC,CAOhC;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,EACpE,UAAU,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,EACxD,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,OAAO,EAAE,EACtB,QAAQ,CAAC,EAAE,SAAS,gBAAgB,EAAE,GACrC,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,CAUrC;AAID,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,UAAU,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WAAW,EAAE,OAAO,EAAE,GACrB,gBAAgB,CASlB;AAID,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,UAAU,EAC3D,QAAQ,EAAE,aAAa,EACvB,aAAa,EAAE,mBAAmB,EAClC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,gBAAgB,EACzB,QAAQ,EAAE,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,GACvD,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,CAWpC;AAID,wBAAsB,yBAAyB,CAAC,OAAO,SAAS,UAAU,EACxE,OAAO,EAAE,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,EAC3C,UAAU,EAAE,SAAS,UAAU,CAAC,OAAO,CAAC,EAAE,EAC1C,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,EAC7B,mBAAmB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,GAChD,OAAO,CAAC,OAAO,CAAC,CA4BlB;AAID,wBAAgB,WAAW,CACzB,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,kBAAkB,KAAK,IAAI,GACtD,IAAI,CAQN"}
package/dist/context.js CHANGED
@@ -9,15 +9,12 @@ function t(e) {
9
9
  status: e.status
10
10
  };
11
11
  }
12
- function n(e, t, n, r, i) {
13
- return e.map((e, a) => ({
14
- component: e.component,
15
- data: r[a],
16
- meta: e.meta,
12
+ function n(e, t, n, r) {
13
+ return e.map((e, i) => ({
14
+ data: r[i],
17
15
  name: e.name,
18
16
  params: { ...t },
19
- pathname: n,
20
- status: i?.[a] ?? "idle"
17
+ pathname: n
21
18
  }));
22
19
  }
23
20
  function r(e, t, n, r, i) {
@@ -32,20 +29,24 @@ function r(e, t, n, r, i) {
32
29
  query: t
33
30
  };
34
31
  }
35
- async function i(t, n, r) {
36
- let i = !1;
37
- async function a(o) {
38
- if (o < n.length) {
32
+ async function i(t, n, r, i) {
33
+ let a = !1;
34
+ async function o(s) {
35
+ if (s < n.length) {
39
36
  let r = !1;
40
- await n[o]?.(t, async () => {
41
- if (r) throw new e("next() called multiple times");
42
- r = !0, await a(o + 1);
43
- });
37
+ try {
38
+ await n[s]?.(t, async () => {
39
+ if (r) throw new e("next() called multiple times");
40
+ r = !0, await o(s + 1);
41
+ });
42
+ } catch (e) {
43
+ throw i?.(e) ?? e;
44
+ }
44
45
  return;
45
46
  }
46
- i = !0, await r();
47
+ a = !0, await r();
47
48
  }
48
- return await a(0), i;
49
+ return await o(0), a;
49
50
  }
50
51
  function a(e, t, n) {
51
52
  if (n) {
@@ -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 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<TMeta = unknown, TComponent = unknown>(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch<TMeta, TComponent>;\n status: NavigationStatus;\n}): RouteState<TMeta, TComponent> {\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, data results, and optional per-node statuses.\n * Each node carries its own `status` for fine-grained nested layout feedback.\n */\nexport function buildMatchBranch<TMeta = unknown, TComponent = unknown>(\n branchDefs: readonly RouteBranchDef<TMeta, TComponent>[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n statuses?: readonly NavigationStatus[],\n): RouteMatchBranch<TMeta, TComponent> {\n return branchDefs.map((def, i): RouteMatchBranch<TMeta, TComponent>[number] => ({\n component: def.component as TComponent,\n data: dataResults[i],\n meta: def.meta as TMeta,\n name: def.name,\n params: { ...params },\n pathname,\n status: statuses?.[i] ?? 'idle',\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): 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 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\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":";;;AAmBA,SAAgB,EAAwD,GAKtC;CAChC,OAAO;EACL,OAAO,EAAM;EACb,UAAU,EAAM;EAChB,SAAS,EAAM;EACf,QAAQ,EAAM;CAChB;AACF;AAMA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACqC;CACrC,OAAO,EAAW,KAAK,GAAK,OAAoD;EAC9E,WAAW,EAAI;EACf,MAAM,EAAY;EAClB,MAAM,EAAI;EACV,MAAM,EAAI;EACV,QAAQ,EAAE,GAAG,EAAO;EACpB;EACA,QAAQ,IAAW,MAAM;CAC3B,EAAE;AACJ;AAIA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACoC;CACpC,OAAO;EACL,MAAM,EAAS;EACf,cAAc,EAAS;EACvB,QAAQ,CAAC;EACT;EACA;EACA;EACA,UAAU,EAAS;EACnB,OAAO;CACT;AACF;AAIA,eAAsB,EACpB,GACA,GACA,GACkB;CAClB,IAAI,IAAc;CAElB,eAAe,EAAS,GAA8B;EACpD,IAAI,IAAQ,EAAW,QAAQ;GAC7B,IAAI,IAAS;GAEb,MAAM,EAAW,EAAM,GAAG,GAAS,YAAY;IAC7C,IAAI,GAAQ,MAAM,IAAI,EAAkB,8BAA8B;IAGtE,AADA,IAAS,IACT,MAAM,EAAS,IAAQ,CAAC;GAC1B,CAAC;GAED;EACF;EAGA,AADA,IAAc,IACd,MAAM,EAAS;CACjB;CAIA,OAFA,MAAM,EAAS,CAAC,GAET;AACT;AAIA,SAAgB,EACd,GACA,GACA,GACM;CACN,IAAI,GAAS;EACX,EAAQ,GAAO,CAAO;EAEtB;CACF;AAGF"}
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":";;;AAoBA,SAAgB,EAAiB,GAKlB;CACb,OAAO;EACL,OAAO,EAAM;EACb,UAAU,EAAM;EAChB,SAAS,EAAM;EACf,QAAQ,EAAM;CAChB;AACF;AAKA,SAAgB,EACd,GACA,GACA,GACA,GACkB;CAClB,OAAO,EAAW,KACf,GAAK,OAAmB;EACvB,MAAM,EAAY;EAClB,MAAM,EAAI;EACV,QAAQ,EAAE,GAAG,EAAO;EACpB;CACF,EACF;AACF;AAIA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACoC;CACpC,OAAO;EACL,MAAM,EAAS;EACf,cAAc,EAAS;EACvB,QAAQ,CAAC;EACT;EACA;EACA;EACA,UAAU,EAAS;EACnB,OAAO;CACT;AACF;AAIA,eAAsB,EACpB,GACA,GACA,GACA,GACkB;CAClB,IAAI,IAAc;CAElB,eAAe,EAAS,GAA8B;EACpD,IAAI,IAAQ,EAAW,QAAQ;GAC7B,IAAI,IAAS;GAEb,IAAI;IACF,MAAM,EAAW,EAAM,GAAG,GAAS,YAAY;KAC7C,IAAI,GAAQ,MAAM,IAAI,EAAkB,8BAA8B;KAGtE,AADA,IAAS,IACT,MAAM,EAAS,IAAQ,CAAC;IAC1B,CAAC;GACH,SAAS,GAAO;IACd,MAAM,IAAsB,CAAK,KAAK;GACxC;GAEA;EACF;EAGA,AADA,IAAc,IACd,MAAM,EAAS;CACjB;CAIA,OAFA,MAAM,EAAS,CAAC,GAET;AACT;AAIA,SAAgB,EACd,GACA,GACA,GACM;CACN,IAAI,GAAS;EACX,EAAQ,GAAO,CAAO;EAEtB;CACF;AAGF"}
package/dist/guards.cjs CHANGED
@@ -1,2 +1,2 @@
1
- async function e(e,t,n){let r=new Set(t),i=[...e];for(let{handler:e,routes:t}of i)if(!(t!==void 0&&!t.some(e=>r.has(e)))&&!await e(n))return!1;return!0}exports.runLeaveBlockers=e;
1
+ async function e(e,t,n){let r=new Set(t),i=[...e];for(let{handler:e,routes:t}of i)if((t===void 0||t.some(e=>r.has(e)))&&!await e(n))return!1;return!0}exports.runLeaveBlockers=e;
2
2
  //# sourceMappingURL=guards.cjs.map
@@ -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,EACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAc,IAAI,IAAI,CAAgB,EAEtC,EAAW,CAAC,GAAG,CAAQ,EAE7B,IAAK,GAAM,CAAE,UAAS,YAAY,EAC5B,SAAW,IAAA,IAAa,CAAC,EAAO,KAAM,GAAS,EAAY,IAAI,CAAI,CAAC,IAIpE,CAAC,MAFiB,EAAQ,CAAW,EAE3B,MAAO,GAGvB,MAAO,EACT"}
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,EACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAc,IAAI,IAAI,CAAgB,EAEtC,EAAW,CAAC,GAAG,CAAQ,EAE7B,IAAK,GAAM,CAAE,UAAS,YAAY,EAC5B,QAAW,IAAA,IAAc,EAAO,KAAM,GAAS,EAAY,IAAI,CAAI,CAAC,IAIpE,CAAC,MAFiB,EAAQ,CAAW,EAE3B,MAAO,GAGvB,MAAO,EACT"}
package/dist/guards.js CHANGED
@@ -1,7 +1,7 @@
1
1
  //#region src/guards.ts
2
2
  async function e(e, t, n) {
3
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;
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
5
  return !0;
6
6
  }
7
7
  //#endregion
@@ -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,EACpB,GACA,GACA,GACkB;CAClB,IAAM,IAAc,IAAI,IAAI,CAAgB,GAEtC,IAAW,CAAC,GAAG,CAAQ;CAE7B,KAAK,IAAM,EAAE,YAAS,eAAY,GAC5B,YAAW,KAAA,KAAa,CAAC,EAAO,MAAM,MAAS,EAAY,IAAI,CAAI,CAAC,MAIpE,CAAC,MAFiB,EAAQ,CAAW,GAE3B,OAAO;CAGvB,OAAO;AACT"}
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,EACpB,GACA,GACA,GACkB;CAClB,IAAM,IAAc,IAAI,IAAI,CAAgB,GAEtC,IAAW,CAAC,GAAG,CAAQ;CAE7B,KAAK,IAAM,EAAE,YAAS,eAAY,GAC5B,WAAW,KAAA,KAAc,EAAO,MAAM,MAAS,EAAY,IAAI,CAAI,CAAC,MAIpE,CAAC,MAFiB,EAAQ,CAAW,GAE3B,OAAO;CAGvB,OAAO;AACT"}
package/dist/history.cjs CHANGED
@@ -1,2 +1,2 @@
1
- function e(){return{back(){window.history.back()},get location(){return{hash:window.location.hash,pathname:window.location.pathname,search:window.location.search,state:window.history.state}},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,e)},replace(e,t){window.history.replaceState(t,``,e)}}}function t(e=`/`){let t=new URL(e,`http://localhost`),n=[{hash:t.hash,pathname:t.pathname,search:t.search,state:null}],r=0,i=new Set;return{back(){r<=0||(--r,i.forEach(e=>{e()}))},get location(){return n[r]},onPopstate(e){return i.add(e),()=>i.delete(e)},push(e,t=null){let i=new URL(e,`http://localhost`);n.splice(r+1),n.push({hash:i.hash,pathname:i.pathname,search:i.search,state:t}),r=n.length-1},replace(e,t=null){let i=new URL(e,`http://localhost`);n[r]={hash:i.hash,pathname:i.pathname,search:i.search,state:t}}}}exports.createBrowserHistory=e,exports.createMemoryHistory=t;
1
+ const e=require("./path.cjs");function t(){return{back(){window.history.back()},get location(){return{hash:window.location.hash,pathname:window.location.pathname,search:window.location.search,state:window.history.state}},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,e)},replace(e,t){window.history.replaceState(t,``,e)}}}function n(t={}){let n=e.normalizePath(t.base??`/`),r=n===`/`?`/`:`${n}/`,i=()=>{let t=new URL(window.location.hash.slice(1)||`/`,`http://localhost`);return{hash:t.hash,pathname:e.joinPaths(n,t.pathname),search:t.search,state:window.history.state}},a=t=>{let i=new URL(t,`http://localhost`),a=e.stripBase(i.pathname,n);return`${r}#${a}${i.search}${i.hash}`};return{back(){window.history.back()},get location(){return i()},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,a(e))},replace(e,t){window.history.replaceState(t,``,a(e))}}}function r(e=`/`){let t=new URL(e,`http://localhost`),n=[{hash:t.hash,pathname:t.pathname,search:t.search,state:null}],r=0,i=new Set;return{back(){r<=0||(--r,i.forEach(e=>{e()}))},get location(){return n[r]},onPopstate(e){return i.add(e),()=>i.delete(e)},push(e,t=null){let i=new URL(e,`http://localhost`);n.splice(r+1),n.push({hash:i.hash,pathname:i.pathname,search:i.search,state:t}),r=n.length-1},replace(e,t=null){let i=new URL(e,`http://localhost`);n[r]={hash:i.hash,pathname:i.pathname,search:i.search,state:t}}}}exports.createBrowserHistory=t,exports.createHashHistory=n,exports.createMemoryHistory=r;
2
2
  //# sourceMappingURL=history.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"history.cjs","names":[],"sources":["../src/history.ts"],"sourcesContent":["import 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\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":"AAGA,SAAgB,GAAsC,CACpD,MAAO,CACL,MAAO,CACL,OAAO,QAAQ,KAAK,CACtB,EACA,IAAI,UAAW,CACb,MAAO,CACL,KAAM,OAAO,SAAS,KACtB,SAAU,O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izePath, 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 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\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,GAAsC,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,WAAY,CAAQ,MAE/B,OAAO,oBAAoB,WAAY,CAAQ,CAC9D,EACA,KAAK,EAAK,EAAO,CACf,OAAO,QAAQ,UAAU,EAAO,GAAI,CAAG,CACzC,EACA,QAAQ,EAAK,EAAO,CAClB,OAAO,QAAQ,aAAa,EAAO,GAAI,CAAG,CAC5C,CACF,CACF,CAIA,SAAgB,EAAkB,EAA8B,CAAC,EAAkB,CACjF,IAAM,EAAO,EAAA,cAAc,EAAQ,MAAQ,GAAG,EACxC,EAAW,IAAS,IAAM,IAAM,GAAG,EAAK,GACxC,MAAiB,CACrB,IAAM,EAAS,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,GAAK,IAAK,kBAAkB,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,SAAU,EAAE,SAAU,OAAQ,EAAE,OAAQ,OAAM,CAAC,EAC1E,EAAS,EAAM,OAAS,CAE1B,EACA,QAAQ,EAAK,EAAQ,KAAM,CACzB,IAAM,EAAI,IAAI,IAAI,EAAK,kBAAkB,EAEzC,EAAM,GAAU,CAAE,KAAM,EAAE,KAAM,SAAU,EAAE,SAAU,OAAQ,EAAE,OAAQ,OAAM,CAEhF,CACF,CACF"}
package/dist/history.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { HistoryDriver } from './types';
2
2
  /** Creates a history driver backed by the browser History API. */
3
3
  export declare function createBrowserHistory(): HistoryDriver;
4
+ export type HashHistoryOptions = {
5
+ base?: string;
6
+ };
7
+ export declare function createHashHistory(options?: HashHistoryOptions): HistoryDriver;
4
8
  /**
5
9
  * Creates an in-memory history driver. Suitable for SSR, tests, and non-browser environments.
6
10
  *
@@ -1 +1 @@
1
- {"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../src/history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,kEAAkE;AAClE,wBAAgB,oBAAoB,IAAI,aAAa,CA0BpD;AAID;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,SAAM,GAAG,aAAa,CAwCpE"}
1
+ {"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../src/history.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,kEAAkE;AAClE,wBAAgB,oBAAoB,IAAI,aAAa,CA0BpD;AAED,MAAM,MAAM,kBAAkB,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnD,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,kBAAuB,GAAG,aAAa,CAuCjF;AAID;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,SAAM,GAAG,aAAa,CAwCpE"}
package/dist/history.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { joinPaths as e, normalizePath as t, stripBase as n } from "./path.js";
1
2
  //#region src/history.ts
2
- function e() {
3
+ function r() {
3
4
  return {
4
5
  back() {
5
6
  window.history.back();
@@ -23,7 +24,38 @@ function e() {
23
24
  }
24
25
  };
25
26
  }
26
- function t(e = "/") {
27
+ function i(r = {}) {
28
+ let i = t(r.base ?? "/"), a = i === "/" ? "/" : `${i}/`, o = () => {
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
+ }, s = (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
+ get location() {
45
+ return o();
46
+ },
47
+ onPopstate(e) {
48
+ return window.addEventListener("popstate", e), () => window.removeEventListener("popstate", e);
49
+ },
50
+ push(e, t) {
51
+ window.history.pushState(t, "", s(e));
52
+ },
53
+ replace(e, t) {
54
+ window.history.replaceState(t, "", s(e));
55
+ }
56
+ };
57
+ }
58
+ function a(e = "/") {
27
59
  let t = new URL(e, "http://localhost"), n = [{
28
60
  hash: t.hash,
29
61
  pathname: t.pathname,
@@ -63,6 +95,6 @@ function t(e = "/") {
63
95
  };
64
96
  }
65
97
  //#endregion
66
- export { e as createBrowserHistory, t as createMemoryHistory };
98
+ export { r as createBrowserHistory, i as createHashHistory, a as createMemoryHistory };
67
99
 
68
100
  //# sourceMappingURL=history.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","names":[],"sources":["../src/history.ts"],"sourcesContent":["import 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\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":";AAGA,SAAgB,IAAsC;CACpD,OAAO;EACL,OAAO;GACL,OAAO,QAAQ,KAAK;EACtB;EACA,IAAI,WAAW;GACb,OAAO;IACL,MAAM,OAAO,SAAS;IACtB,UAAU,OAAO,SAAS;IAC1B,QAAQ,OAAO,SAAS;IAExB,OAAO,OAAO,QAAQ;GACxB;EACF;EACA,WAAW,GAAU;GAGnB,OAFA,OAAO,iBAAiB,YAAY,CAAQ,SAE/B,OAAO,oBAAoB,YAAY,CAAQ;EAC9D;EACA,KAAK,GAAK,GAAO;GACf,OAAO,QAAQ,UAAU,GAAO,IAAI,CAAG;EACzC;EACA,QAAQ,GAAK,GAAO;GAClB,OAAO,QAAQ,aAAa,GAAO,IAAI,CAAG;EAC5C;CACF;AACF;AAYA,SAAgB,EAAoB,IAAc,KAAoB;CACpE,IAAM,IAAS,IAAI,IAAI,GAAa,kBAAkB,GAChD,IAA0B,CAC9B;EAAE,MAAM,EAAO;EAAM,UAAU,EAAO;EAAU,QAAQ,EAAO;EAAQ,OAAO;CAAK,CACrF,GACI,IAAS,GACP,oBAAY,IAAI,IAAgB;CAEtC,OAAO;EACL,OAAO;GACD,KAAU,MAEd,KACA,EAAU,SAAS,MAAM;IACvB,EAAE;GACJ,CAAC;EACH;EACA,IAAI,WAA2B;GAC7B,OAAO,EAAM;EACf;EACA,WAAW,GAAU;GAGnB,OAFA,EAAU,IAAI,CAAQ,SAET,EAAU,OAAO,CAAQ;EACxC;EACA,KAAK,GAAK,IAAQ,MAAM;GACtB,IAAM,IAAI,IAAI,IAAI,GAAK,kBAAkB;GAIzC,AAFA,EAAM,OAAO,IAAS,CAAC,GACvB,EAAM,KAAK;IAAE,MAAM,EAAE;IAAM,UAAU,EAAE;IAAU,QAAQ,EAAE;IAAQ;GAAM,CAAC,GAC1E,IAAS,EAAM,SAAS;EAE1B;EACA,QAAQ,GAAK,IAAQ,MAAM;GACzB,IAAM,IAAI,IAAI,IAAI,GAAK,kBAAkB;GAEzC,EAAM,KAAU;IAAE,MAAM,EAAE;IAAM,UAAU,EAAE;IAAU,QAAQ,EAAE;IAAQ;GAAM;EAEhF;CACF;AACF"}
1
+ {"version":3,"file":"history.js","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 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\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":";;AAIA,SAAgB,IAAsC;CACpD,OAAO;EACL,OAAO;GACL,OAAO,QAAQ,KAAK;EACtB;EACA,IAAI,WAAW;GACb,OAAO;IACL,MAAM,OAAO,SAAS;IACtB,UAAU,OAAO,SAAS;IAC1B,QAAQ,OAAO,SAAS;IAExB,OAAO,OAAO,QAAQ;GACxB;EACF;EACA,WAAW,GAAU;GAGnB,OAFA,OAAO,iBAAiB,YAAY,CAAQ,SAE/B,OAAO,oBAAoB,YAAY,CAAQ;EAC9D;EACA,KAAK,GAAK,GAAO;GACf,OAAO,QAAQ,UAAU,GAAO,IAAI,CAAG;EACzC;EACA,QAAQ,GAAK,GAAO;GAClB,OAAO,QAAQ,aAAa,GAAO,IAAI,CAAG;EAC5C;CACF;AACF;AAIA,SAAgB,EAAkB,IAA8B,CAAC,GAAkB;CACjF,IAAM,IAAO,EAAc,EAAQ,QAAQ,GAAG,GACxC,IAAW,MAAS,MAAM,MAAM,GAAG,EAAK,IACxC,UAAiB;EACrB,IAAM,IAAS,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,KAAK,KAAK,kBAAkB;EAE/E,OAAO;GACL,MAAM,EAAO;GACb,UAAU,EAAU,GAAM,EAAO,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E,IAAS,EAAM,SAAS;EAE1B;EACA,QAAQ,GAAK,IAAQ,MAAM;GACzB,IAAM,IAAI,IAAI,IAAI,GAAK,kBAAkB;GAEzC,EAAM,KAAU;IAAE,MAAM,EAAE;IAAM,UAAU,EAAE;IAAU,QAAQ,EAAE;IAAQ;GAAM;EAEhF;CACF;AACF"}
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./router.cjs");exports.WayfinderApiError=e.WayfinderApiError,exports.WayfinderDisposedError=e.WayfinderDisposedError,exports.WayfinderError=e.WayfinderError,exports.WayfinderRedirectLoopError=e.WayfinderRedirectLoopError,exports.WayfinderRouteError=e.WayfinderRouteError,exports.createBrowserHistory=t.createBrowserHistory,exports.createMemoryHistory=t.createMemoryHistory,exports.createRouter=r.createRouter,exports.redirectTo=n.redirectTo;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./router.cjs");exports.WayfinderApiError=e.WayfinderApiError,exports.WayfinderDisposedError=e.WayfinderDisposedError,exports.WayfinderError=e.WayfinderError,exports.WayfinderRedirectLoopError=e.WayfinderRedirectLoopError,exports.WayfinderRouteError=e.WayfinderRouteError,exports.createBrowserHistory=t.createBrowserHistory,exports.createHashHistory=t.createHashHistory,exports.createMemoryHistory=t.createMemoryHistory,exports.createRouter=r.createRouter,exports.redirectTo=n.redirectTo;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { WayfinderApiError, WayfinderDisposedError, WayfinderError, WayfinderRedirectLoopError, WayfinderRouteError, } from './errors';
2
- export { createBrowserHistory, createMemoryHistory } from './history';
2
+ export { createBrowserHistory, createHashHistory, createMemoryHistory, type HashHistoryOptions } from './history';
3
3
  export { redirectTo } from './middleware';
4
4
  export type { Router } from './router';
5
5
  export { createRouter } from './router';
6
- export type { BeforeLeaveBlocker, BeforeLeaveOptions, CoerceSearchFn, DataContext, DataFn, DataStream, HistoryDriver, IsActiveOptions, MaybePromise, Middleware, NamedNavigationTarget, NavigateOptions, NavigationDestination, NavigationStatus, NavigationTarget, PathParams, QueryParams, RawNavigationTarget, ResolvedQueryParams, ResolvedQueryValue, RouteContext, RouteDefinition, RouteLocation, RouteMatch, RouteMatchBranch, RouteMiddleware, RouteName, RouteParams, RoutePathByName, RouterErrorContext, RouterOptions, RouteState, RouteTable, ScrollDecision, ScrollPosition, Unsubscribe, UntypedNamedNavigationTarget, } from './types';
6
+ export type { BeforeLeaveBlocker, BeforeLeaveOptions, CoerceSearchFn, DataContext, DataFn, HistoryDriver, IsActiveOptions, MaybePromise, Middleware, NamedNavigationTarget, NavigateOptions, NavigationDestination, NavigationStatus, NavigationTarget, PathParams, QueryParams, RawNavigationTarget, ResolvedQueryParams, ResolvedQueryValue, RouteContext, RouteDefinition, RouteLocation, RouteMatch, RouteMatchBranch, RouteMiddleware, RouteName, RouteParams, RoutePathByName, RouterErrorContext, RouterOptions, RouteState, RouteTable, RouteViewMap, RouteViewName, RouteViewRegistry, ScrollDecision, ScrollPosition, Unsubscribe, UntypedNamedNavigationTarget, } from './types';
7
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,EACd,WAAW,EACX,MAAM,EACN,UAAU,EACV,aAAa,EACb,eAAe,EACf,YAAY,EACZ,UAAU,EACV,qBAAqB,EACrB,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,SAAS,EACT,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,UAAU,EACV,UAAU,EACV,cAAc,EACd,cAAc,EACd,WAAW,EACX,4BAA4B,GAC7B,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,KAAK,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAClH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,EACd,WAAW,EACX,MAAM,EACN,aAAa,EACb,eAAe,EACf,YAAY,EACZ,UAAU,EACV,qBAAqB,EACrB,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,SAAS,EACT,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,UAAU,EACV,UAAU,EACV,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,WAAW,EACX,4BAA4B,GAC7B,MAAM,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { WayfinderApiError as e, WayfinderDisposedError as t, WayfinderError as n, WayfinderRedirectLoopError as r, WayfinderRouteError as i } from "./errors.js";
2
- import { createBrowserHistory as a, createMemoryHistory as o } from "./history.js";
3
- import { redirectTo as s } from "./middleware.js";
4
- import { createRouter as c } from "./router.js";
5
- export { e as WayfinderApiError, t as WayfinderDisposedError, n as WayfinderError, r as WayfinderRedirectLoopError, i as WayfinderRouteError, a as createBrowserHistory, o as createMemoryHistory, c as createRouter, s as redirectTo };
2
+ import { createBrowserHistory as a, createHashHistory as o, createMemoryHistory as s } from "./history.js";
3
+ import { redirectTo as c } from "./middleware.js";
4
+ import { createRouter as l } from "./router.js";
5
+ export { e as WayfinderApiError, t as WayfinderDisposedError, n as WayfinderError, r as WayfinderRedirectLoopError, i as WayfinderRouteError, a as createBrowserHistory, o as createHashHistory, s as createMemoryHistory, l as createRouter, c as redirectTo };
package/dist/path.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs");function t(e){let t=`/${e}`.replace(/\/+/g,`/`);return t!==`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function n(e,n){return t(`${e}/${n}`)}function r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function i(n){let i=t(n);if(i===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let a=[],o=i.slice(1).split(`/`),s=[`^`],c=[`^`];for(let t=0;t<o.length;t+=1){let i=o[t];if(i===`*`){if(t!==o.length-1)throw new e.WayfinderRouteError(`Wildcard "*" must be the final segment in path: ${n}`);s.push(`(?:/.*)?`);break}if(i.startsWith(`:`)&&i.endsWith(`*`)){if(t!==o.length-1)throw new e.WayfinderRouteError(`Wildcard param must be final segment in path: ${n}`);let r=i.slice(1,-1);if(!/^\w+$/.test(r))throw new e.WayfinderRouteError(`Invalid param name ":${r}" in path "${n}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);a.push(r),s.push(t===o.length-1?`(?:/(.*))?`:`/(.*)`),c.push(`/.*`);break}if(i.startsWith(`:`)){let t=i.slice(1);if(!/^\w+$/.test(t))throw new e.WayfinderRouteError(`Invalid param name ":${t}" in path "${n}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);a.push(t),s.push(`/([^/]+)`),c.push(`/[^/]+`);continue}let l=r(i);s.push(`/${l}`),c.push(`/${l}`)}return s.push(`$`),c.push(`(?:/.*)?$`),{paramNames:a,pattern:new RegExp(s.join(``)),prefixPattern:new RegExp(c.join(``))}}function a(e,t){let n=t.matcher.pattern.exec(e);if(!n)return null;let r={};return t.matcher.paramNames.forEach((e,t)=>{let i=n[t+1]??``;try{r[e]=decodeURIComponent(i)}catch{r[e]=i}}),r}function o(e,t){for(let n of t){let t=a(e,n);if(t)return{params:t,record:n}}return{params:{}}}function s(e,t){return t.matcher.prefixPattern.test(e)}function c(e){let t=new URLSearchParams(e),n={},r=(e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})};for(let[e,i]of t.entries()){let t=Object.hasOwn(n,e)?n[e]:void 0;if(t===void 0){r(e,i);continue}if(Array.isArray(t)){t.push(i);continue}r(e,[t,i])}return n}function l(t,r,i={},a){let o=r.replace(/:(\w+)(\*)?/g,(t,n,r)=>{let a=i[n];if(a==null)throw new e.WayfinderRouteError(`Missing path param: ${n}`);return r?a.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(a)});if(a&&Object.keys(a).length){let e=new URLSearchParams;Object.entries(a).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),o+=`?${e.toString()}`}return n(t,o)}function u(e,n=`/`){let r=t(e),i=t(n);if(i===`/`)return r;if(r===i)return`/`;let a=`${i}/`;return r.startsWith(a)?t(r.slice(i.length)):r}function d(e,t){return{hash:t.location.hash.replace(/^#/,``),historyState:t.location.state,pathname:u(t.location.pathname||`/`,e),query:c(t.location.search||``)}}function f(e,t,n,r){let i=l(e,t,n);if(!r||Object.keys(r).length===0)return i;let a=new URLSearchParams;for(let[e,t]of Object.entries(r))Array.isArray(t)?t.forEach(t=>{a.append(e,t)}):a.set(e,t);return`${i}?${a.toString()}`}exports.buildPreloadKey=f,exports.buildUrl=l,exports.compilePathMatcher=i,exports.joinPaths=n,exports.matchRecord=a,exports.matchRouteFor=o,exports.matchesPrefix=s,exports.normalizePath=t,exports.parseQuery=c,exports.readLocation=d,exports.stripBase=u;
1
+ const e=require("./errors.cjs");function t(e){let t=`/${e}`.replace(/\/+/g,`/`);return t!==`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function n(e,n){return t(`${e}/${n}`)}function r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function i(n){let i=t(n);if(i===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let a=[],o=i.slice(1).split(`/`),s=[`^`],c=[`^`];for(let t=0;t<o.length;t+=1){let i=o[t];if(i===`*`){if(t!==o.length-1)throw new e.WayfinderRouteError(`Wildcard "*" must be the final segment in path: ${n}`);s.push(`(?:/.*)?`);break}if(i.startsWith(`:`)&&i.endsWith(`*`)){if(t!==o.length-1)throw new e.WayfinderRouteError(`Wildcard param must be final segment in path: ${n}`);let r=i.slice(1,-1);if(!/^\w+$/.test(r))throw new e.WayfinderRouteError(`Invalid param name ":${r}" in path "${n}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);a.push(r),s.push(t===o.length-1?`(?:/(.*))?`:`/(.*)`),c.push(`/.*`);break}if(i.startsWith(`:`)){let t=i.slice(1);if(!/^\w+$/.test(t))throw new e.WayfinderRouteError(`Invalid param name ":${t}" in path "${n}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);a.push(t),s.push(`/([^/]+)`),c.push(`/[^/]+`);continue}let l=r(i);s.push(`/${l}`),c.push(`/${l}`)}return s.push(`$`),c.push(`(?:/.*)?$`),{paramNames:a,pattern:new RegExp(s.join(``)),prefixPattern:new RegExp(c.join(``))}}function a(e,t){let n=t.matcher.pattern.exec(e);if(!n)return null;let r={};return t.matcher.paramNames.forEach((e,t)=>{let i=n[t+1]??``;try{r[e]=decodeURIComponent(i)}catch{r[e]=i}}),r}function o(e,t){for(let n of t){let t=a(e,n);if(t)return{params:t,record:n}}return{params:{}}}function s(e,t){return t.matcher.prefixPattern.test(e)}function c(e){let t=new URLSearchParams(e),n={},r=(e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})};for(let[e,i]of t.entries()){let t=Object.hasOwn(n,e)?n[e]:void 0;if(t===void 0){r(e,i);continue}if(Array.isArray(t)){t.push(i);continue}r(e,[t,i])}return n}function l(t,r,i={},a){let o=r.replace(/:(\w+)(\*)?/g,(t,n,r)=>{let a=i[n];if(a==null)throw new e.WayfinderRouteError(`Missing path param: ${n}`);return r?a.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(a)});if(a&&Object.keys(a).length){let e=new URLSearchParams;Object.entries(a).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),o+=`?${e.toString()}`}return n(t,o)}function u(e,n=`/`){let r=t(e),i=t(n);if(i===`/`)return r;if(r===i)return`/`;let a=`${i}/`;return r.startsWith(a)?t(r.slice(i.length)):r}function d(e,t){return{hash:t.location.hash.replace(/^#/,``),historyState:t.location.state,pathname:u(t.location.pathname||`/`,e),query:c(t.location.search||``)}}exports.buildUrl=l,exports.compilePathMatcher=i,exports.joinPaths=n,exports.matchRecord=a,exports.matchRouteFor=o,exports.matchesPrefix=s,exports.normalizePath=t,exports.parseQuery=c,exports.readLocation=d,exports.stripBase=u;
2
2
  //# sourceMappingURL=path.cjs.map