@mpen/rerouter 0.1.7 → 0.3.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 (59) hide show
  1. package/README.md +76 -18
  2. package/dist/bin.d.ts +29 -0
  3. package/dist/bin.js +228 -0
  4. package/dist/hooks-Dlwcb0sV.js +20 -0
  5. package/dist/hooks.d.ts +2 -0
  6. package/dist/hooks.js +2 -0
  7. package/dist/index-BYXpNitc.d.ts +5 -0
  8. package/dist/index.d.ts +265 -0
  9. package/dist/index.js +139 -0
  10. package/dist/routes-Hpf6cwcZ.js +135 -0
  11. package/examples/App.tsx +111 -0
  12. package/examples/index.html +67 -0
  13. package/examples/pages/BlogPost.tsx +17 -0
  14. package/examples/pages/FetchLoading.tsx +53 -0
  15. package/examples/pages/FetchLoadingItem.tsx +45 -0
  16. package/examples/pages/Home.tsx +3 -0
  17. package/examples/pages/KitchenSink.tsx +23 -0
  18. package/examples/pages/Login.tsx +3 -0
  19. package/examples/pages/Match.tsx +5 -0
  20. package/examples/pages/NotFound.tsx +3 -0
  21. package/examples/pages/SlowLoading.tsx +8 -0
  22. package/examples/routes.gen.ts +125 -0
  23. package/examples/routes.ts +40 -0
  24. package/package.json +37 -32
  25. package/src/bin.test.ts +199 -0
  26. package/src/bin.ts +333 -0
  27. package/src/components/Link.test.tsx +139 -0
  28. package/src/components/Link.tsx +87 -0
  29. package/src/components/NavLink.test.tsx +119 -0
  30. package/src/components/NavLink.tsx +71 -0
  31. package/src/components/Router.tsx +75 -0
  32. package/src/fixtures/bin/kitchen-sink.tsx +15 -0
  33. package/src/fixtures/bin/optional.tsx +3 -0
  34. package/src/fixtures/bin/pages/Home.tsx +3 -0
  35. package/src/fixtures/bin/pages/KitchenSink.tsx +3 -0
  36. package/src/fixtures/bin/pages/Login.tsx +3 -0
  37. package/src/fixtures/bin/pages/Match.tsx +3 -0
  38. package/src/fixtures/bin/pages/NotFound.tsx +3 -0
  39. package/src/fixtures/bin/pages/Optional.tsx +3 -0
  40. package/src/fixtures/bin/regexp-groups.tsx +11 -0
  41. package/src/fixtures/bin/simple.tsx +1 -0
  42. package/src/fixtures/bin/unnamed.tsx +4 -0
  43. package/src/hooks/index.ts +1 -0
  44. package/src/hooks/useUrl.ts +22 -0
  45. package/src/index.ts +6 -0
  46. package/src/lib/mergeSearch.test.ts +37 -0
  47. package/src/lib/mergeSearch.ts +21 -0
  48. package/src/lib/routes.test.ts +67 -0
  49. package/src/lib/routes.ts +245 -0
  50. package/src/lib/url.ts +9 -0
  51. package/tsconfig.json +9 -0
  52. package/tsdown.config.ts +22 -0
  53. package/LICENSE +0 -21
  54. package/dist/bundle.cjs +0 -406
  55. package/dist/bundle.d.ts +0 -2
  56. package/dist/bundle.mjs +0 -404
  57. package/dist/dev.d.ts +0 -1
  58. package/dist/log.d.ts +0 -1
  59. package/dist/uri-template.d.ts +0 -50
@@ -0,0 +1,71 @@
1
+ import { cc, type ClassValue } from '@mpen/classcat'
2
+ import type { Override } from '@mpen/ts-types'
3
+ import { useUrlPath } from '../hooks/useUrl'
4
+ import { Link, type LinkProps } from './Link'
5
+
6
+ export type NavLinkMatch = 'exact' | 'prefix'
7
+
8
+ /**
9
+ * Props for [`NavLink`]{@link NavLink}.
10
+ */
11
+ export type NavLinkProps = Override<
12
+ LinkProps,
13
+ {
14
+ /**
15
+ * Classes to apply when the link target matches the current path.
16
+ */
17
+ activeClass?: ClassValue
18
+
19
+ /**
20
+ * Classes to apply when the link target does not match the current path.
21
+ */
22
+ inactiveClass?: ClassValue
23
+
24
+ /**
25
+ * How to compare the link target to the current path.
26
+ *
27
+ * @defaultValue `'exact'`
28
+ */
29
+ match?: NavLinkMatch
30
+ }
31
+ >
32
+
33
+ function isActivePath(pathname: string, targetPathname: string, match: NavLinkMatch): boolean {
34
+ if (pathname === targetPathname) return true
35
+ if (match === 'exact') return false
36
+ if (targetPathname === '/') return false
37
+ return pathname.startsWith(`${targetPathname}/`)
38
+ }
39
+
40
+ /**
41
+ * Renders a [`Link`]{@link Link} with classes selected from the current route.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * <NavLink
46
+ * activeClass={['pill', 'active']}
47
+ * inactiveClass={['pill', { muted: true }]}
48
+ * to="/settings"
49
+ * >
50
+ * Settings
51
+ * </NavLink>
52
+ * ```
53
+ *
54
+ * @param props - Link props plus active and inactive class values.
55
+ * @returns An anchor element that navigates through rerouter.
56
+ */
57
+ export function NavLink({
58
+ activeClass,
59
+ className,
60
+ inactiveClass,
61
+ match = 'exact',
62
+ to,
63
+ ...props
64
+ }: NavLinkProps) {
65
+ const pathname = useUrlPath()
66
+ const target = new URL(to, window.location.href)
67
+ const active = isActivePath(pathname, target.pathname, match)
68
+ const linkClassName = cc(className, active ? activeClass : inactiveClass)
69
+
70
+ return <Link {...props} className={linkClassName || undefined} to={to} />
71
+ }
@@ -0,0 +1,75 @@
1
+ import { lazy, Suspense, useMemo, type ReactNode } from 'react'
2
+ import { useUrlPath } from '../hooks'
3
+ import { normalizeRoutes, type Route } from '../lib/routes'
4
+
5
+ type LazyRouteComponent = ReturnType<typeof lazy>
6
+
7
+ const lazyRouteComponents = new WeakMap<Route['component'], LazyRouteComponent>()
8
+
9
+ function getLazyRouteComponent(component: Route['component']): LazyRouteComponent {
10
+ let LazyComponent = lazyRouteComponents.get(component)
11
+ if (!LazyComponent) {
12
+ LazyComponent = lazy(component)
13
+ lazyRouteComponents.set(component, LazyComponent)
14
+ }
15
+ return LazyComponent
16
+ }
17
+
18
+ /**
19
+ * Props for [`Router`]{@link Router}.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * <Router routes={routes} loading={<div>Loading...</div>} />
24
+ * ```
25
+ */
26
+ export interface RouterProps {
27
+ /**
28
+ * Route definitions to match against the current URL pathname.
29
+ */
30
+ routes: readonly Route[]
31
+ /**
32
+ * Optional fallback rendered while a matched route component module is loading.
33
+ */
34
+ loading?: ReactNode
35
+ }
36
+
37
+ /**
38
+ * Renders the first route that matches the current URL pathname.
39
+ *
40
+ * @param props - The router props.
41
+ * @returns The matched lazy route component, the loading fallback, or `null`.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * import routes from './routes'
46
+ *
47
+ * function App() {
48
+ * return <Router routes={routes} loading={<div>Loading...</div>} />
49
+ * }
50
+ * ```
51
+ */
52
+ export function Router({ routes, loading = null }: RouterProps) {
53
+ const pathname = useUrlPath()
54
+
55
+ const normalizedRoutes = useMemo(
56
+ () =>
57
+ normalizeRoutes(routes).map((route) => ({
58
+ ...route,
59
+ Component: getLazyRouteComponent(route.component),
60
+ })),
61
+ [routes],
62
+ )
63
+
64
+ for (const { matches, Component } of normalizedRoutes) {
65
+ const params = matches(pathname)
66
+ if (!params) continue
67
+ return (
68
+ <Suspense fallback={loading}>
69
+ <Component {...(params as any)} />
70
+ </Suspense>
71
+ )
72
+ }
73
+
74
+ return null
75
+ }
@@ -0,0 +1,15 @@
1
+ import type { RouteObject } from '@mpen/rerouter'
2
+
3
+ const ROUTES: readonly RouteObject[] = [
4
+ { name: 'home', pattern: '/', component: () => import('./pages/Home') },
5
+ {
6
+ name: 'kitchenSink',
7
+ pattern: '/hello/:foo/bar/:baz/*splat/xxx{/:optional/lol/:two}',
8
+ component: () => import('./pages/KitchenSink'),
9
+ },
10
+ { name: 'login', pattern: '/login', component: () => import('./pages/Login') },
11
+ { name: 'match', pattern: '/matches/:id', component: () => import('./pages/Match') },
12
+ { name: 'notFound', pattern: '*', component: () => import('./pages/NotFound') },
13
+ ]
14
+
15
+ export default ROUTES
@@ -0,0 +1,3 @@
1
+ export default [
2
+ { name: 'optional', pattern: '/foo{/:bar}', component: () => import('./pages/Optional') },
3
+ ]
@@ -0,0 +1,3 @@
1
+ export default function Home() {
2
+ return null
3
+ }
@@ -0,0 +1,3 @@
1
+ export default function KitchenSink() {
2
+ return null
3
+ }
@@ -0,0 +1,3 @@
1
+ export default function Login() {
2
+ return null
3
+ }
@@ -0,0 +1,3 @@
1
+ export default function Match() {
2
+ return null
3
+ }
@@ -0,0 +1,3 @@
1
+ export default function NotFound() {
2
+ return null
3
+ }
@@ -0,0 +1,3 @@
1
+ export default function Optional() {
2
+ return null
3
+ }
@@ -0,0 +1,11 @@
1
+ import type { RouteObject } from '@mpen/rerouter'
2
+
3
+ const ROUTES: readonly RouteObject[] = [
4
+ {
5
+ name: 'blogPost',
6
+ pattern: '/blog/:id(\\d+){-:title}?',
7
+ component: () => import('./pages/Match'),
8
+ },
9
+ ]
10
+
11
+ export default ROUTES
@@ -0,0 +1 @@
1
+ export default [{ name: 'home', pattern: '/', component: () => import('./pages/Home') }]
@@ -0,0 +1,4 @@
1
+ export default [
2
+ { name: 'home', pattern: '/', component: () => import('./pages/Home') },
3
+ { pattern: '/layout/:id', component: () => import('./pages/Home') },
4
+ ]
@@ -0,0 +1 @@
1
+ export { useUrlPath, useUrlSearchParams } from './useUrl'
@@ -0,0 +1,22 @@
1
+ import { useMemo, useSyncExternalStore } from 'react'
2
+
3
+ // Snapshot getters
4
+ const getPathname = () => window.location.pathname
5
+ const getSearch = () => window.location.search
6
+
7
+ function subscribe(cb: () => void): () => void {
8
+ const handler = () => cb()
9
+ window.addEventListener('popstate', handler)
10
+ return () => {
11
+ window.removeEventListener('popstate', handler)
12
+ }
13
+ }
14
+
15
+ export function useUrlPath(): string {
16
+ return useSyncExternalStore(subscribe, getPathname, getPathname)
17
+ }
18
+
19
+ export function useUrlSearchParams(): URLSearchParams {
20
+ const search = useSyncExternalStore(subscribe, getSearch, getSearch)
21
+ return useMemo(() => new URLSearchParams(search), [search])
22
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './components/Link'
2
+ export * from './components/NavLink'
3
+ export * from './components/Router'
4
+ export * from './lib/routes'
5
+ export * from './lib/url'
6
+ export * from './hooks'
@@ -0,0 +1,37 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { mergeSearch } from './mergeSearch'
3
+
4
+ describe(mergeSearch.name, () => {
5
+ test('adds search params to a path without a query string', () => {
6
+ expect(mergeSearch('/matches', { page: 2, archived: false })).toBe(
7
+ '/matches?page=2&archived=false',
8
+ )
9
+ })
10
+
11
+ test('overwrites matching params and keeps unrelated existing params', () => {
12
+ expect(mergeSearch('/matches?page=1&sort=asc', { page: 2 })).toBe(
13
+ '/matches?page=2&sort=asc',
14
+ )
15
+ })
16
+
17
+ test('preserves hash fragments after the merged query string', () => {
18
+ expect(mergeSearch('/matches?page=1#details', { page: 2, tab: 'stats' })).toBe(
19
+ '/matches?page=2&tab=stats#details',
20
+ )
21
+ })
22
+
23
+ test('adds search params before a hash fragment when no query string exists', () => {
24
+ expect(mergeSearch('/matches#details', { tab: 'stats' })).toBe('/matches?tab=stats#details')
25
+ })
26
+
27
+ test('accepts URLSearchParams and tuple search params', () => {
28
+ expect(mergeSearch('/matches?filter=open', new URLSearchParams('filter=all'))).toBe(
29
+ '/matches?filter=all',
30
+ )
31
+ expect(mergeSearch('/matches', [['filter', 'open']])).toBe('/matches?filter=open')
32
+ })
33
+
34
+ test('encodes merged params using URLSearchParams serialization', () => {
35
+ expect(mergeSearch('/matches?q=old', { q: 'hello world' })).toBe('/matches?q=hello+world')
36
+ })
37
+ })
@@ -0,0 +1,21 @@
1
+ import type { SearchParamsInit } from '../components/Link'
2
+
3
+ export function mergeSearch(to: string, search: SearchParamsInit): string {
4
+ const hashIndex = to.indexOf('#')
5
+ const hash = hashIndex !== -1 ? to.slice(hashIndex) : ''
6
+ const pathAndQuery = hashIndex !== -1 ? to.slice(0, hashIndex) : to
7
+
8
+ const queryIndex = pathAndQuery.indexOf('?')
9
+ const path = queryIndex !== -1 ? pathAndQuery.slice(0, queryIndex) : pathAndQuery
10
+ const existingQuery = queryIndex !== -1 ? pathAndQuery.slice(queryIndex + 1) : ''
11
+
12
+ const params = new URLSearchParams(existingQuery)
13
+ const newParams = new URLSearchParams(search as any)
14
+
15
+ for (const [key, value] of newParams) {
16
+ params.set(key, value)
17
+ }
18
+
19
+ const queryString = params.toString()
20
+ return `${path}${queryString ? '?' + queryString : ''}${hash}`
21
+ }
@@ -0,0 +1,67 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { normalizeRoutes, type RouteObject } from './routes'
3
+
4
+ const loadComponent: RouteObject['component'] = async () => ({
5
+ default: () => null,
6
+ })
7
+
8
+ describe('normalizeRoutes', () => {
9
+ test('matches routes without names', () => {
10
+ const [route] = normalizeRoutes([
11
+ {
12
+ pattern: '/fetch-loading/:id',
13
+ component: loadComponent,
14
+ },
15
+ ])
16
+
17
+ expect(route.name).toBeUndefined()
18
+ expect(route.matches('/fetch-loading/abc-123')).toEqual({ id: 'abc-123' })
19
+ })
20
+
21
+ test('matches catch-all routes', () => {
22
+ for (const pattern of ['*', '/*']) {
23
+ const [route] = normalizeRoutes([
24
+ {
25
+ pattern,
26
+ component: loadComponent,
27
+ },
28
+ ])
29
+
30
+ expect(route.matches('/')).toEqual({})
31
+ expect(route.matches('/anything')).toEqual({})
32
+ expect(route.matches('/nested/path')).toEqual({})
33
+ }
34
+ })
35
+
36
+ test('matches regexp params with optional groups', () => {
37
+ const [route] = normalizeRoutes([
38
+ {
39
+ name: 'blogPost',
40
+ pattern: '/blog/:id(\\d+){-:title}?',
41
+ component: loadComponent,
42
+ },
43
+ ])
44
+
45
+ expect(route.matches('/blog/123')).toEqual({ id: '123' })
46
+ expect(route.matches('/blog/123-hello%20world')).toEqual({
47
+ id: '123',
48
+ title: 'hello world',
49
+ })
50
+ expect(route.matches('/blog/not-a-number')).toBeNull()
51
+ })
52
+
53
+ test('matches named wildcards', () => {
54
+ const [route] = normalizeRoutes([
55
+ {
56
+ name: 'files',
57
+ pattern: '/files/*path',
58
+ component: loadComponent,
59
+ },
60
+ ])
61
+
62
+ expect(route.matches('/files/docs/api')).toEqual({ path: 'docs/api' })
63
+ expect(route.matches('/files/docs%20and%20api/reference')).toEqual({
64
+ path: 'docs and api/reference',
65
+ })
66
+ })
67
+ })
@@ -0,0 +1,245 @@
1
+ import { match as pathMatch } from 'path-to-regexp'
2
+ import type { ComponentType } from 'react'
3
+
4
+ /**
5
+ * Route params captured from the current URL pathname.
6
+ */
7
+ export type RouteParams = Record<string, string | undefined>
8
+
9
+ /**
10
+ * A React component that receives URL params captured for its route.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * const UserPage: RouteComponent<{ id: string }> = ({ id }) => <div>{id}</div>
15
+ * ```
16
+ */
17
+ export type RouteComponent<TParams extends RouteParams = RouteParams> = ComponentType<TParams>
18
+
19
+ /**
20
+ * A dynamically imported route component module.
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * export default function UserPage({ id }: { id: string }) {
25
+ * return <div>{id}</div>
26
+ * }
27
+ * ```
28
+ */
29
+ export type RouteComponentModule<TParams extends RouteParams = RouteParams> = {
30
+ default: RouteComponent<TParams>
31
+ }
32
+
33
+ /**
34
+ * Loads a route component on demand.
35
+ *
36
+ * @example
37
+ * ```tsx
38
+ * const loadUserPage: RouteComponentLoader<{ id: string }> = () => import('./pages/UserPage')
39
+ * ```
40
+ */
41
+ export type RouteComponentLoader<TParams extends RouteParams = RouteParams> = () => Promise<
42
+ RouteComponentModule<TParams>
43
+ >
44
+
45
+ /**
46
+ * Object route definition consumed by [`Router`]{@link Router}.
47
+ *
48
+ * @example
49
+ * ```tsx
50
+ * const route: RouteObject = {
51
+ * name: 'userProfile',
52
+ * pattern: '/users/:id',
53
+ * component: () => import('./pages/UserProfile'),
54
+ * }
55
+ * ```
56
+ */
57
+ export type RouteObject = {
58
+ /**
59
+ * Optional route name used by the CLI to generate a URL helper.
60
+ *
61
+ * Routes without a name still participate in runtime matching, but are skipped by the
62
+ * helper generator.
63
+ */
64
+ name?: string
65
+ pattern: string | URLPattern
66
+ component: RouteComponentLoader<any>
67
+ }
68
+
69
+ /**
70
+ * Route definition consumed by [`Router`]{@link Router}.
71
+ *
72
+ * @example
73
+ * ```tsx
74
+ * const routes: readonly Route[] = [
75
+ * { name: 'home', pattern: '/', component: () => import('./pages/Home') },
76
+ * { pattern: '/users/:id', component: () => import('./pages/UserLayout') },
77
+ * ]
78
+ * ```
79
+ */
80
+ export type Route = RouteObject
81
+
82
+ /**
83
+ * Route definition normalized into a single object shape with a pathname matcher.
84
+ */
85
+ export type NormalizedRoute = {
86
+ name?: string
87
+ pattern: string | URLPattern
88
+ component: RouteComponentLoader<any>
89
+ matches(pathname: string): RouteParams | null
90
+ }
91
+
92
+ function toUrlPattern(pattern: string | URLPattern): URLPattern {
93
+ if (typeof pattern !== 'string') return pattern
94
+ return new URLPattern({ pathname: pattern })
95
+ }
96
+
97
+ function decodeRouteParams(groups: Record<string, unknown>): RouteParams {
98
+ const params: RouteParams = {}
99
+ for (const [key, value] of Object.entries(groups)) {
100
+ if (value == null) params[key] = undefined
101
+ else params[key] = decodeURIComponent(String(value))
102
+ }
103
+ return params
104
+ }
105
+
106
+ function stripLegacyParamPattern(pattern: string, startIndex: number): number {
107
+ let depth = 1
108
+ let endIndex = startIndex + 1
109
+ while (endIndex < pattern.length && depth > 0) {
110
+ const char = pattern[endIndex]
111
+ if (char === '\\') {
112
+ endIndex += 2
113
+ continue
114
+ }
115
+ if (char === '(') depth++
116
+ else if (char === ')') depth--
117
+ endIndex++
118
+ }
119
+ return endIndex
120
+ }
121
+
122
+ /**
123
+ * Converts legacy `path-to-regexp` syntax that is ignored by URL generation into syntax accepted
124
+ * by the current parser.
125
+ *
126
+ * @param pattern - The route pattern to normalize.
127
+ * @returns The pattern with custom regexp constraints stripped and optional group suffixes removed.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * normalizeLegacyPathToRegexpSyntax('/blog/:id(\\d+){-:title}?')
132
+ * // '/blog/:id{-:title}'
133
+ * ```
134
+ *
135
+ * @internal
136
+ */
137
+ export function normalizeLegacyPathToRegexpSyntax(pattern: string): string {
138
+ let normalized = ''
139
+ for (let i = 0; i < pattern.length; i++) {
140
+ const char = pattern[i]
141
+ if (char === '\\') {
142
+ normalized += char
143
+ if (i + 1 < pattern.length) normalized += pattern[++i]
144
+ continue
145
+ }
146
+
147
+ if (char === ':' || char === '*') {
148
+ normalized += char
149
+ while (i + 1 < pattern.length && /[$_\p{ID_Continue}]/u.test(pattern[i + 1])) {
150
+ normalized += pattern[++i]
151
+ }
152
+ if (pattern[i + 1] === '(') {
153
+ i = stripLegacyParamPattern(pattern, i + 1) - 1
154
+ }
155
+ continue
156
+ }
157
+
158
+ if (char === '}' && pattern[i + 1] === '?') {
159
+ normalized += char
160
+ i++
161
+ continue
162
+ }
163
+
164
+ normalized += char
165
+ }
166
+ return normalized
167
+ }
168
+
169
+ /**
170
+ * Normalizes routes into objects with a shared matcher implementation.
171
+ *
172
+ * @param routes - The route definitions to normalize.
173
+ * @returns Routes with stable `name`, `pattern`, `component`, and `matches` fields.
174
+ *
175
+ * @example
176
+ * ```tsx
177
+ * const normalized = normalizeRoutes(routes)
178
+ * const match = normalized[0]?.matches('/users/123')
179
+ * ```
180
+ */
181
+ export function normalizeRoutes(routes: readonly Route[]): NormalizedRoute[] {
182
+ return routes.map((route) => {
183
+ const { name, pattern, component } = route
184
+
185
+ if (typeof pattern !== 'string') {
186
+ const urlPattern = toUrlPattern(pattern)
187
+ return {
188
+ name,
189
+ pattern,
190
+ component,
191
+ matches(pathname: string) {
192
+ const match = urlPattern.exec({ pathname } as any)
193
+ if (!match) return null
194
+ return ((match as any).pathname?.groups ?? {}) as RouteParams
195
+ },
196
+ }
197
+ }
198
+
199
+ if (pattern === '*' || pattern === '/*') {
200
+ return {
201
+ name,
202
+ pattern,
203
+ component,
204
+ matches: (_pathname: string) => ({}),
205
+ }
206
+ }
207
+
208
+ let matcher: ReturnType<typeof pathMatch> | undefined
209
+ let urlPattern: URLPattern | undefined
210
+ try {
211
+ matcher = pathMatch(pattern, { decode: decodeURIComponent })
212
+ } catch {
213
+ try {
214
+ urlPattern = toUrlPattern(pattern)
215
+ } catch {
216
+ matcher = pathMatch(normalizeLegacyPathToRegexpSyntax(pattern), {
217
+ decode: decodeURIComponent,
218
+ })
219
+ }
220
+ }
221
+ return {
222
+ name,
223
+ pattern,
224
+ component,
225
+ matches(pathname: string) {
226
+ if (urlPattern) {
227
+ const match = urlPattern.exec({ pathname } as any)
228
+ if (!match) return null
229
+ return decodeRouteParams((match as any).pathname?.groups ?? {})
230
+ }
231
+
232
+ if (!matcher) return null
233
+ const match = matcher(pathname)
234
+ if (!match) return null
235
+ const params: RouteParams = {}
236
+ for (const [key, value] of Object.entries(match.params as any)) {
237
+ if (value == null) params[key] = undefined
238
+ else if (Array.isArray(value)) params[key] = value.join('/')
239
+ else params[key] = String(value)
240
+ }
241
+ return params
242
+ },
243
+ }
244
+ })
245
+ }
package/src/lib/url.ts ADDED
@@ -0,0 +1,9 @@
1
+ export function pushUrl(next: string, state?: unknown): void {
2
+ window.history.pushState(state, '', next)
3
+ window.dispatchEvent(new PopStateEvent('popstate'))
4
+ }
5
+
6
+ export function replaceUrl(next: string, state?: unknown): void {
7
+ window.history.replaceState(state, '', next)
8
+ window.dispatchEvent(new PopStateEvent('popstate'))
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "jsx": "react-jsx",
5
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
6
+ "types": ["bun", "node", "react", "react-dom"]
7
+ },
8
+ "include": ["src/**/*", "examples/**/*"]
9
+ }
@@ -0,0 +1,22 @@
1
+ import { defineConfig } from 'tsdown'
2
+
3
+ // https://tsdown.dev/reference/api/Interface.UserConfig
4
+ export default defineConfig({
5
+ entry: {
6
+ index: 'src/index.ts',
7
+ hooks: 'src/hooks/index.ts',
8
+ bin: 'src/bin.ts',
9
+ },
10
+ format: 'esm',
11
+ platform: 'browser',
12
+ deps: {
13
+ neverBundle: [/^(node|bun):/, 'react'],
14
+ },
15
+ exports: {
16
+ legacy: true,
17
+ bin: {
18
+ rerouter: './src/bin.ts',
19
+ },
20
+ },
21
+ dts: true, // The client must use "moduleResolution": "bundler", "node16" or "nodenext". "node" will not resolve the types properly.
22
+ })