@xzsv/router 0.0.0-stage → 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.
package/src/env.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ interface ImportMeta {
2
+ readonly env?: { readonly DEV?: boolean; readonly SSR?: boolean }
3
+ }
package/src/index.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @module: @xzsv/router
3
+ *
4
+ * A lightweight, client-side router for Svelte 5 with support for:
5
+ * - Nested routes and layouts
6
+ * - Dynamic parameters and wildcards
7
+ * - Lazy loading
8
+ * - Navigation hooks
9
+ * - Dual-tree rendering for smooth transitions
10
+ */
11
+
12
+ // Core router
13
+ export {
14
+ createRouter,
15
+ isActiveLink,
16
+ phase,
17
+ preloadRoute,
18
+ routeNode,
19
+ searchParamsProxy as searchParams,
20
+ } from './create.svelte.ts'
21
+ export { default as Link } from './Link.svelte'
22
+ export { log } from './log.ts'
23
+ export { default as Router } from './Router.svelte'
24
+ export { q } from './utils.ts'
25
+
26
+ // Types
27
+ export type {
28
+ AllParams,
29
+ ComponentTree,
30
+ ComponentTreeNode,
31
+ Hooks,
32
+ LayoutComponent,
33
+ LazyRouteComponent,
34
+ LinkProps,
35
+ Location,
36
+ NavigateOptions,
37
+ Path,
38
+ PathParams,
39
+ Phase,
40
+ QueryValue,
41
+ RouteComponent,
42
+ RouteNodeInfo,
43
+ RouterApi,
44
+ Routes,
45
+ TransitionFn,
46
+ Transitions,
47
+ } from './types'
package/src/log.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { getLogger } from '@logtape/logtape'
2
+
3
+ // Silent by default: the app configures LogTape sinks and levels
4
+ // (category ["xzsv", "router"]). The library never calls configure itself.
5
+ export const log = getLogger(['xzsv', 'router'])
6
+ export { getLogger }
@@ -0,0 +1,6 @@
1
+ export interface RouteNodeCtx {
2
+ depth: number
3
+ key: number
4
+ }
5
+
6
+ export const routeNodeKey = Symbol('xzsv-route-node')
package/src/types.ts ADDED
@@ -0,0 +1,364 @@
1
+ import type { Component, Snippet } from 'svelte'
2
+
3
+ /**
4
+ * Base props for route components
5
+ */
6
+ export type BaseProps = {}
7
+
8
+ /**
9
+ * Lazy-loaded route component
10
+ */
11
+ export type LazyRouteComponent<Props extends BaseProps = BaseProps> = () => Promise<{
12
+ [key: string]: Component<Props>
13
+ }>
14
+
15
+ /**
16
+ * Route component can be either a regular component or a lazy-loaded one
17
+ */
18
+ export type RouteComponent<Props extends BaseProps = any> =
19
+ | Component<Props>
20
+ | LazyRouteComponent<Props>
21
+
22
+ /**
23
+ * Contextual info passed to transition callbacks per route node.
24
+ */
25
+ export type RouteNodeInfo = {
26
+ depth: number
27
+ key: number
28
+ from: string
29
+ to: string
30
+ }
31
+
32
+ /**
33
+ * Per-element transition callback. Return a promise to hold the
34
+ * dual-tree swap until the animation settles (or the timeout fires).
35
+ */
36
+ export type TransitionFn = (
37
+ el: HTMLElement,
38
+ info: RouteNodeInfo,
39
+ ) => void | Promise<void>
40
+
41
+ /**
42
+ * Router-orchestrated transitions: enter/leave fire per route-node
43
+ * element (pages/layout roots carrying the `routeNode` attachment),
44
+ * only for nodes past the equality point — persistent layouts never
45
+ * animate. `timeoutMs` bounds how long the router waits for returned
46
+ * promises before finalizing anyway (default 1000).
47
+ */
48
+ export type Transitions = {
49
+ enter?: TransitionFn
50
+ leave?: TransitionFn
51
+ timeoutMs?: number
52
+ /**
53
+ * Wrap the tree swap in a same-document View Transition
54
+ * (`document.startViewTransition`) when available, letting
55
+ * `::view-transition-*` CSS animate the handoff. Falls back to a plain
56
+ * swap where the API is missing. Off by default.
57
+ */
58
+ viewTransition?: boolean
59
+ }
60
+
61
+ /**
62
+ * Layout component includes children snippet
63
+ */
64
+ export type LayoutComponent =
65
+ | RouteComponent<{ children: Snippet }>
66
+ | [RouteComponent, { submodule?: string }]
67
+
68
+ /**
69
+ * Component tree structure for dual-tree rendering
70
+ */
71
+ export type ComponentTree = {
72
+ value: {
73
+ a: ComponentTreeNode[]
74
+ b: ComponentTreeNode[]
75
+ eq: number
76
+ }
77
+ }
78
+
79
+ export type ComponentTreeNode = {
80
+ C: Component<any>
81
+ key: number
82
+ params?: Record<string, string>
83
+ }
84
+
85
+ /**
86
+ * Lifecycle hooks for route navigation
87
+ */
88
+ export type Hooks = {
89
+ /**
90
+ * Called before loading the route components.
91
+ * Can throw to cancel navigation.
92
+ */
93
+ beforeLoad?(args: {
94
+ from: string
95
+ to: string
96
+ cycle: Cycle
97
+ match?: RouteComponent
98
+ params: Record<string, string>
99
+ signal?: AbortSignal
100
+ }): void | Promise<void>
101
+
102
+ /**
103
+ * Called after components are resolved but before rendering.
104
+ * Useful for loading data or assets.
105
+ */
106
+ duringLoad?(args: {
107
+ from: string
108
+ to: string
109
+ cycle: Cycle
110
+ componentTree: ComponentTree['value']
111
+ mountedComponents: Record<string, any>
112
+ keys: { in: string[]; out: string[] }
113
+ signal?: AbortSignal
114
+ }): void | Promise<void>
115
+
116
+ /**
117
+ * Called during the rendering phase.
118
+ * Used for transitions and animations.
119
+ */
120
+ duringRender?(args: {
121
+ from: string
122
+ to: string
123
+ cycle: Cycle
124
+ componentTree: ComponentTree['value']
125
+ mountedComponents: Record<string, any>
126
+ keys: { in: string[]; out: string[] }
127
+ signal?: AbortSignal
128
+ }): void | Promise<void>
129
+
130
+ /**
131
+ * Called after rendering is complete.
132
+ */
133
+ afterRender?(args: {
134
+ from: string
135
+ to: string
136
+ cycle: Cycle
137
+ componentTree: ComponentTree['value']
138
+ mountedComponents: Record<string, any>
139
+ keys: { in: string[]; out: string[] }
140
+ signal?: AbortSignal
141
+ }): void
142
+ }
143
+
144
+ /**
145
+ * Tree cycle
146
+ */
147
+ export type Cycle = {
148
+ value: 'a' | 'ba' | 'b' | 'ab'
149
+ from: 'a' | 'b'
150
+ readonly to: 'a' | 'b'
151
+ readonly first: 'a' | 'b'
152
+ readonly second: 'a' | 'b' | undefined
153
+ readonly chars: ReadonlyArray<('a' | 'b')>
154
+ readonly isSingle: boolean
155
+ readonly isDual: boolean
156
+ readonly filled: 'ab' | 'ba'
157
+ fill(): void
158
+ finalize(): void
159
+ }
160
+
161
+ /**
162
+ * Route definition structure
163
+ */
164
+ export type Routes = {
165
+ [_: `/${string}`]:
166
+ | RouteComponent
167
+ | [RouteComponent, { submodule?: string; params?: string[] }]
168
+ | Routes
169
+ [_: `*${string}` | `(*${string})`]:
170
+ | RouteComponent
171
+ | [RouteComponent, { submodule?: string; params?: string[] }]
172
+ | undefined
173
+ layout?: LayoutComponent
174
+ hooks?: Hooks
175
+ }
176
+
177
+ /**
178
+ * Navigation options
179
+ */
180
+ export type NavigateOptions = {
181
+ hash?: string
182
+ replace?: boolean
183
+ scrollToTop?: ScrollBehavior | false
184
+ search?: string
185
+ state?: string
186
+ bypass?: boolean
187
+ }
188
+
189
+ /**
190
+ * Query parameter values accepted by `q()` and `<Link search={...}>`.
191
+ * Falsy-absent values (`undefined`/`null`/`''`) are skipped.
192
+ */
193
+ export type QueryValue = string | number | boolean | undefined | null
194
+
195
+ /**
196
+ * Props for the `<Link>` component. Only `to` and `children` are required;
197
+ * everything else mirrors `navigate()` options, which Link forwards via
198
+ * the router's global click interception (`data-*` attributes).
199
+ */
200
+ export type LinkProps = {
201
+ /** Target path — build dynamic ones with `p()`. */
202
+ to: string
203
+ /** Params for `to`'s dynamic segments; used for active matching. */
204
+ params?: Record<string, string>
205
+ /** Query string: a ready-made string or an object encoded via `q()`. */
206
+ search?: string | Record<string, QueryValue>
207
+ hash?: string
208
+ replace?: boolean
209
+ scrollToTop?: ScrollBehavior | false
210
+ /** Prefix-match for active state (section nav inside a page tree). */
211
+ startsWith?: boolean
212
+ /** Class applied when the link is active. */
213
+ activeClass?: string
214
+ /** Class applied when the link is inactive. */
215
+ inactiveClass?: string
216
+ /** Emit `data-preload` for hover prefetch. Default `true`. */
217
+ preload?: boolean
218
+ class?: string
219
+ children: Snippet
220
+ [key: string]: unknown
221
+ }
222
+
223
+ /**
224
+ * Location information
225
+ */
226
+ export type Location = {
227
+ pathname: string
228
+ search: string
229
+ state: any
230
+ hash: string
231
+ }
232
+
233
+ /**
234
+ * Router phase states
235
+ */
236
+ export type Phase =
237
+ | 'idle'
238
+ | 'beforeLoad'
239
+ | 'duringLoad'
240
+ | 'duringRender'
241
+ | 'afterRender'
242
+ /**
243
+ * A navigation failed: a hook threw, or route resolution errored. The
244
+ * URL still points at the previous route. Treat it like idle — the
245
+ * next navigation proceeds normally.
246
+ */
247
+ | 'error'
248
+
249
+ /**
250
+ * Type utilities for extracting route paths and params
251
+ */
252
+ type StripNonRoutes<T extends Routes> = {
253
+ [
254
+ K in keyof T as K extends `*${string}` ? never
255
+ : K extends `(*${string})` ? never
256
+ : K extends 'layout' ? never
257
+ : K extends 'hooks' ? never
258
+ : K
259
+ ]: T[K] extends Routes ? StripNonRoutes<T[K]> : T[K]
260
+ }
261
+
262
+ type RecursiveKeys<T extends Routes, Prefix extends string = ''> = {
263
+ [K in keyof T]: K extends string ? T[K] extends Routes ? RecursiveKeys<T[K], `${Prefix}${K}`>
264
+ : `${Prefix}${K}`
265
+ : never
266
+ }[keyof T]
267
+
268
+ type RemoveLastSlash<T extends string> = T extends '/' ? T
269
+ : T extends `${infer R}/` ? R
270
+ : T
271
+
272
+ type RemoveParenthesis<T extends string> = T extends `${infer A}(${infer B})${infer C}`
273
+ ? RemoveParenthesis<`${A}${B}${C}`>
274
+ : T
275
+
276
+ export type Path<T extends Routes> = RemoveParenthesis<
277
+ RemoveLastSlash<RecursiveKeys<StripNonRoutes<T>>>
278
+ >
279
+
280
+ type ExtractParams<T extends string> = T extends `${string}:${infer Param}/${infer Rest}`
281
+ ? Param | ExtractParams<`/${Rest}`>
282
+ : T extends `${string}(:${infer Param})` ? Param
283
+ : T extends `${string}:${infer Param}` ? Param
284
+ : T extends `${string}(*${infer Param})` ? Param
285
+ : T extends `${string}*${infer Param}` ? Param extends '' ? never
286
+ : Param
287
+ : never
288
+
289
+ export type PathParams<T extends string> = ExtractParams<T> extends never ? never : Record<ExtractParams<T>, string>
290
+
291
+ // export type ConstructPathArgs<T extends string> = PathParams<T> extends never ? [T] : [T, PathParams<T>]
292
+
293
+ type NavigateArgs<T extends string> =
294
+ | (PathParams<T> extends never ? [T] | [T, NavigateOptions]
295
+ : [T, NavigateOptions & { params: PathParams<T> }])
296
+ | [number]
297
+
298
+ export type IsActiveArgs<T extends string> = PathParams<T> extends never ? [T] : [T] | [T, PathParams<T>]
299
+
300
+ export type AllParams<T extends Routes> = Partial<
301
+ Record<ExtractParams<RecursiveKeys<T>>, string>
302
+ >
303
+
304
+ /**
305
+ * Main router API
306
+ */
307
+ export type RouterApi<T extends Routes> = {
308
+ /**
309
+ * Construct a path with type safety
310
+ */
311
+ p(path: string, params?: Record<string, string>): string
312
+
313
+ /**
314
+ * Navigate to a route
315
+ */
316
+ navigate<U extends Path<T>>(...args: NavigateArgs<U>): void
317
+ /**
318
+ * Dynamic/constructed paths (e.g. results of `p()` or built strings):
319
+ * no literal checking, params must already be substituted.
320
+ */
321
+ navigate(path: string, options?: NavigateOptions): void
322
+
323
+ /**
324
+ * Warm a route's lazy components programmatically — what hover-preload
325
+ * does, callable from pointerdown handlers, idle callbacks, or boot
326
+ * sequences. Deduped per path; resolves when components are loaded.
327
+ */
328
+ preload(path: string): Promise<void>
329
+
330
+ /**
331
+ * Check if a path is active
332
+ */
333
+ isActive: {
334
+ <U extends Path<T>>(...args: IsActiveArgs<U>): boolean
335
+ startsWith<U extends Path<T>>(...args: IsActiveArgs<U>): boolean
336
+ }
337
+
338
+ /**
339
+ * Current route information
340
+ */
341
+ route: {
342
+ params: AllParams<T>
343
+ pathname: Path<T>
344
+ search: string
345
+ state: unknown
346
+ hash: string
347
+ phase: Phase
348
+ }
349
+
350
+ /**
351
+ * Current navigation phase
352
+ */
353
+ phase: { value: Phase }
354
+
355
+ /**
356
+ * Component tree (for advanced use cases)
357
+ */
358
+ C: ComponentTree
359
+
360
+ /**
361
+ * Mounted components (for advanced use cases)
362
+ */
363
+ MC: Record<string, any>
364
+ }