react-routes-forge 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -20
- package/dist/chunk-H5UZR7HM.js +2 -0
- package/dist/chunk-H5UZR7HM.js.map +1 -0
- package/dist/chunk-NX4N6IWV.js +2 -0
- package/dist/chunk-NX4N6IWV.js.map +1 -0
- package/dist/hooks/index.cjs +1 -1
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +4 -1
- package/dist/hooks/index.d.ts +4 -1
- package/dist/hooks/index.js +1 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/{index-CRAdjXCI.d.cts → index-B3PDrNod.d.cts} +7 -1
- package/dist/{index-CRAdjXCI.d.ts → index-B3PDrNod.d.ts} +7 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -3
- package/dist/index.d.ts +5 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +2 -0
- package/dist/next/index.cjs.map +1 -0
- package/dist/next/index.d.cts +36 -0
- package/dist/next/index.d.ts +36 -0
- package/dist/next/index.js +2 -0
- package/dist/next/index.js.map +1 -0
- package/package.json +12 -2
- package/dist/chunk-IP4ZU25B.js +0 -2
- package/dist/chunk-IP4ZU25B.js.map +0 -1
package/README.md
CHANGED
|
@@ -22,11 +22,14 @@
|
|
|
22
22
|
- [API reference](#api-reference)
|
|
23
23
|
- [`defineRoutes(routeMap)`](#defineroutesroutemap)
|
|
24
24
|
- [`build(template, params, query?, options?)`](#buildtemplate-params-query-options)
|
|
25
|
+
- [`buildPath(template, params, query?, options?)`](#buildpathtemplate-params-query-options)
|
|
25
26
|
- [`isActivePath(currentPath, template, options?)`](#isactivepathcurrentpath-template-options)
|
|
26
27
|
- [`extractParamsFromPath(template, resolvedPath)`](#extractparamsfrompathtemplate-resolvedpath)
|
|
27
28
|
- [`matchPath(template, options?)`](#matchpathtemplate-options)
|
|
28
29
|
- [`joinPaths(...segments)`](#joinpathssegments)
|
|
29
30
|
- [`getParamNames(template)`](#getparamnamestemplate)
|
|
31
|
+
- [`extractParamNames(template)`](#extractparamnamestemplate)
|
|
32
|
+
- [`isDynamic(template)`](#isdynamictemplate)
|
|
30
33
|
- [`flattenRoutes(routes)`](#flattenroutesroutes)
|
|
31
34
|
- [`getBreadcrumbs(routes, currentPath, options?)`](#getbreadcrumbsroutes-currentpath-options)
|
|
32
35
|
- [`appendQuery(path, query?, hash?)`](#appendquerypath-query-hash)
|
|
@@ -39,6 +42,7 @@
|
|
|
39
42
|
- [`useResolvedPath(template, params, query?, options?)`](#useresolvedpathtemplate-params-query-options)
|
|
40
43
|
- [`useActivePath(template, options?)`](#useactivepathtemplate-options)
|
|
41
44
|
- [`useTypedSearchParams(options?)`](#usetypedsearchparamsoptions)
|
|
45
|
+
- [Next.js Integration](#nextjs-integration)
|
|
42
46
|
- [Splat (`/*`) segments](#splat--segments)
|
|
43
47
|
- [Route validation](#route-validation)
|
|
44
48
|
- [Query string support](#query-string-support)
|
|
@@ -165,13 +169,13 @@ That's the entire API surface you need for most apps. Everything below covers th
|
|
|
165
169
|
|
|
166
170
|
### Route types
|
|
167
171
|
|
|
168
|
-
| Route type | Example | Behaves as
|
|
169
|
-
| ----------- | ----------------------- |
|
|
170
|
-
| **Static** | `HOME: '/'` |
|
|
171
|
-
| **Dynamic** | `DETAILS: '/users/:id'` |
|
|
172
|
-
| **Splat** | `FILES: '/files/*'` |
|
|
172
|
+
| Route type | Example | Behaves as | Gains |
|
|
173
|
+
| ----------- | ----------------------- | ------------------------------------- | --------------------------------------------------------------------- |
|
|
174
|
+
| **Static** | `HOME: '/'` | A primitive string (its template) | `.build(query?, options?)` — attach query/hash, no params to fill |
|
|
175
|
+
| **Dynamic** | `DETAILS: '/users/:id'` | A primitive string (its template) | `.build(params, query?, options?)` and `.paramNames` |
|
|
176
|
+
| **Splat** | `FILES: '/files/*'` | A primitive string (its template) | `.build(params, query?, options?)` and `.paramNames` |
|
|
173
177
|
|
|
174
|
-
`defineRoutes()` walks your route object recursively,
|
|
178
|
+
`defineRoutes()` walks your route object recursively, returning every path as a genuine primitive string. `.build()` (and `.paramNames` on dynamic paths) are attached to `String.prototype` once, so both static and dynamic routes can carry a query string or hash. Dynamic paths (containing a `:param` segment or a trailing `/*` splat) additionally gain `.paramNames`.
|
|
175
179
|
|
|
176
180
|
Param names are `[A-Za-z0-9_]` only (matching React Router), so a static suffix after a param stays literal — `/files/:name.json` builds `{ name: "report" }` → `/files/report.json`, and `:name.json` is **not** treated as a single param name.
|
|
177
181
|
|
|
@@ -197,11 +201,14 @@ Quick reference for everything the package exports — grouped by kind. Click th
|
|
|
197
201
|
| Export | Purpose |
|
|
198
202
|
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
|
|
199
203
|
| [`build(template, params, query?, options?)`](#buildtemplate-params-query-options) | Resolve a template into a URL without `defineRoutes` |
|
|
204
|
+
| [`buildPath(template, params, query?, options?)`](#buildpathtemplate-params-query-options) | Same as `build()` — the underlying resolver `build` aliases |
|
|
200
205
|
| [`isActivePath(currentPath, template, options?)`](#isactivepathcurrentpath-template-options) | Check if a path matches a template (nav-highlighting) |
|
|
201
206
|
| [`extractParamsFromPath(template, resolvedPath)`](#extractparamsfrompathtemplate-resolvedpath) | Pull param values back out of a resolved URL |
|
|
202
207
|
| [`matchPath(template, options?)`](#matchpathtemplate-options) | Convert a route template into an anchored `RegExp` |
|
|
203
208
|
| [`joinPaths(...segments)`](#joinpathssegments) | Join and normalize path segments |
|
|
204
209
|
| [`getParamNames(template)`](#getparamnamestemplate) | List the `:param` names in a template |
|
|
210
|
+
| [`extractParamNames(template)`](#extractparamnamestemplate) | Same as `getParamNames()` — the canonical implementation |
|
|
211
|
+
| [`isDynamic(template)`](#isdynamictemplate) | `true` if a template contains a `:param` or trailing `/*` |
|
|
205
212
|
| [`flattenRoutes(routes)`](#flattenroutesroutes) | Flatten a `PATHS` tree for sitemaps / duplicate detection |
|
|
206
213
|
| [`getBreadcrumbs(routes, currentPath, options?)`](#getbreadcrumbsroutes-currentpath-options) | Build a breadcrumb trail from a route tree and current URL |
|
|
207
214
|
| [`appendQuery(path, query?, hash?)`](#appendquerypath-query-hash) | Append query params / hash to an existing path |
|
|
@@ -227,7 +234,7 @@ Quick reference for everything the package exports — grouped by kind. Click th
|
|
|
227
234
|
|
|
228
235
|
Creates a fully typed route object from a nested plain object.
|
|
229
236
|
|
|
230
|
-
- Every path is string
|
|
237
|
+
- Every path is a genuine primitive string — use it directly anywhere a string is expected (e.g. `<Route path={...} />`).
|
|
231
238
|
- Static paths gain **`.build(query?, options?)`** — attach a query string and/or hash fragment without params.
|
|
232
239
|
- Dynamic paths (containing `:param`) and splat paths (trailing `/*`) gain:
|
|
233
240
|
- **`.build(params, query?, options?)`** — resolves the template into a concrete URL
|
|
@@ -304,6 +311,21 @@ See [Splat (`/*`) segments](#splat--segments) for details.
|
|
|
304
311
|
|
|
305
312
|
---
|
|
306
313
|
|
|
314
|
+
### `buildPath(template, params, query?, options?)`
|
|
315
|
+
|
|
316
|
+
The canonical path resolver that [`build()`](#buildtemplate-params-query-options) is an alias of — identical signature and behaviour. It is exported under both names; reach for `buildPath` when you want the name to match the internals (e.g. when reading the [`useResolvedPath()`](#useresolvedpathtemplate-params-query-options) wrapper), and `build` for a shorter call site.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
import { buildPath } from "react-routes-forge";
|
|
320
|
+
|
|
321
|
+
buildPath("/users/:id", { id: 42 }); // → '/users/42'
|
|
322
|
+
buildPath("/users", {}, { sort: "asc" }); // → '/users?sort=asc'
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
All `build()` examples above apply verbatim to `buildPath`.
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
307
329
|
### `isActivePath(currentPath, template, options?)`
|
|
308
330
|
|
|
309
331
|
Checks whether a resolved path matches a route template — the building block for nav-highlighting ("is this link active?"). Query strings on `currentPath` are ignored automatically. It mirrors React Router's `NavLink` matching semantics:
|
|
@@ -411,6 +433,36 @@ getParamNames("/users"); // → []
|
|
|
411
433
|
|
|
412
434
|
---
|
|
413
435
|
|
|
436
|
+
### `extractParamNames(template)`
|
|
437
|
+
|
|
438
|
+
The canonical implementation behind [`getParamNames()`](#getparamnamestemplate) — same signature and results, kept under both names for compatibility. Param names are `[A-Za-z0-9_]` only, recognized at the start of a segment; a trailing `/*` splat is reported as `['*']`.
|
|
439
|
+
|
|
440
|
+
```ts
|
|
441
|
+
import { extractParamNames } from "react-routes-forge";
|
|
442
|
+
|
|
443
|
+
extractParamNames("/users/:id/posts/:postId"); // → ['id', 'postId']
|
|
444
|
+
extractParamNames("/files/*"); // → ['*']
|
|
445
|
+
extractParamNames("/users"); // → []
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
---
|
|
449
|
+
|
|
450
|
+
### `isDynamic(template)`
|
|
451
|
+
|
|
452
|
+
Returns `true` when a template contains a `:param` segment or a trailing `/*` splat, and `false` otherwise. This is exactly the test `defineRoutes()` uses to decide whether a path gains `.paramNames`:
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
import { isDynamic } from "react-routes-forge";
|
|
456
|
+
|
|
457
|
+
isDynamic("/users/:id"); // true
|
|
458
|
+
isDynamic("/users/:id?"); // true (optional params count)
|
|
459
|
+
isDynamic("/files/*"); // true (splat)
|
|
460
|
+
isDynamic("/users"); // false
|
|
461
|
+
isDynamic("/users/foo:bar"); // false (literal colon inside a segment)
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
---
|
|
465
|
+
|
|
414
466
|
### `flattenRoutes(routes)`
|
|
415
467
|
|
|
416
468
|
Walks a `defineRoutes()` tree and returns a flat array of `{ key, path }` entries, where `key` is the dot-joined path from the root (e.g. `"SERVICES.BENEFICIARY_CARE_CENTER.EDIT"`) and `path` is the raw template string.
|
|
@@ -533,6 +585,7 @@ appendQuery("/users?tab=list", { page: 2 }); // → '/users?tab=list&page=2'
|
|
|
533
585
|
appendQuery("/users#top", { tab: "list" }); // → '/users?tab=list#top'
|
|
534
586
|
appendQuery("/users", { active: true }); // → '/users?active=true'
|
|
535
587
|
appendQuery("/users", { tag: ["a", "b"] }); // → '/users?tag=a&tag=b'
|
|
588
|
+
appendQuery("/users", { tag: ["a", null, "b", undefined] }); // → '/users?tag=a&tag=b'
|
|
536
589
|
```
|
|
537
590
|
|
|
538
591
|
This is the same helper every path-resolving function uses internally.
|
|
@@ -592,15 +645,21 @@ beforeEach(() => {
|
|
|
592
645
|
|
|
593
646
|
## React hooks
|
|
594
647
|
|
|
595
|
-
Import these
|
|
648
|
+
Import these if you're using React Router or Next.js — they live in separate entries (`react-routes-forge/hooks` and `react-routes-forge/next`), so the core package never pulls in router dependencies. The React Router hooks work identically with **`react-router-dom`** (v6/v7) and **`react-router`** (v6/v7).
|
|
649
|
+
|
|
650
|
+
> **Note for Next.js users**: Equivalent hooks for Next.js App Router and Pages Router are available in `react-routes-forge/next`. They share the same API as the React Router hooks documented below.
|
|
596
651
|
|
|
597
652
|
### `useRouteParams<T>()`
|
|
598
653
|
|
|
599
|
-
Typed wrapper around React Router's `useParams`. Pass the route's template string as a generic to get a correctly typed params object back — no casting, and it works for any number of `:param` segments. Alternatively, pass a **dynamic route value from your `PATHS` tree** and the params are inferred from it automatically:
|
|
654
|
+
Typed wrapper around React Router's and Next.js's `useParams`. Pass the route's template string as a generic to get a correctly typed params object back — no casting, and it works for any number of `:param` segments. Alternatively, pass a **dynamic route value from your `PATHS` tree** and the params are inferred from it automatically:
|
|
600
655
|
|
|
601
656
|
```tsx
|
|
657
|
+
// For React Router
|
|
602
658
|
import { useRouteParams } from "react-routes-forge/hooks";
|
|
603
659
|
|
|
660
|
+
// For Next.js
|
|
661
|
+
// import { useRouteParams } from "react-routes-forge/next";
|
|
662
|
+
|
|
604
663
|
// Route: '/users/edit/:id'
|
|
605
664
|
function EditUser() {
|
|
606
665
|
const { id } = useRouteParams<"/users/edit/:id">();
|
|
@@ -627,10 +686,13 @@ function EditUserInferred() {
|
|
|
627
686
|
|
|
628
687
|
### `useNavigateTo()`
|
|
629
688
|
|
|
630
|
-
Thin, typed wrapper around `useNavigate()` that accepts a resolved path (the output of `.build()`) along with the usual navigation options.
|
|
689
|
+
Thin, typed wrapper around `useNavigate()` (or Next.js's `useRouter()`) that accepts a resolved path (the output of `.build()`) along with the usual navigation options.
|
|
631
690
|
|
|
632
691
|
```tsx
|
|
692
|
+
// For React Router
|
|
633
693
|
import { useNavigateTo } from "react-routes-forge/hooks";
|
|
694
|
+
// For Next.js
|
|
695
|
+
// import { useNavigateTo } from "react-routes-forge/next";
|
|
634
696
|
import { PATHS } from "./paths";
|
|
635
697
|
|
|
636
698
|
function Component() {
|
|
@@ -651,6 +713,8 @@ navigateTo(PATHS.USERS.ROOT, { state: { from: "settings" } });
|
|
|
651
713
|
|
|
652
714
|
### `useResolvedPath(template, params, query?, options?)`
|
|
653
715
|
|
|
716
|
+
> **Note**: This hook is specific to React Router (`react-routes-forge/hooks`). For Next.js, you can simply use `.build()` directly since Next.js doesn't use relative routing or base paths in the same way.
|
|
717
|
+
|
|
654
718
|
Resolves a path template to a concrete URL string without navigating — useful for `<Link to={...} />`, preloading, or building a URL for something other than `navigate()`. It mirrors the library's own [`build()`](#buildtemplate-params-query-options), so splat (`*`) and optional (`:param?`) segments work identically to the core API — and the encoding/`strict` behaviour is consistent across React Router v6 and v7. Accepts the same `query` and `options` as [`build()`](#buildtemplate-params-query-options).
|
|
655
719
|
|
|
656
720
|
```tsx
|
|
@@ -678,10 +742,13 @@ const path = useResolvedPath("/page", {}, undefined, { hash: "section" });
|
|
|
678
742
|
|
|
679
743
|
### `useActivePath(template, options?)`
|
|
680
744
|
|
|
681
|
-
A hook that checks whether the current location matches a route template or path — a thin wrapper around [`isActivePath()`](#isactivepathcurrentpath-template-options) that reads the location from the router. Same matching semantics: case-insensitive by default, trailing slashes tolerated, `exact: true` by default.
|
|
745
|
+
A hook that checks whether the current location matches a route template or path — a thin wrapper around [`isActivePath()`](#isactivepathcurrentpath-template-options) that reads the location from the router (`useLocation` in React Router, `usePathname` in Next.js). Same matching semantics: case-insensitive by default, trailing slashes tolerated, `exact: true` by default.
|
|
682
746
|
|
|
683
747
|
```tsx
|
|
748
|
+
// For React Router
|
|
684
749
|
import { useActivePath } from "react-routes-forge/hooks";
|
|
750
|
+
// For Next.js
|
|
751
|
+
// import { useActivePath } from "react-routes-forge/next";
|
|
685
752
|
|
|
686
753
|
function Nav() {
|
|
687
754
|
const isUsersActive = useActivePath(PATHS.USERS.ROOT, { exact: false });
|
|
@@ -699,10 +766,13 @@ function Nav() {
|
|
|
699
766
|
|
|
700
767
|
### `useTypedSearchParams(options?)`
|
|
701
768
|
|
|
702
|
-
A typed wrapper around
|
|
769
|
+
A typed wrapper around the router's search-params API (React Router's `useSearchParams` or Next.js's `useSearchParams` + `useRouter`). Returns a parsed query params object (using [`extractQueryFromPath()`](#extractqueryfrompathpath-options)) and a setter that updates the query string. The same coercion options are supported: `{ coerceBooleans: true }` and `{ coerceNumbers: true }`.
|
|
703
770
|
|
|
704
771
|
```tsx
|
|
772
|
+
// For React Router
|
|
705
773
|
import { useTypedSearchParams } from "react-routes-forge/hooks";
|
|
774
|
+
// For Next.js
|
|
775
|
+
// import { useTypedSearchParams } from "react-routes-forge/next";
|
|
706
776
|
|
|
707
777
|
function Filters() {
|
|
708
778
|
const [query, setQuery] = useTypedSearchParams({
|
|
@@ -721,6 +791,35 @@ function Filters() {
|
|
|
721
791
|
|
|
722
792
|
---
|
|
723
793
|
|
|
794
|
+
## Next.js Integration
|
|
795
|
+
|
|
796
|
+
`react-routes-forge` provides first-class support for Next.js App Router and Pages Router. The core utilities (`defineRoutes`, `.build()`, query helpers) are fully isomorphic and can be used on both the client and server.
|
|
797
|
+
|
|
798
|
+
**Client Hooks:**
|
|
799
|
+
All hooks provided for Next.js are available in `react-routes-forge/next` and require a Client Component context (e.g. `"use client"` directive).
|
|
800
|
+
|
|
801
|
+
```tsx
|
|
802
|
+
"use client";
|
|
803
|
+
|
|
804
|
+
import { useActivePath, useRouteParams, useNavigateTo, useTypedSearchParams } from "react-routes-forge/next";
|
|
805
|
+
import { PATHS } from "../paths";
|
|
806
|
+
|
|
807
|
+
export function Sidebar() {
|
|
808
|
+
const isUsersActive = useActivePath(PATHS.USERS.ROOT);
|
|
809
|
+
const { id } = useRouteParams(PATHS.USERS.DETAILS);
|
|
810
|
+
const navigateTo = useNavigateTo();
|
|
811
|
+
|
|
812
|
+
return <nav>...</nav>;
|
|
813
|
+
}
|
|
814
|
+
```
|
|
815
|
+
|
|
816
|
+
**Server Components:**
|
|
817
|
+
You can safely import your `PATHS` definition in Server Components and use `.build()` to generate URLs for `<Link href={...}>`, `redirect()`, or metadata generation without any issues. No `"use client"` is needed for the core API!
|
|
818
|
+
|
|
819
|
+
For a full breakdown of Next.js usage, see the [Next.js documentation](https://mhsmustafa84.github.io/react-routes-forge/nextjs).
|
|
820
|
+
|
|
821
|
+
---
|
|
822
|
+
|
|
724
823
|
## Splat (`/*`) segments
|
|
725
824
|
|
|
726
825
|
Splat routes (`/files/*`) capture the rest of the path — including slashes — into a single `*` param, matching React Router semantics. Supported across the entire core API, not just the hooks.
|
|
@@ -930,22 +1029,23 @@ Everywhere the template string itself was used (e.g. `<Route path={PATHS.SERVICE
|
|
|
930
1029
|
|
|
931
1030
|
## Known behaviours & gotchas
|
|
932
1031
|
|
|
933
|
-
### Routes are
|
|
1032
|
+
### Routes are genuine primitive strings
|
|
934
1033
|
|
|
935
|
-
`defineRoutes`
|
|
1034
|
+
`defineRoutes()` returns **plain primitive strings** — `typeof` a route value is `"string"` and strict equality against the template works. `.build()` (and `.paramNames` on dynamic routes) are not own properties of the route value; they are attached to `String.prototype` once, so every route value can still call them lazily from its own text:
|
|
936
1035
|
|
|
937
1036
|
```ts
|
|
938
1037
|
// ✓ These all work as expected
|
|
1038
|
+
PATHS.HOME === "/"; // true (strict equality works)
|
|
1039
|
+
typeof PATHS.HOME; // 'string'
|
|
939
1040
|
String(PATHS.HOME); // '/'
|
|
940
1041
|
`${PATHS.USERS.EDIT}`; // '/users/edit/:id'
|
|
941
|
-
PATHS.USERS.EDIT
|
|
942
|
-
|
|
943
|
-
// ✗ Watch out for these
|
|
944
|
-
typeof PATHS.HOME; // 'object' ← not 'string'
|
|
945
|
-
PATHS.HOME === "/"; // false ← strict equality fails
|
|
1042
|
+
PATHS.USERS.EDIT.build({ id: 42 }); // '/users/42' (via String.prototype)
|
|
1043
|
+
PATHS.USERS.EDIT.paramNames; // ['id']
|
|
946
1044
|
```
|
|
947
1045
|
|
|
948
|
-
|
|
1046
|
+
Because route values are primitives, they work anywhere a plain string does — as object/`Map` keys, and directly with React Router's `<Link to={...}>` or `navigate()` (which branch on `typeof to === "string"`), no `.build()` call required for static paths.
|
|
1047
|
+
|
|
1048
|
+
The flip side: since `.build` and `.paramNames` live on `String.prototype`, **every** string in your app has them, not just routes. `"/foo".build({})` → `'/foo'`, and `"/a/:b".paramNames` → `['b']` — `.paramNames` is a lazy getter that parses the string's own text, so it's always correct. Just be aware the helpers exist globally when you're using the library.
|
|
949
1049
|
|
|
950
1050
|
### `useResolvedPath` vs. the library's own `buildPath`
|
|
951
1051
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as v,b as l,c as k,d as R,f as g,g as p,i as f,l as c,o as b}from"./chunk-NX4N6IWV.js";function h(t,e="",a=new Set){if(a.has(t))return[];a.add(t);let o=[];for(let r of Object.keys(t)){let n=e?`${e}.${r}`:r,i=t[r];typeof i=="string"?o.push({key:n,path:i}):i instanceof String?o.push({key:n,path:i.valueOf()}):typeof i=="object"&&i!==null&&o.push(...h(i,n,a))}return o}function $(t){let e=t.split("."),a=e[e.length-1]??t;return(a==="ROOT"&&e.length>1?e[e.length-2]:a).replace(/_/g," ").toLowerCase().replace(/^\w/,r=>r.toUpperCase())}function S(t,e,a){let o=Array.isArray(t)?t:h(t),r=e.split("?")[0]??"",n=a?.labelResolver??$,i=a?.labels??{},u=[];for(let s of o){let d=R(s.path),x=r.match(d);if(x){let y=f(s.path,x[0]),P=p(s.path)?c(s.path,y):s.path;u.push({key:s.key,resolvedPath:P,template:s.path,isCurrent:!0});continue}let w=k(s.path),T=r.match(w);if(T){let y=T[0],P=f(s.path,y),B=p(s.path)?c(s.path,P):s.path;u.push({key:s.key,resolvedPath:B,template:s.path,isCurrent:!1})}}let m=s=>s.split("/").filter(Boolean).length;return u.sort((s,d)=>m(s.template)-m(d.template)),u.map(s=>({key:s.key,label:i[s.key]??n(s.key),path:s.resolvedPath,isCurrent:s.isCurrent}))}var j=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function D(t,e){t.startsWith("/")||l(`[route-forge] Route "${e}" does not start with "/": "${t}".`),t.includes("*")&&!t.endsWith("/*")&&l(`[route-forge] Route "${e}" uses "*" outside a trailing "/*" splat; only a trailing splat is supported: "${t}".`)}function Q(t){let e=new Map,a=new Set,o=h(t);for(let r of o){let n=e.get(r.path);n===void 0?e.set(r.path,r.key):a.has(r.path)||(a.add(r.path),l(`[route-forge] Duplicate route path "${r.path}" for "${n}" and "${r.key}". Only one of them will be reachable.`))}for(let r=0;r<o.length;r++){let n=o[r];if(p(n.path))for(let i=r+1;i<o.length;i++){let u=o[i];if(!p(u.path)&&b(u.path,n.path,{exact:!0})){let m=`${n.key}->${u.key}`;a.has(m)||(a.add(m),l(`[route-forge] Route "${u.key}" ("${u.path}") is shadowed by dynamic route "${n.key}" ("${n.path}"). Place static routes before dynamic parameters in route trees.`))}}}}function C(){Object.prototype.hasOwnProperty.call(String.prototype,"build")||(Object.defineProperty(String.prototype,"build",{value:function(e,a,o){let r=this.valueOf();return p(r)?c(r,e??{},a,o):c(r,{},e,a)},writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(String.prototype,"buildRelative",{value:function(e,a,o){return this.build(e,a,o).replace(/^\/+/,"")||"."},writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(String.prototype,"paramNames",{get(){return g(this.valueOf())},enumerable:!1,configurable:!0}))}C();function O(t){let e={};for(let a in t){if(!Object.prototype.hasOwnProperty.call(t,a))continue;let o=t[a];typeof o=="string"?(D(o,a),e[a]=p(o)?o:o):j(o)&&(e[a]=O(o))}return e}function F(t){let e=O(t);return v()||Q(e),e}export{h as a,S as b,F as c};
|
|
2
|
+
//# sourceMappingURL=chunk-H5UZR7HM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/routes.ts","../src/core/defineRoutes.ts"],"sourcesContent":["import { matchPath, matchPrefix } from \"./pattern\";\nimport { extractParamsFromPath, isDynamic } from \"./params\";\nimport { buildPath } from \"./build\";\nimport type {\n BreadcrumbItem,\n BreadcrumbOptions,\n FlatRoute,\n} from \"../types\";\n\n/**\n * Walk a `defineRoutes` output tree and return a flat array of\n * `{ key, path }` entries where `key` is the dot-joined key path from\n * the root (e.g. `\"SERVICES.BCC.EDIT\"`) and `path` is the raw template\n * string (e.g. `\"/services/bcc/edit/:id\"`).\n *\n * Useful for:\n * - Generating sitemaps from a single source of truth.\n * - Detecting duplicate path strings across branches at startup:\n *\n * @example\n * const flat = flattenRoutes(PATHS);\n * const paths = flat.map((r) => r.path);\n * const dupes = paths.filter((p, i) => paths.indexOf(p) !== i);\n * if (dupes.length) console.warn('Duplicate paths:', dupes);\n */\nexport function flattenRoutes(\n routes: Record<string, unknown>,\n prefix = \"\",\n visited = new Set<Record<string, unknown>>(),\n): FlatRoute[] {\n if (visited.has(routes)) return [];\n visited.add(routes);\n\n const entries: FlatRoute[] = [];\n\n for (const key of Object.keys(routes)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n const value = routes[key];\n\n if (typeof value === \"string\") {\n // Plain static string leaf.\n entries.push({ key: fullKey, path: value });\n } else if (value instanceof String) {\n // String-object leaf (wrapped dynamic path from defineRoutes).\n entries.push({ key: fullKey, path: value.valueOf() });\n } else if (typeof value === \"object\" && value !== null) {\n // Nested route group — recurse.\n entries.push(...flattenRoutes(value as Record<string, unknown>, fullKey, visited));\n }\n // Anything else (functions, numbers, …) is silently skipped.\n }\n\n return entries;\n}\n\nfunction deriveBreadcrumbLabel(key: string): string {\n const parts = key.split(\".\");\n const last = parts[parts.length - 1] ?? key;\n // Use the parent segment when the leaf is the conventional \"ROOT\" key,\n // so USERS.ROOT → \"Users\" rather than \"Root\".\n const raw =\n last === \"ROOT\" && parts.length > 1 ? parts[parts.length - 2]! : last;\n return raw\n .replace(/_/g, \" \")\n .toLowerCase()\n .replace(/^\\w/, (c) => c.toUpperCase());\n}\n\n/**\n * Build a breadcrumb trail from a route tree or a flat route list.\n *\n * For a given `currentPath`, it walks the route tree and returns every route\n * that is an ancestor of (or an exact match to) the current page. Ancestors\n * are matched by prefix (e.g. `/users` matches `/users/edit/42/posts`).\n *\n * Dynamic params in ancestor paths are automatically resolved from the\n * matched portion of the URL.\n *\n * @param routes - A route tree (output of `defineRoutes`) or a pre-flattened\n * array from `flattenRoutes()`.\n * @param currentPath - The current URL (with or without query string).\n * @param options - Optional label resolver.\n * @returns An array of {@link BreadcrumbItem} ordered by depth\n * (most general first), where the last item is the current page.\n *\n * @example\n * ```ts\n * const PATHS = defineRoutes({\n * HOME: \"/\",\n * USERS: { ROOT: \"/users\", EDIT: \"/users/edit/:id\" },\n * } as const);\n *\n * getBreadcrumbs(PATHS, \"/users/edit/42\");\n * // → [\n * // { key: \"HOME\", label: \"Home\", path: \"/\", isCurrent: false },\n * // { key: \"USERS.ROOT\", label: \"Users\", path: \"/users\", isCurrent: false },\n * // { key: \"USERS.EDIT\", label: \"Edit\", path: \"/users/edit/42\", isCurrent: true },\n * // ]\n * ```\n */\nexport function getBreadcrumbs(\n routes: Record<string, unknown> | FlatRoute[],\n currentPath: string,\n options?: BreadcrumbOptions,\n): BreadcrumbItem[] {\n const flat = Array.isArray(routes) ? routes : flattenRoutes(routes);\n const pathname = currentPath.split(\"?\")[0] ?? \"\";\n const labelFn = options?.labelResolver ?? deriveBreadcrumbLabel;\n const labels = options?.labels ?? {};\n\n const items: Array<{\n key: string;\n resolvedPath: string;\n template: string;\n isCurrent: boolean;\n }> = [];\n\n for (const route of flat) {\n const exactRe = matchPath(route.path);\n const exactMatch = pathname.match(exactRe);\n\n if (exactMatch) {\n const params = extractParamsFromPath(route.path, exactMatch[0]);\n const resolved = isDynamic(route.path)\n ? buildPath(route.path, params)\n : route.path;\n items.push({\n key: route.key,\n resolvedPath: resolved,\n template: route.path,\n isCurrent: true,\n });\n continue;\n }\n\n const prefixRe = matchPrefix(route.path);\n const prefixMatch = pathname.match(prefixRe);\n\n if (prefixMatch) {\n const matchedPortion = prefixMatch[0];\n const params = extractParamsFromPath(route.path, matchedPortion);\n const resolved = isDynamic(route.path)\n ? buildPath(route.path, params)\n : route.path;\n items.push({\n key: route.key,\n resolvedPath: resolved,\n template: route.path,\n isCurrent: false,\n });\n }\n }\n\n // Sort by path depth (segment count), not raw string length — a shallow\n // route with a long param name (e.g. \"/shop/:reallyLongSlugName\") must\n // still sort before a deeper route with short segments (e.g.\n // \"/shop/widgets/details\"), even though the latter has fewer characters.\n const segmentCount = (t: string) => t.split(\"/\").filter(Boolean).length;\n items.sort((a, b) => segmentCount(a.template) - segmentCount(b.template));\n\n return items.map((item) => ({\n key: item.key,\n label: labels[item.key] ?? labelFn(item.key),\n path: item.resolvedPath,\n isCurrent: item.isCurrent,\n }));\n}\n","import { devWarn, isProduction } from \"./environment\";\nimport { buildPath } from \"./build\";\nimport { extractParamNames, isDynamic } from \"./params\";\nimport { isActivePath } from \"./match\";\nimport { flattenRoutes } from \"./routes\";\nimport type {\n BuildPathOptions,\n ExtractParams,\n PathParams,\n QueryParams,\n RoutePath,\n RouteTree,\n} from \"../types\";\n\n// Re-export so consumers that import from 'core/defineRoutes' get the full surface\nexport { buildPath } from \"./build\";\nexport { extractParamNames, isDynamic } from \"./params\";\n\n/**\n * A dynamic route is a template string with a `:param` or trailing `/*` splat,\n * augmented with a `.build()` helper and a `.paramNames` array.\n *\n * Exported so consumers (e.g. the hooks entry) can type against it.\n */\nexport type StaticRoute<T extends string> = T & {\n build(query?: QueryParams, options?: BuildPathOptions): RoutePath;\n buildRelative(query?: QueryParams, options?: BuildPathOptions): string;\n};\n\nexport type DynamicRoute<T extends string> = T extends\n | `${string}:${string}`\n | `${string}/*`\n ? T & {\n build(\n params: PathParams<T>,\n query?: QueryParams,\n options?: BuildPathOptions,\n ): RoutePath;\n buildRelative(\n params: PathParams<T>,\n query?: QueryParams,\n options?: BuildPathOptions,\n ): string;\n paramNames: Array<ExtractParams<T>>;\n }\n : StaticRoute<T>;\n\nexport type ResolvedRoutes<T extends RouteTree> = {\n [K in keyof T]: T[K] extends RouteTree\n ? ResolvedRoutes<T[K]>\n : T[K] extends string\n ? DynamicRoute<T[K]>\n : never;\n};\n\nconst isRouteGroup = (value: unknown): value is RouteTree =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype;\n\n/**\n * Validate a single route template and warn (dev-only) about common mistakes:\n * missing leading `/` and non-trailing `*` splats.\n */\nfunction validateTemplate(template: string, key: string): void {\n if (!template.startsWith(\"/\")) {\n devWarn(\n `[route-forge] Route \"${key}\" does not start with \"/\": \"${template}\".`,\n );\n }\n\n if (template.includes(\"*\") && !template.endsWith(\"/*\")) {\n devWarn(\n `[route-forge] Route \"${key}\" uses \"*\" outside a trailing \"/*\" splat; only a trailing splat is supported: \"${template}\".`,\n );\n }\n}\n\n/**\n * Warn (dev-only) when two routes resolve to the same path template or shadow each other.\n */\nfunction detectDuplicatePaths(routes: Record<string, unknown>): void {\n const seen = new Map<string, string>();\n const warned = new Set<string>();\n const flat = flattenRoutes(routes);\n\n for (const route of flat) {\n const existing = seen.get(route.path);\n if (existing === undefined) {\n seen.set(route.path, route.key);\n } else if (!warned.has(route.path)) {\n warned.add(route.path);\n devWarn(\n `[route-forge] Duplicate route path \"${route.path}\" for \"${existing}\" and \"${route.key}\". ` +\n `Only one of them will be reachable.`,\n );\n }\n }\n\n // Shadowing check: warn when a static path matches a dynamic path defined before it\n for (let i = 0; i < flat.length; i++) {\n const r1 = flat[i]!;\n if (!isDynamic(r1.path)) continue;\n\n for (let j = i + 1; j < flat.length; j++) {\n const r2 = flat[j]!;\n if (isDynamic(r2.path)) continue;\n\n if (isActivePath(r2.path, r1.path, { exact: true })) {\n const pairKey = `${r1.key}->${r2.key}`;\n if (!warned.has(pairKey)) {\n warned.add(pairKey);\n devWarn(\n `[route-forge] Route \"${r2.key}\" (\"${r2.path}\") is shadowed by dynamic route \"${r1.key}\" (\"${r1.path}\"). Place static routes before dynamic parameters in route trees.`,\n );\n }\n }\n }\n }\n}\n\n/**\n * Attach `.build()` (and, for dynamic templates, `.paramNames`) to\n * `String.prototype` exactly once, so route values can stay **genuine\n * primitive strings** instead of `new String(template)` objects.\n *\n * Route values used to be wrapped in `new String(template)` so `.build()`\n * could be attached as an own property. That silently broke direct use with\n * React Router's `<Link to={...}>` (and anything else that branches on\n * `typeof to === \"string\"`, e.g. React Router's internal `resolveTo()`):\n * `typeof` on a `String` object is `\"object\"`, not `\"string\"`, so React\n * Router treated the route value as a `Partial<Path>` and spread it\n * (`{ ...routeValue }`) instead of parsing it as a path — producing a\n * `pathname`-less destination and a broken/no-op navigation. `.build()`\n * happened to \"fix\" it only because it returns a plain string.\n *\n * Putting `.build()`/`.paramNames` on the prototype instead means every\n * primitive string route value can still call `.build()` / read\n * `.paramNames` (resolved lazily from `this`, the template text itself),\n * while `typeof route === \"string\"` stays true — so route values now work\n * directly anywhere a plain path string is expected, `<Link to={route}>`\n * included, with no `.build()` call required.\n */\nfunction installBuildProtocol(): void {\n if (Object.prototype.hasOwnProperty.call(String.prototype, \"build\")) {\n return;\n }\n\n Object.defineProperty(String.prototype, \"build\", {\n value: function build(\n this: string,\n paramsOrQuery?: PathParams<string> | QueryParams,\n query?: QueryParams,\n options?: BuildPathOptions,\n ): RoutePath {\n const template = this.valueOf();\n\n // Dynamic templates take (params, query?, options?); static templates\n // take (query?, options?) — disambiguated from the template itself,\n // since that's all the prototype method has to go on.\n return (\n isDynamic(template)\n ? buildPath(\n template,\n (paramsOrQuery ?? {}) as PathParams<string>,\n query,\n options,\n )\n : buildPath(\n template,\n {},\n paramsOrQuery as QueryParams,\n query as unknown as BuildPathOptions,\n )\n ) as RoutePath;\n },\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n Object.defineProperty(String.prototype, \"buildRelative\", {\n value: function buildRelative(\n this: string,\n paramsOrQuery?: PathParams<string> | QueryParams,\n query?: QueryParams,\n options?: BuildPathOptions,\n ): string {\n const absolutePath = (this as any).build(paramsOrQuery, query, options);\n return absolutePath.replace(/^\\/+/, \"\") || \".\";\n },\n writable: false,\n enumerable: false,\n configurable: true,\n });\n\n Object.defineProperty(String.prototype, \"paramNames\", {\n get(this: string): string[] {\n return extractParamNames(this.valueOf());\n },\n enumerable: false,\n configurable: true,\n });\n}\n\ninstallBuildProtocol();\n\nfunction wrapStaticPath<T extends string>(template: T): StaticRoute<T> {\n // A genuine primitive string — `.build()` comes from String.prototype\n // (see installBuildProtocol above), so `typeof` stays \"string\".\n return template as StaticRoute<T>;\n}\n\nfunction wrapDynamicPath<T extends string>(template: T): DynamicRoute<T> {\n // Same here: primitive string, `.build()` and `.paramNames` are resolved\n // lazily from String.prototype based on the template text itself.\n return template as DynamicRoute<T>;\n}\n\nfunction processRouteMap<T extends RouteTree>(routes: T): ResolvedRoutes<T> {\n const result = {} as ResolvedRoutes<T>;\n\n for (const key in routes) {\n if (!Object.prototype.hasOwnProperty.call(routes, key)) continue;\n\n const value = routes[key];\n\n if (typeof value === \"string\") {\n validateTemplate(value, key);\n result[key] = (\n isDynamic(value) ? wrapDynamicPath(value) : wrapStaticPath(value)\n ) as ResolvedRoutes<T>[typeof key];\n } else if (isRouteGroup(value)) {\n result[key] = processRouteMap(\n value,\n ) as ResolvedRoutes<T>[typeof key];\n }\n }\n\n return result;\n}\n\nexport function defineRoutes<T extends RouteTree>(\n routes: T,\n): ResolvedRoutes<T> {\n const result = processRouteMap(routes);\n // detectDuplicatePaths only ever produces console.warn output (suppressed\n // in production by devWarn), so skip the O(n^2) walk entirely in\n // production rather than computing it and discarding the result.\n if (!isProduction()) {\n detectDuplicatePaths(result as Record<string, unknown>);\n }\n return result;\n}\n"],"mappings":"gGAyBO,SAASA,EACdC,EACAC,EAAS,GACTC,EAAU,IAAI,IACD,CACb,GAAIA,EAAQ,IAAIF,CAAM,EAAG,MAAO,CAAC,EACjCE,EAAQ,IAAIF,CAAM,EAElB,IAAMG,EAAuB,CAAC,EAE9B,QAAWC,KAAO,OAAO,KAAKJ,CAAM,EAAG,CACrC,IAAMK,EAAUJ,EAAS,GAAGA,CAAM,IAAIG,CAAG,GAAKA,EACxCE,EAAQN,EAAOI,CAAG,EAEpB,OAAOE,GAAU,SAEnBH,EAAQ,KAAK,CAAE,IAAKE,EAAS,KAAMC,CAAM,CAAC,EACjCA,aAAiB,OAE1BH,EAAQ,KAAK,CAAE,IAAKE,EAAS,KAAMC,EAAM,QAAQ,CAAE,CAAC,EAC3C,OAAOA,GAAU,UAAYA,IAAU,MAEhDH,EAAQ,KAAK,GAAGJ,EAAcO,EAAkCD,EAASH,CAAO,CAAC,CAGrF,CAEA,OAAOC,CACT,CAEA,SAASI,EAAsBH,EAAqB,CAClD,IAAMI,EAAQJ,EAAI,MAAM,GAAG,EACrBK,EAAOD,EAAMA,EAAM,OAAS,CAAC,GAAKJ,EAKxC,OADEK,IAAS,QAAUD,EAAM,OAAS,EAAIA,EAAMA,EAAM,OAAS,CAAC,EAAKC,GAEhE,QAAQ,KAAM,GAAG,EACjB,YAAY,EACZ,QAAQ,MAAQC,GAAMA,EAAE,YAAY,CAAC,CAC1C,CAkCO,SAASC,EACdX,EACAY,EACAC,EACkB,CAClB,IAAMC,EAAO,MAAM,QAAQd,CAAM,EAAIA,EAASD,EAAcC,CAAM,EAC5De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AwBA,SAASM,GAA6B,CAChC,OAAO,UAAU,eAAe,KAAK,OAAO,UAAW,OAAO,IAIlE,OAAO,eAAe,OAAO,UAAW,QAAS,CAC/C,MAAO,SAELC,EACAC,EACAC,EACW,CACX,IAAMrB,EAAW,KAAK,QAAQ,EAK9B,OACEa,EAAUb,CAAQ,EACdsB,EACEtB,EACCmB,GAAiB,CAAC,EACnBC,EACAC,CACF,EACAC,EACEtB,EACA,CAAC,EACDmB,EACAC,CACF,CAER,EACA,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAED,OAAO,eAAe,OAAO,UAAW,gBAAiB,CACvD,MAAO,SAELD,EACAC,EACAC,EACQ,CAER,OADsB,KAAa,MAAMF,EAAeC,EAAOC,CAAO,EAClD,QAAQ,OAAQ,EAAE,GAAK,GAC7C,EACA,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAED,OAAO,eAAe,OAAO,UAAW,aAAc,CACpD,KAA4B,CAC1B,OAAOE,EAAkB,KAAK,QAAQ,CAAC,CACzC,EACA,WAAY,GACZ,aAAc,EAChB,CAAC,EACH,CAEAL,EAAqB,EAcrB,SAASM,EAAqCC,EAA8B,CAC1E,IAAMC,EAAS,CAAC,EAEhB,QAAWC,KAAOF,EAAQ,CACxB,GAAI,CAAC,OAAO,UAAU,eAAe,KAAKA,EAAQE,CAAG,EAAG,SAExD,IAAMC,EAAQH,EAAOE,CAAG,EAEpB,OAAOC,GAAU,UACnBC,EAAiBD,EAAOD,CAAG,EAC3BD,EAAOC,CAAG,EACRG,EAAUF,CAAK,EAAoBA,EAAwBA,GAEpDG,EAAaH,CAAK,IAC3BF,EAAOC,CAAG,EAAIH,EACZI,CACF,EAEJ,CAEA,OAAOF,CACT,CAEO,SAASM,EACdP,EACmB,CACnB,IAAMC,EAASF,EAAgBC,CAAM,EAIrC,OAAKQ,EAAa,GAChBC,EAAqBR,CAAiC,EAEjDA,CACT","names":["flattenRoutes","routes","prefix","visited","entries","key","fullKey","value","deriveBreadcrumbLabel","parts","last","c","getBreadcrumbs","currentPath","options","flat","pathname","labelFn","labels","items","route","exactRe","matchPath","exactMatch","params","extractParamsFromPath","resolved","isDynamic","buildPath","prefixRe","matchPrefix","prefixMatch","matchedPortion","segmentCount","t","a","b","item","isRouteGroup","value","validateTemplate","template","key","devWarn","detectDuplicatePaths","routes","seen","warned","flat","flattenRoutes","route","existing","i","r1","isDynamic","j","r2","isActivePath","pairKey","installBuildProtocol","paramsOrQuery","query","options","buildPath","extractParamNames","processRouteMap","routes","result","key","value","validateTemplate","isDynamic","isRouteGroup","defineRoutes","isProduction","detectDuplicatePaths"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function C(){return globalThis.process?.env?.NODE_ENV==="production"}function y(e){C()||console.warn(e)}var O=/[.*+?^${}()|[\]\\]/g,d=/(^|\/):([A-Za-z0-9_]+)(\?)?/g;function g(e){return e.replace(O,"\\$&")}function $(e){let t=e.endsWith("/*"),n=t?e.slice(0,-2):e,r="",s=0;for(let i of n.matchAll(d)){let c=i.index??0,u=i[0];r+=g(n.slice(s,c));let[,o="",,l]=i;r+=l?`(?:${g(o)}([^/]+))?`:`${g(o)}([^/]+)`,s=c+(u?.length??0)}return r+g(n.slice(s))+(t?"(?:/(.*))?":"")}function E(e,t){return new RegExp(`:${g(t)}\\?(?![A-Za-z0-9_])`).test(e)}var P=new Map,v=/^/;function b(e){if(e==="/")return v;let t=P.get(e);if(t!==void 0)return t;let n=new RegExp(`^${$(e)}(?=/|$)`);return P.set(e,n),n}function S(e){try{return decodeURIComponent(e)}catch{return e}}var R=new Map;function m(e,t){let n=t?.end??!0,r=t?.caseSensitive?"":"i",s=`${e}:${n}:${r}`,i=R.get(s);if(i!==void 0)return i;let c=$(e),u=n?`^${c}$`:`^${c}(?=/|$)`,o=new RegExp(u,r);return R.set(s,o),o}function T(){P.clear(),R.clear()}function h(e){let t=[...e.matchAll(d)].map(n=>n[2]);return e.endsWith("/*")&&t.push("*"),t}function W(e){return e.search(d)!==-1||e.endsWith("/*")}function j(e){return h(e)}function k(e,t){let n=t.split("?")[0]??"",r=h(e),s=n.match(m(e));if(!s)return{};let i={};return r.forEach((c,u)=>{let o=s[u+1];o!==void 0&&(i[c]=S(o))}),i}function w(e,t,n){let r=e.indexOf("#"),s=r===-1?e:e.slice(0,r),i=r===-1?"":e.slice(r+1),c=new URLSearchParams;if(t)for(let[l,a]of Object.entries(t))Object.prototype.hasOwnProperty.call(t,l)&&a!=null&&(Array.isArray(a)?a.forEach(f=>{f!=null&&c.append(l,String(f))}):c.append(l,String(a)));let u=s,o=c.toString();return o&&(u+=(u.includes("?")?"&":"?")+o),n?u+="#"+encodeURIComponent(n):i&&(u+="#"+i),u}function H(e,t){let n=e.indexOf("#"),r=n===-1?e:e.slice(0,n),s=r.indexOf("?");if(s===-1)return{};let i=new URLSearchParams(r.slice(s+1)),c={};for(let u of new Set(i.keys())){let l=i.getAll(u).map(a=>{if(t?.coerceBooleans){let f=String(a).toLowerCase();if(f==="true"||f==="false")return f==="true"}return t?.coerceNumbers&&a.trim()!==""&&!isNaN(Number(a))?Number(a):a});c[u]=l.length>1?l:l[0]??""}return c}function _(e,t,n,r){let s=h(e),i=s.filter(o=>(t[o]===void 0||t[o]===null)&&!E(e,o)&&o!=="*"),c=s.reduce((o,l)=>{let a=t[l],f=a==null;if(l==="*"){if(f)return o.replace(/\/\*$/,"")||"/";if(typeof a!="string"&&typeof a!="number")throw new TypeError(`Splat parameter must be string or number, got ${typeof a}`);let x=r?.encode===!1?String(a):String(a).split("/").map(p=>encodeURIComponent(p)).join("/");return o.replace(/\/\*$/,`/${x}`)}let A=new RegExp(`(^|/):${g(l)}\\??(?![A-Za-z0-9_])`,"g");return o.replace(A,(x,p)=>{if(f)return x.endsWith("?")?"":`${p}:${l}`;let N=r?.encode===!1?String(a):encodeURIComponent(String(a));return`${p}${N}`})},e);if(i.length>0){if(r?.strict)throw new RangeError(`[route-forge] Missing required param(s) ${i.map(o=>`":${o}"`).join(", ")} in template "${e}".`);y(`[route-forge] Unresolved params in path "${c}". Check that all :param segments have matching keys.`)}let u=r?.locale?Q(r.locale,c):c;return w(u,n,r?.hash)}function G(e,t,n,r){return _(e,t,n,r)}function Q(...e){return"/"+e.map(r=>r.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}function K(e,t,n={}){let r=n.exact??!0,s=n.caseSensitive??!1,i=(e.split("?")[0]??"").replace(/\/+$/,"")||"/",c=t.replace(/\/+$/,"")||"/",u=s?c:c.toLowerCase(),o=s?i:i.toLowerCase();return(r?m(u,{caseSensitive:s}):b(u)).test(o)}export{C as a,y as b,b as c,m as d,T as e,h as f,W as g,j as h,k as i,w as j,H as k,_ as l,G as m,Q as n,K as o};
|
|
2
|
+
//# sourceMappingURL=chunk-NX4N6IWV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/environment.ts","../src/core/pattern.ts","../src/core/params.ts","../src/core/query.ts","../src/core/build.ts","../src/core/match.ts"],"sourcesContent":["/**\n * Returns `true` when running in a production bundle (suppresses dev warnings).\n */\nexport function isProduction(): boolean {\n const runtimeProcess = (\n globalThis as typeof globalThis & {\n process?: { env?: Record<string, string | undefined> };\n }\n ).process;\n return runtimeProcess?.env?.NODE_ENV === \"production\";\n}\n\n/**\n * Emits a `console.warn` in non-production environments.\n * Shared by the core utilities and `defineRoutes()` so the production check\n * lives in one place.\n */\nexport function devWarn(message: string): void {\n if (!isProduction()) {\n console.warn(message);\n }\n}\n","/** Global RegExp instances — safe since String.prototype.replace/matchAll don't bleed lastIndex. */\nconst ESCAPE_RE = /[.*+?^${}()|[\\]\\\\]/g;\n\n/**\n * Matches a `:param` token that starts a URL segment.\n *\n * A param is only recognized when its `:` sits at the very start of the\n * template or is immediately preceded by `/`, so a literal colon inside a\n * segment (e.g. `/users/foo:bar`) is not treated as a param. Param names are\n * restricted to `[A-Za-z0-9_]` (matching React Router), so any static suffix\n * (e.g. `.json` in `/files/:name.json`) stays a literal. The optional `?`\n * marker (`:param?`) is captured separately so it can be handled as a\n * whole-segment modifier.\n */\nexport const PARAM_SEGMENT_RE = /(^|\\/):([A-Za-z0-9_]+)(\\?)?/g;\n\nexport function escapeRegex(value: string): string {\n return value.replace(ESCAPE_RE, \"\\\\$&\");\n}\n\n/**\n * Convert a route template into an unanchored `RegExp` source string.\n *\n * - Required `:name` segments become a capturing group `([^/]+)`.\n * - Optional `:name?` segments become `(?:([^/]+))?` — the whole segment is\n * optional, matching React Router semantics.\n * - A trailing splat (`/*`) becomes `(?:/(.*))?`, capturing the remainder of\n * the path (including slashes) or nothing at all.\n * - Everything else is regex-escaped literally.\n */\nfunction createTemplatePattern(template: string): string {\n const splat = template.endsWith(\"/*\");\n const base = splat ? template.slice(0, -2) : template;\n let pattern = \"\";\n let cursor = 0;\n\n for (const match of base.matchAll(PARAM_SEGMENT_RE)) {\n const start = match.index ?? 0;\n const token = match[0];\n\n pattern += escapeRegex(base.slice(cursor, start));\n\n const [, boundary = \"\", , optional] = match;\n pattern += optional\n ? `(?:${escapeRegex(boundary)}([^/]+))?`\n : `${escapeRegex(boundary)}([^/]+)`;\n\n cursor = start + (token?.length ?? 0);\n }\n\n return (\n pattern + escapeRegex(base.slice(cursor)) + (splat ? \"(?:/(.*))?\" : \"\")\n );\n}\n\n/** Returns `true` when `name` is an optional (`:name?`) param in `template`. */\nexport function isOptionalParam(template: string, name: string): boolean {\n return new RegExp(`:${escapeRegex(name)}\\\\?(?![A-Za-z0-9_])`).test(template);\n}\n\n/**\n * Returns a `RegExp` that matches `template` as a path prefix, honoring\n * segment boundaries (`/users` matches `/users/42` but not `/usersettings`).\n *\n * The root template `/` is a prefix of every path.\n *\n * Compiled patterns are cached per template: the resulting `RegExp` has no\n * `/g` flag, so repeated `.test()`/`.exec()` calls are side-effect free and\n * sharing instances across callers is safe.\n */\nconst PREFIX_CACHE = new Map<string, RegExp>();\nconst ROOT_PREFIX_RE = /^/;\n\nexport function matchPrefix(template: string): RegExp {\n if (template === \"/\") return ROOT_PREFIX_RE;\n const cached = PREFIX_CACHE.get(template);\n if (cached !== undefined) return cached;\n const re = new RegExp(`^${createTemplatePattern(template)}(?=/|$)`);\n PREFIX_CACHE.set(template, re);\n return re;\n}\n\n/** Decode a URL-encoded param value, falling back to the raw value on error. */\nexport function safeDecode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Convert a route template string into an anchored `RegExp` for matching paths.\n *\n * Each `:param` segment becomes a capturing group so the returned regex\n * can be used with `.test()` or `.exec()`.\n *\n * Query strings are **not** stripped — callers should split on `\"?\"` first\n * (see {@link isActivePath} or {@link extractParamsFromPath} for higher-level\n * helpers that handle this automatically).\n *\n * @param template - A route template, e.g. `\"/users/:id\"` or `\"/users/:id/posts/:postId\"`.\n * @returns A `RegExp` anchored with `^` and `$` that captures param values.\n *\n * @example\n * ```ts\n * const re = matchPath(\"/users/:id\");\n * re.test(\"/users/42\"); // true\n * re.exec(\"/users/42\"); // [\"/users/42\", \"42\"]\n * re.test(\"/users/42/posts\"); // false (exact match)\n * re.test(\"/users/42?page=1\"); // true (query is part of captured value)\n * ```\n *\n * Compiled patterns are cached per template (the regex has no `/g` flag, so\n * sharing instances across callers is safe).\n */\nconst PATH_CACHE = new Map<string, RegExp>();\n\nexport function matchPath(\n template: string,\n options?: { end?: boolean; caseSensitive?: boolean },\n): RegExp {\n const end = options?.end ?? true;\n const flags = options?.caseSensitive ? \"\" : \"i\";\n const cacheKey = `${template}:${end}:${flags}`;\n\n const cached = PATH_CACHE.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const basePattern = createTemplatePattern(template);\n const pattern = end ? `^${basePattern}$` : `^${basePattern}(?=/|$)`;\n const re = new RegExp(pattern, flags);\n PATH_CACHE.set(cacheKey, re);\n return re;\n}\n\n/**\n * Clears internal regex cache maps (PREFIX_CACHE and PATH_CACHE).\n * Useful in test suites to prevent cached patterns from leaking across test cases.\n */\nexport function clearPathCache(): void {\n PREFIX_CACHE.clear();\n PATH_CACHE.clear();\n}\n","import { PARAM_SEGMENT_RE, matchPath, safeDecode } from \"./pattern\";\n\n/**\n * Extract the `:param` names from a route template.\n *\n * A param is only recognized at the start of a segment (see\n * {@link PARAM_SEGMENT_RE}), so literal colons (`/users/foo:bar`) and static\n * suffixes after a param (`/files/:name.json`) are not treated as params.\n * A trailing splat (`/*`) is reported as the `\"*\"` name.\n */\nexport function extractParamNames(template: string): string[] {\n const names = [...template.matchAll(PARAM_SEGMENT_RE)].map(\n (match) => match[2] as string,\n );\n if (template.endsWith(\"/*\")) names.push(\"*\");\n return names;\n}\n\n/** Returns `true` when the template contains a `:param` or trailing `/*` splat. */\nexport function isDynamic(path: string): boolean {\n return path.search(PARAM_SEGMENT_RE) !== -1 || path.endsWith(\"/*\");\n}\n\n/**\n * Alias of {@link extractParamNames} — kept for backwards compatibility.\n */\nexport function getParamNames(template: string): string[] {\n return extractParamNames(template);\n}\n\n/**\n * Extract the param values matched by `template` from a resolved path.\n *\n * The query string is stripped before matching, so `/users/42?tab=profile`\n * still yields `{ id: \"42\" }`. Values are URL-decoded back to their original\n * form; a non-matching path yields an empty object.\n */\nexport function extractParamsFromPath(\n template: string,\n resolvedPath: string,\n): Record<string, string> {\n const pathWithoutSearch = resolvedPath.split(\"?\")[0] ?? \"\";\n const paramNames = extractParamNames(template);\n const match = pathWithoutSearch.match(matchPath(template));\n\n if (!match) return {};\n\n const result: Record<string, string> = {};\n paramNames.forEach((name, index) => {\n const raw = match[index + 1];\n if (raw !== undefined) result[name] = safeDecode(raw);\n });\n return result;\n}\n","import type { QueryParams } from \"../types\";\n\n/**\n * Append a query string and/or hash fragment to a path that may already\n * contain a query or hash.\n *\n * - Existing query pairs are preserved; new ones are joined with `&`.\n * - The query string is always inserted before any hash fragment, so an\n * existing `#section` on `path` is kept unless a new `hash` is given.\n *\n * @example\n * ```ts\n * appendQuery(\"/users?tab=list\", { page: 2 }); // → \"/users?tab=list&page=2\"\n * appendQuery(\"/users#top\", { tab: \"list\" }); // → \"/users?tab=list#top\"\n * ```\n */\nexport function appendQuery(\n path: string,\n query?: QueryParams,\n hash?: string,\n): string {\n const hashIdx = path.indexOf(\"#\");\n const base = hashIdx === -1 ? path : path.slice(0, hashIdx);\n const existingHash = hashIdx === -1 ? \"\" : path.slice(hashIdx + 1);\n\n const searchParams = new URLSearchParams();\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (!Object.prototype.hasOwnProperty.call(query, key)) continue;\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n value.forEach((v) => {\n if (v !== undefined && v !== null)\n searchParams.append(key, String(v));\n });\n } else {\n searchParams.append(key, String(value));\n }\n }\n }\n\n let result = base;\n const queryString = searchParams.toString();\n if (queryString) {\n result += (result.includes(\"?\") ? \"&\" : \"?\") + queryString;\n }\n\n if (hash) {\n result += \"#\" + encodeURIComponent(hash);\n } else if (existingHash) {\n result += \"#\" + existingHash;\n }\n\n return result;\n}\n\n/**\n * Parse the query string out of a path (or bare query string) into a plain\n * object. Repeated keys become arrays; a single key is a scalar string.\n *\n * With `{ coerceBooleans: true }`, the strings `\"true\"`/`\"false\"` are\n * converted to actual booleans.\n *\n * @example\n * ```ts\n * extractQueryFromPath(\"/users/42?tab=profile&tag=a&tag=b\");\n * // → { tab: \"profile\", tag: [\"a\", \"b\"] }\n * extractQueryFromPath(\"/search?active=true\", { coerceBooleans: true });\n * // → { active: true }\n * ```\n */\nexport function extractQueryFromPath(\n path: string,\n options?: { coerceBooleans?: boolean; coerceNumbers?: boolean },\n): QueryParams {\n const hashIdx = path.indexOf(\"#\");\n const noHash = hashIdx === -1 ? path : path.slice(0, hashIdx);\n const queryIdx = noHash.indexOf(\"?\");\n if (queryIdx === -1) return {};\n\n const params = new URLSearchParams(noHash.slice(queryIdx + 1));\n const result: QueryParams = {};\n\n for (const key of new Set(params.keys())) {\n const values = params.getAll(key);\n const parsed = values.map((v) => {\n if (options?.coerceBooleans) {\n const lower = String(v).toLowerCase();\n if (lower === \"true\" || lower === \"false\") {\n return lower === \"true\";\n }\n }\n if (options?.coerceNumbers && v.trim() !== \"\" && !isNaN(Number(v))) {\n return Number(v);\n }\n return v;\n });\n result[key] = parsed.length > 1 ? parsed : (parsed[0] ?? \"\");\n }\n\n return result;\n}\n","import { escapeRegex, isOptionalParam } from \"./pattern\";\nimport { extractParamNames } from \"./params\";\nimport { appendQuery } from \"./query\";\nimport { devWarn } from \"./environment\";\nimport type { BuildPathOptions, QueryParams, RouteParams } from \"../types\";\n\n/**\n * Resolve a route template against a params object, appending an optional\n * query string and hash fragment.\n *\n * Missing required params are left as their `:name` placeholder and a\n * `console.warn` is emitted — pass `{ strict: true }` to throw a `RangeError`\n * instead. Optional (`:param?`) segments are dropped entirely when missing;\n * a missing splat just drops the trailing `/*`. Values are URL-encoded by\n * default (`{ encode: false }` opts out).\n */\nexport function buildPath(\n template: string,\n params: RouteParams,\n query?: QueryParams,\n options?: BuildPathOptions,\n): string {\n const paramNames = extractParamNames(template);\n const unresolved = paramNames.filter(\n (name) =>\n (params[name] === undefined || params[name] === null) &&\n !isOptionalParam(template, name) &&\n // A missing splat simply drops the `/*` suffix (matching React Router,\n // where `/files/*` also matches `/files`).\n name !== \"*\",\n );\n\n const resolved = paramNames.reduce((path, name) => {\n const value = params[name];\n const missing = value === undefined || value === null;\n\n if (name === \"*\") {\n if (missing) return path.replace(/\\/\\*$/, \"\") || \"/\";\n\n if (typeof value !== 'string' && typeof value !== 'number') {\n throw new TypeError(\n `Splat parameter must be string or number, got ${typeof value}`\n );\n }\n\n // Splat values are path-like: preserve `/` separators but still\n // encode characters that could break the URL (`?`, `#`, spaces, …).\n const encoded =\n options?.encode === false\n ? String(value)\n : String(value)\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n return path.replace(/\\/\\*$/, `/${encoded}`);\n }\n\n const re = new RegExp(\n `(^|/):${escapeRegex(name)}\\\\??(?![A-Za-z0-9_])`,\n \"g\",\n );\n\n return path.replace(re, (match, boundary) => {\n if (missing) {\n // Optional segment: drop the whole `/segment`. Required: keep the\n // `:name` placeholder so strict mode can report it.\n return match.endsWith(\"?\") ? \"\" : `${boundary}:${name}`;\n }\n\n const encoded =\n options?.encode === false\n ? String(value)\n : encodeURIComponent(String(value));\n return `${boundary}${encoded}`;\n });\n }, template);\n\n if (unresolved.length > 0) {\n if (options?.strict) {\n throw new RangeError(\n `[route-forge] Missing required param(s) ${unresolved.map((p) => `\":${p}\"`).join(\", \")} in template \"${template}\".`,\n );\n }\n\n devWarn(\n `[route-forge] Unresolved params in path \"${resolved}\". ` +\n `Check that all :param segments have matching keys.`,\n );\n }\n\n const finalPath = options?.locale\n ? joinPaths(options.locale, resolved)\n : resolved;\n\n return appendQuery(finalPath, query, options?.hash);\n}\n\n/**\n * Standalone alias of {@link buildPath} — resolves a template against params.\n */\nexport function build(\n template: string,\n params: RouteParams,\n query?: QueryParams,\n options?: BuildPathOptions,\n): string {\n return buildPath(template, params, query, options);\n}\n\n/**\n * Join URL path segments into a single slash-prefixed path, normalising\n * duplicate slashes.\n *\n * @example\n * joinPaths(\"/api/\", \"/v1/\", \"users\"); // → \"/api/v1/users\"\n */\nexport function joinPaths(...segments: string[]): string {\n const processed = segments.map((segment) =>\n segment.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\"),\n );\n const filtered = processed.filter(Boolean);\n return \"/\" + filtered.join(\"/\");\n}\n","import { matchPath, matchPrefix } from \"./pattern\";\n\n/**\n * Test whether `currentPath` matches `template`, mirroring React Router's\n * `NavLink` matching semantics:\n *\n * - Case-insensitive by default (pass `caseSensitive: true` to opt out).\n * - Trailing slashes are tolerated (`/users/` matches `/users`).\n * - `exact: true` (the default) requires a full match; `exact: false`\n * matches any path that starts with the template.\n */\nexport function isActivePath(\n currentPath: string,\n template: string,\n options: { exact?: boolean; caseSensitive?: boolean } = {},\n): boolean {\n // NOTE: default each property individually rather than relying on a\n // default *object* for `options` — JS default parameters only apply when\n // the whole argument is omitted, so `isActivePath(a, b, { caseSensitive: true })`\n // would otherwise silently lose the documented `exact: true` default.\n const exact = options.exact ?? true;\n const caseSensitive = options.caseSensitive ?? false;\n\n const pathname = (currentPath.split(\"?\")[0] ?? \"\").replace(/\\/+$/, \"\") || \"/\";\n const normalizedTemplate = template.replace(/\\/+$/, \"\") || \"/\";\n const target = caseSensitive\n ? normalizedTemplate\n : normalizedTemplate.toLowerCase();\n const candidate = caseSensitive ? pathname : pathname.toLowerCase();\n const regex = exact\n ? matchPath(target, { caseSensitive })\n : matchPrefix(target);\n\n return regex.test(candidate);\n}\n"],"mappings":"AAGO,SAASA,GAAwB,CAMtC,OAJE,WAGA,SACqB,KAAK,WAAa,YAC3C,CAOO,SAASC,EAAQC,EAAuB,CACxCF,EAAa,GAChB,QAAQ,KAAKE,CAAO,CAExB,CCpBA,IAAMC,EAAY,sBAaLC,EAAmB,+BAEzB,SAASC,EAAYC,EAAuB,CACjD,OAAOA,EAAM,QAAQH,EAAW,MAAM,CACxC,CAYA,SAASI,EAAsBC,EAA0B,CACvD,IAAMC,EAAQD,EAAS,SAAS,IAAI,EAC9BE,EAAOD,EAAQD,EAAS,MAAM,EAAG,EAAE,EAAIA,EACzCG,EAAU,GACVC,EAAS,EAEb,QAAWC,KAASH,EAAK,SAASN,CAAgB,EAAG,CACnD,IAAMU,EAAQD,EAAM,OAAS,EACvBE,EAAQF,EAAM,CAAC,EAErBF,GAAWN,EAAYK,EAAK,MAAME,EAAQE,CAAK,CAAC,EAEhD,GAAM,CAAC,CAAEE,EAAW,GAAI,CAAEC,CAAQ,EAAIJ,EACtCF,GAAWM,EACP,MAAMZ,EAAYW,CAAQ,CAAC,YAC3B,GAAGX,EAAYW,CAAQ,CAAC,UAE5BJ,EAASE,GAASC,GAAO,QAAU,EACrC,CAEA,OACEJ,EAAUN,EAAYK,EAAK,MAAME,CAAM,CAAC,GAAKH,EAAQ,aAAe,GAExE,CAGO,SAASS,EAAgBV,EAAkBW,EAAuB,CACvE,OAAO,IAAI,OAAO,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BE,EAAgBF,EAAQ,eAAiB,GAEzCG,GAAYL,EAAY,MAAM,GAAG,EAAE,CAAC,GAAK,IAAI,QAAQ,OAAQ,EAAE,GAAK,IACpEM,EAAqBL,EAAS,QAAQ,OAAQ,EAAE,GAAK,IACrDM,EAASH,EACXE,EACAA,EAAmB,YAAY,EAC7BE,EAAYJ,EAAgBC,EAAWA,EAAS,YAAY,EAKlE,OAJcF,EACVM,EAAUF,EAAQ,CAAE,cAAAH,CAAc,CAAC,EACnCM,EAAYH,CAAM,GAET,KAAKC,CAAS,CAC7B","names":["isProduction","devWarn","message","ESCAPE_RE","PARAM_SEGMENT_RE","escapeRegex","value","createTemplatePattern","template","splat","base","pattern","cursor","match","start","token","boundary","optional","isOptionalParam","name","PREFIX_CACHE","ROOT_PREFIX_RE","matchPrefix","cached","re","safeDecode","PATH_CACHE","matchPath","options","end","flags","cacheKey","basePattern","clearPathCache","extractParamNames","template","names","PARAM_SEGMENT_RE","match","isDynamic","path","getParamNames","extractParamsFromPath","resolvedPath","pathWithoutSearch","paramNames","matchPath","result","name","index","raw","safeDecode","appendQuery","path","query","hash","hashIdx","base","existingHash","searchParams","key","value","v","result","queryString","extractQueryFromPath","options","noHash","queryIdx","params","parsed","lower","buildPath","template","params","query","options","paramNames","extractParamNames","unresolved","name","isOptionalParam","resolved","path","value","missing","encoded","segment","re","escapeRegex","match","boundary","p","devWarn","finalPath","joinPaths","appendQuery","build","segments","isActivePath","currentPath","template","options","exact","caseSensitive","pathname","normalizedTemplate","target","candidate","matchPath","matchPrefix"]}
|
package/dist/hooks/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var D=(e,r)=>{for(var t in r)y(e,t,{get:r[t],enumerable:!0})},q=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of H(r))!z.call(e,o)&&o!==t&&y(e,o,{get:()=>r[o],enumerable:!(n=F(r,o))||n.enumerable});return e};var Z=e=>q(y({},"__esModule",{value:!0}),e);var J={};D(J,{useActivePath:()=>M,useNavigateTo:()=>S,useResolvedPath:()=>I,useRouteParams:()=>w,useTypedSearchParams:()=>U});module.exports=Z(J);var R=require("react-router");function w(e){if(typeof window>"u")throw new Error("useRouteParams can only be used in browser environment. Call this hook only in client components or after hydration.");return(0,R.useParams)()}var E=require("react"),$=require("react-router");function S(){if(typeof window>"u")throw new Error("useNavigateTo can only be used in browser environment. Call this hook only in client components or after hydration.");let e=(0,$.useNavigate)();return(0,E.useCallback)((r,t)=>{e(String(r),t)},[e])}var G=/[.*+?^${}()|[\]\\]/g,x=/(^|\/):([A-Za-z0-9_]+)(\?)?/g;function p(e){return e.replace(G,"\\$&")}function N(e){let r=e.endsWith("/*"),t=r?e.slice(0,-2):e,n="",o=0;for(let i of t.matchAll(x)){let c=i.index??0,u=i[0];n+=p(t.slice(o,c));let[,s="",,l]=i;n+=l?`(?:${p(s)}([^/]+))?`:`${p(s)}([^/]+)`,o=c+(u?.length??0)}return n+p(t.slice(o))+(r?"(?:/(.*))?":"")}function O(e,r){return new RegExp(`:${p(r)}\\?(?![A-Za-z0-9_])`).test(e)}var v=new Map,X=/^/;function C(e){if(e==="/")return X;let r=v.get(e);if(r!==void 0)return r;let t=new RegExp(`^${N(e)}(?=/|$)`);return v.set(e,t),t}var A=new Map;function b(e,r){let t=r?.end??!0,n=r?.caseSensitive?"":"i",o=`${e}:${t}:${n}`,i=A.get(o);if(i!==void 0)return i;let c=N(e),u=t?`^${c}$`:`^${c}(?=/|$)`,s=new RegExp(u,n);return A.set(o,s),s}function T(e){let r=[...e.matchAll(x)].map(t=>t[2]);return e.endsWith("/*")&&r.push("*"),r}function Q(e,r,t){let n=e.indexOf("#"),o=n===-1?e:e.slice(0,n),i=n===-1?"":e.slice(n+1),c=new URLSearchParams;if(r)for(let[l,a]of Object.entries(r))Object.prototype.hasOwnProperty.call(r,l)&&a!=null&&(Array.isArray(a)?a.forEach(f=>{f!=null&&c.append(l,String(f))}):c.append(l,String(a)));let u=o,s=c.toString();return s&&(u+=(u.includes("?")?"&":"?")+s),t?u+="#"+encodeURIComponent(t):i&&(u+="#"+i),u}function _(e,r){let t=e.indexOf("#"),n=t===-1?e:e.slice(0,t),o=n.indexOf("?");if(o===-1)return{};let i=new URLSearchParams(n.slice(o+1)),c={};for(let u of new Set(i.keys())){let l=i.getAll(u).map(a=>{if(r?.coerceBooleans){let f=String(a).toLowerCase();if(f==="true"||f==="false")return f==="true"}return r?.coerceNumbers&&a.trim()!==""&&!isNaN(Number(a))?Number(a):a});c[u]=l.length>1?l:l[0]??""}return c}function K(){return globalThis.process?.env?.NODE_ENV==="production"}function k(e){K()||console.warn(e)}function B(e,r,t,n){let o=T(e),i=o.filter(s=>(r[s]===void 0||r[s]===null)&&!O(e,s)&&s!=="*"),c=o.reduce((s,l)=>{let a=r[l],f=a==null;if(l==="*"){if(f)return s.replace(/\/\*$/,"")||"/";if(typeof a!="string"&&typeof a!="number")throw new TypeError(`Splat parameter must be string or number, got ${typeof a}`);let P=n?.encode===!1?String(a):String(a).split("/").map(d=>encodeURIComponent(d)).join("/");return s.replace(/\/\*$/,`/${P}`)}let m=new RegExp(`(^|/):${p(l)}\\??(?![A-Za-z0-9_])`,"g");return s.replace(m,(P,d)=>{if(f)return P.endsWith("?")?"":`${d}:${l}`;let W=n?.encode===!1?String(a):encodeURIComponent(String(a));return`${d}${W}`})},e);if(i.length>0){if(n?.strict)throw new RangeError(`[route-forge] Missing required param(s) ${i.map(s=>`":${s}"`).join(", ")} in template "${e}".`);k(`[route-forge] Unresolved params in path "${c}". Check that all :param segments have matching keys.`)}let u=n?.locale?V(n.locale,c):c;return Q(u,t,n?.hash)}function V(...e){return"/"+e.map(n=>n.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}function I(e,r,t,n){if(typeof window>"u")throw new Error("useResolvedPath can only be used in browser environment. Call this hook only in client components or after hydration.");return B(e,r,t,n)}var L=require("react-router");function j(e,r,t={}){let n=t.exact??!0,o=t.caseSensitive??!1,i=(e.split("?")[0]??"").replace(/\/+$/,"")||"/",c=r.replace(/\/+$/,"")||"/",u=o?c:c.toLowerCase(),s=o?i:i.toLowerCase();return(n?b(u,{caseSensitive:o}):C(u)).test(s)}function M(e,r={}){if(typeof window>"u")throw new Error("useActivePath can only be used in browser environment. Call this hook only in client components or after hydration.");let t=(0,L.useLocation)();return j(t.pathname,e,r)}var g=require("react"),h=require("react-router");function U(e){if(typeof window>"u")throw new Error("useTypedSearchParams can only be used in browser environment. Call this hook only in client components or after hydration.");let r=(0,h.useLocation)(),t=(0,h.useNavigate)(),n=(0,g.useMemo)(()=>_(r.search,e),[r.search,e]),o=(0,g.useCallback)((i,c)=>{let u=new URLSearchParams;Object.entries(i).forEach(([a,f])=>{Object.prototype.hasOwnProperty.call(i,a)&&f!=null&&(Array.isArray(f)?f.forEach(m=>{m!=null&&u.append(a,String(m))}):u.append(a,String(f)))});let s=u.toString();t(`${s?"?":""}${s}${r.hash}`,c)},[t,r.hash]);return[n,o]}0&&(module.exports={useActivePath,useNavigateTo,useResolvedPath,useRouteParams,useTypedSearchParams});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|