@oomfware/stacker 0.1.0 → 0.1.2

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/routes.ts DELETED
@@ -1,325 +0,0 @@
1
- import type { ComponentType, ReactNode } from 'react';
2
-
3
- import type { BuildShape, CodecRecord, DecodeShape, Infer } from './codec.ts';
4
- import { getDefault, isOptional } from './codec.ts';
5
-
6
- // #region node definitions
7
-
8
- type Empty = Record<never, never>;
9
-
10
- /**
11
- * defines how a leaf route instance is keyed.
12
- *
13
- * - `page` — one instance per history entry.
14
- * - `singleton` — one instance per distinct set of path parameters, shared across entries.
15
- */
16
- export type LeafType = 'page' | 'singleton';
17
-
18
- /**
19
- * application-defined metadata attached to routes or layouts.
20
- *
21
- * stacker does not read these values, and declares no fields of its own. an application declares the ones it
22
- * needs and reads them back off the active chain with `resolveMeta`.
23
- *
24
- * ```ts
25
- * declare module '@oomfware/stacker' {
26
- * interface RouteMeta {
27
- * readonly requireAuth?: boolean;
28
- * }
29
- * }
30
- * ```
31
- */
32
- // oxlint-disable-next-line typescript/no-empty-object-type -- the host app fills this in by declaration merging
33
- export interface RouteMeta {}
34
-
35
- /** a read-only view of {@link URLSearchParams} that omits its mutating members. */
36
- export type ReadonlyURLSearchParams = Omit<URLSearchParams, 'append' | 'delete' | 'set' | 'sort'>;
37
-
38
- /** context passed to a route `when` predicate. */
39
- export interface WhenContext {
40
- readonly hash: string;
41
- readonly pathname: string;
42
- readonly rawSearch: ReadonlyURLSearchParams;
43
- readonly search: string;
44
- }
45
-
46
- interface LeafShared<Params extends CodecRecord, Query extends CodecRecord> {
47
- /** component to render. */
48
- readonly component: ComponentType;
49
- /** suspense fallback component. */
50
- readonly fallback?: ReactNode;
51
- /** application metadata. */
52
- readonly meta?: RouteMeta;
53
- /** path parameter codecs. */
54
- readonly params?: Params;
55
- /** absolute URL path pattern. */
56
- readonly path: string;
57
- /** query parameter codecs. */
58
- readonly query?: Query;
59
- /** instance-keying strategy. */
60
- readonly type?: LeafType;
61
- /** dynamic predicate for route matching. */
62
- readonly when?: (ctx: WhenContext) => boolean;
63
- }
64
-
65
- /** configuration for a navigable leaf route. */
66
- export type RouteConfig<Params extends CodecRecord, Query extends CodecRecord> = LeafShared<Params, Query>;
67
-
68
- /** a navigable leaf route node. */
69
- export interface RouteLeaf<
70
- Params extends CodecRecord = Empty,
71
- Query extends CodecRecord = Empty,
72
- > extends LeafShared<Params, Query> {
73
- readonly kind: 'route';
74
- }
75
-
76
- /** configuration for an interior layout node. */
77
- export interface LayoutConfig<Children extends RouteChildren, Params extends CodecRecord> {
78
- /** nested child nodes. */
79
- readonly children: Children;
80
- /** layout component rendering an outlet. */
81
- readonly component: ComponentType;
82
- /** suspense fallback component. */
83
- readonly fallback?: ReactNode;
84
- /** application metadata. */
85
- readonly meta?: RouteMeta;
86
- /**
87
- * codecs for layout parameters. parameter names must appear in all descendant leaf paths, allowing layouts
88
- * to decode their own values.
89
- */
90
- readonly params?: Params;
91
- }
92
-
93
- /** an interior layout node. */
94
- export type LayoutNode<Children extends RouteChildren = RouteChildren, Params extends CodecRecord = Empty> = {
95
- readonly kind: 'layout';
96
- } & LayoutConfig<Children, Params>;
97
-
98
- /** a layout or leaf route node. */
99
- export type RouteNode = LayoutNode | RouteLeaf;
100
-
101
- /** a record of child nodes. */
102
- export interface RouteChildren {
103
- readonly [name: string]: RouteNode;
104
- }
105
-
106
- /**
107
- * defines a navigable leaf route.
108
- *
109
- * @param config the route configuration
110
- * @returns the route leaf node
111
- */
112
- export const route = <const Params extends CodecRecord = Empty, const Query extends CodecRecord = Empty>(
113
- config: RouteConfig<Params, Query>,
114
- ): RouteLeaf<Params, Query> => ({ kind: 'route', ...config });
115
-
116
- /**
117
- * defines an interior layout node.
118
- *
119
- * @param config the layout configuration
120
- * @returns the layout node
121
- */
122
- export const layout = <const Children extends RouteChildren, const Params extends CodecRecord = Empty>(
123
- config: LayoutConfig<Children, Params>,
124
- ): LayoutNode<Children, Params> => ({ kind: 'layout', ...config });
125
-
126
- // #endregion
127
-
128
- // #region resolved (runtime) structures
129
-
130
- /** a node resolved with an id and normalized parameters. */
131
- export interface ResolvedNode {
132
- /** unique dot-separated node path. */
133
- readonly id: string;
134
- /** key name within the parent record. */
135
- readonly key: string;
136
- readonly kind: 'layout' | 'route';
137
- readonly node: RouteNode;
138
- /** local parameter codecs. */
139
- readonly params: CodecRecord;
140
- /** absolute path pattern if a route. */
141
- readonly path: string | undefined;
142
- }
143
-
144
- /** a leaf node resolved with its ancestors and metadata. */
145
- export interface ResolvedLeaf {
146
- /** ancestors list from root to leaf. */
147
- readonly chain: readonly ResolvedNode[];
148
- readonly leaf: RouteLeaf;
149
- /** unique route name. */
150
- readonly name: string;
151
- /** path parameter codecs. */
152
- readonly params: CodecRecord;
153
- /** absolute path pattern. */
154
- readonly path: string;
155
- /** query parameter codecs. */
156
- readonly query: CodecRecord;
157
- }
158
-
159
- /** a compiled registry of routes and nodes. */
160
- export interface RouteRegistry<T> {
161
- /** resolved leaves in matching order. */
162
- readonly leaves: ReadonlyMap<string, ResolvedLeaf>;
163
- readonly tree: T;
164
- }
165
-
166
- const PATH_PARAM = /:([A-Za-z_]\w*)/g;
167
-
168
- const pathParamNames = (path: string): string[] => {
169
- const names: string[] = [];
170
- for (const match of path.matchAll(PATH_PARAM)) {
171
- const name = match[1];
172
- if (name !== undefined) {
173
- names.push(name);
174
- }
175
- }
176
- return names;
177
- };
178
-
179
- const sameKeySet = (a: readonly string[], b: readonly string[]): boolean => {
180
- if (a.length !== b.length) {
181
- return false;
182
- }
183
- const set = new Set(a);
184
- return b.every((key) => set.has(key));
185
- };
186
-
187
- // an index-signature constraint would widen defaulted generics and disrupt downstream inference.
188
- type ValidRoutes<T> = { readonly [K in keyof T]: T[K] extends RouteNode ? T[K] : never };
189
-
190
- /**
191
- * compiles a route tree, validating keys, paths, and parameter codecs.
192
- *
193
- * @param tree the route tree configuration
194
- * @returns the compiled registry
195
- * @throws when route definitions violate nesting, unique names, or codec constraints
196
- */
197
- export const defineRoutes = <const T>(tree: T & ValidRoutes<T>): RouteRegistry<T> => {
198
- const leaves = new Map<string, ResolvedLeaf>();
199
- const ids = new Set<string>();
200
-
201
- const visit = (children: RouteChildren, parentChain: readonly ResolvedNode[], parentId: string): void => {
202
- for (const [key, node] of Object.entries(children)) {
203
- if (key.includes('.')) {
204
- throw new Error(`stacker: route key '${key}' must not contain '.'`);
205
- }
206
- const id = parentId ? `${parentId}.${key}` : key;
207
- if (ids.has(id)) {
208
- throw new Error(`stacker: duplicate node id '${id}'`);
209
- }
210
- const params: CodecRecord = node.params ?? {};
211
- const resolved: ResolvedNode = {
212
- id,
213
- key,
214
- kind: node.kind,
215
- node,
216
- params,
217
- path: node.kind === 'route' ? node.path : undefined,
218
- };
219
- ids.add(id);
220
- const chain = [...parentChain, resolved];
221
-
222
- if (node.kind === 'layout') {
223
- visit(node.children, chain, id);
224
- continue;
225
- }
226
-
227
- if (leaves.has(key)) {
228
- throw new Error(`stacker: duplicate route name '${key}'`);
229
- }
230
- if (!node.path.startsWith('/')) {
231
- throw new Error(`stacker: route '${key}' path '${node.path}' must start with '/'`);
232
- }
233
-
234
- const query: CodecRecord = node.query ?? {};
235
- const ownPathParams = pathParamNames(node.path);
236
- const declaredParams = Object.keys(params);
237
-
238
- if (!sameKeySet(ownPathParams, declaredParams)) {
239
- throw new Error(
240
- `stacker: route '${key}' path params [${ownPathParams.join(', ')}] do not match declared params [${declaredParams.join(', ')}]`,
241
- );
242
- }
243
- for (const [paramName, codec] of Object.entries(params)) {
244
- if (isOptional(codec) || getDefault(codec) !== undefined) {
245
- throw new Error(
246
- `stacker: path param '${paramName}' of route '${key}' must not be optional() or withDefault()`,
247
- );
248
- }
249
- }
250
- for (const queryKey of Object.keys(query)) {
251
- if (queryKey in params) {
252
- throw new Error(`stacker: route '${key}' declares '${queryKey}' as both a path and query param`);
253
- }
254
- }
255
- for (const ancestor of chain) {
256
- if (ancestor.kind !== 'layout') {
257
- continue;
258
- }
259
- for (const layoutParam of Object.keys(ancestor.params)) {
260
- if (!ownPathParams.includes(layoutParam)) {
261
- throw new Error(
262
- `stacker: layout '${ancestor.id}' param '${layoutParam}' is not present in route '${key}' path '${node.path}'`,
263
- );
264
- }
265
- }
266
- }
267
-
268
- leaves.set(key, { chain, leaf: node, name: key, params, path: node.path, query });
269
- }
270
- };
271
-
272
- visit(tree, [], '');
273
-
274
- return { leaves, tree };
275
- };
276
-
277
- // #endregion
278
-
279
- // #region type-level derivation
280
-
281
- type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void
282
- ? I
283
- : never;
284
-
285
- export type FlattenChildren<C> = UnionToIntersection<
286
- {
287
- [K in keyof C]: C[K] extends { readonly children: infer GC; readonly kind: 'layout' }
288
- ? FlattenChildren<GC>
289
- : C[K] extends { readonly kind: 'route' }
290
- ? { readonly [P in K]: C[K] }
291
- : never;
292
- }[keyof C]
293
- >;
294
-
295
- type LeavesMap<R> = R extends RouteRegistry<infer T> ? FlattenChildren<T> : never;
296
-
297
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
298
-
299
- // path parameters are required; removing `readonly` accepts plain object literals.
300
- type PathShape<P extends CodecRecord> = { -readonly [K in keyof P]: Infer<P[K]> };
301
-
302
- type LeafDecode<L> = L extends RouteLeaf<infer P, infer Q> ? Prettify<DecodeShape<Q> & PathShape<P>> : never;
303
- type LeafBuild<L> = L extends RouteLeaf<infer P, infer Q> ? Prettify<BuildShape<Q> & PathShape<P>> : never;
304
- // `| undefined` keeps deletion assignable for consumers with `exactOptionalPropertyTypes`.
305
- type LeafQueryPatch<L> =
306
- L extends RouteLeaf<infer _P, infer Q>
307
- ? Prettify<{ readonly [P in keyof Q]?: Infer<Q[P]> | undefined }>
308
- : never;
309
-
310
- /** a union of all navigable route names. */
311
- export type RouteName<R> = keyof LeavesMap<R> & string;
312
-
313
- /** the decoded parameter shape for a route name. */
314
- export type ParamsOf<R, K extends RouteName<R>> = LeafDecode<LeavesMap<R>[K]>;
315
-
316
- /** the parameter shape required to build a URL or navigate to a route. */
317
- export type BuildParamsOf<R, K extends RouteName<R>> = LeafBuild<LeavesMap<R>[K]>;
318
-
319
- /**
320
- * the patch shape accepted by a route's query setter: every query codec, all optional, each value accepting
321
- * `undefined` to delete the parameter. path parameters are excluded — they are not settable in place.
322
- */
323
- export type QueryPatchOf<R, K extends RouteName<R>> = LeafQueryPatch<LeavesMap<R>[K]>;
324
-
325
- // #endregion
package/src/testing.ts DELETED
@@ -1,2 +0,0 @@
1
- export type { MemoryHistoryOptions } from './history/memory.ts';
2
- export { MemoryHistory } from './history/memory.ts';
package/src/url.ts DELETED
@@ -1,41 +0,0 @@
1
- export interface PathParts {
2
- hash: string;
3
- pathname: string;
4
- search: string;
5
- }
6
-
7
- export const parsePath = (to: string): PathParts => {
8
- let pathname = to;
9
- let search = '';
10
- let hash = '';
11
-
12
- const hashIndex = pathname.indexOf('#');
13
- if (hashIndex >= 0) {
14
- hash = pathname.slice(hashIndex);
15
- pathname = pathname.slice(0, hashIndex);
16
- }
17
-
18
- const searchIndex = pathname.indexOf('?');
19
- if (searchIndex >= 0) {
20
- search = pathname.slice(searchIndex);
21
- pathname = pathname.slice(0, searchIndex);
22
- }
23
-
24
- return { hash, pathname, search };
25
- };
26
-
27
- export const resolvePath = (to: string, base: PathParts): PathParts => {
28
- const resolved = new URL(to, `http://_${createPath(base)}`);
29
- return { hash: resolved.hash, pathname: resolved.pathname, search: resolved.search };
30
- };
31
-
32
- export const createPath = ({ hash, pathname, search }: PathParts): string => {
33
- let out = pathname || '/';
34
- if (search && search !== '?') {
35
- out += search.startsWith('?') ? search : `?${search}`;
36
- }
37
- if (hash && hash !== '#') {
38
- out += hash.startsWith('#') ? hash : `#${hash}`;
39
- }
40
- return out;
41
- };
package/src/view-model.ts DELETED
@@ -1,78 +0,0 @@
1
- import { instanceKey } from './keys.ts';
2
- import type { RouteMatch } from './match.ts';
3
- import type { ResolvedNode } from './routes.ts';
4
-
5
- export interface PoolEntry {
6
- /** the history slot this entry occupies, which is also its rendering identity. */
7
- readonly key: string;
8
- readonly match: RouteMatch;
9
- }
10
-
11
- /** an instance node within the layout tree structure. */
12
- export interface InstanceNode {
13
- readonly children: InstanceNode[];
14
- readonly instanceKey: string;
15
- readonly node: ResolvedNode;
16
- readonly params: Readonly<Record<string, unknown>>;
17
- }
18
-
19
- /** the computed rendering view configuration. */
20
- export interface View {
21
- /** instance keys along the active chain from root to leaf. */
22
- readonly activePath: readonly string[];
23
- /** the top-level pool (instances at the root outlet). */
24
- readonly roots: readonly InstanceNode[];
25
- }
26
-
27
- interface PlacedNode {
28
- children: PlacedNode[];
29
- instanceKey: string;
30
- node: ResolvedNode;
31
- params: Readonly<Record<string, unknown>>;
32
- }
33
-
34
- /**
35
- * builds the active view and computes which entries and instances to prune.
36
- *
37
- * layout instances are shared when sibling entries resolve to matching keys. when multiple entries share an
38
- * instance, the parameters from the active entry take precedence.
39
- */
40
- export const computeView = (
41
- cached: readonly PoolEntry[],
42
- pinned: readonly PoolEntry[],
43
- activeKey: string,
44
- ): View => {
45
- const byKey = new Map<string, PlacedNode>();
46
- const roots: PlacedNode[] = [];
47
-
48
- const place = (entry: PoolEntry, active: boolean): void => {
49
- let pool = roots;
50
- for (const matched of entry.match.chain) {
51
- const key = instanceKey(matched, entry.key);
52
- let inst = byKey.get(key);
53
- if (inst === undefined) {
54
- inst = { children: [], instanceKey: key, node: matched.node, params: matched.params };
55
- byKey.set(key, inst);
56
- pool.push(inst);
57
- } else if (active) {
58
- inst.params = matched.params;
59
- }
60
- pool = inst.children;
61
- }
62
- };
63
-
64
- for (const entry of cached) {
65
- place(entry, entry.key === activeKey);
66
- }
67
- for (const entry of pinned) {
68
- place(entry, false);
69
- }
70
-
71
- const active = cached.find((entry) => entry.key === activeKey);
72
- if (active === undefined) {
73
- throw new Error(`stacker: active entry '${activeKey}' is not in the cached set`);
74
- }
75
- const activePath = active.match.chain.map((matched) => instanceKey(matched, active.key));
76
-
77
- return { activePath, roots };
78
- };