@oomfware/stacker 0.1.0 → 0.1.1
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 +16 -0
- package/dist/index.d.mts +11 -1
- package/dist/index.mjs +90 -12
- package/dist/testing.mjs +1 -1
- package/dist/{url-CoOVqRk_.mjs → url-gf-m_-s3.mjs} +9 -1
- package/package.json +2 -7
- package/src/build.ts +0 -53
- package/src/cache.ts +0 -53
- package/src/codec.ts +0 -182
- package/src/history/memory.ts +0 -155
- package/src/history/navigation.ts +0 -213
- package/src/history/types.ts +0 -133
- package/src/index.ts +0 -52
- package/src/keys.ts +0 -41
- package/src/match.ts +0 -180
- package/src/react/context.ts +0 -18
- package/src/react/hooks.ts +0 -178
- package/src/react/link.tsx +0 -61
- package/src/react/outlet.tsx +0 -18
- package/src/react/router-view.tsx +0 -79
- package/src/router.ts +0 -397
- package/src/routes.ts +0 -325
- package/src/testing.ts +0 -2
- package/src/url.ts +0 -41
- package/src/view-model.ts +0 -78
package/README.md
CHANGED
|
@@ -78,6 +78,9 @@ const routes = defineRoutes({
|
|
|
78
78
|
});
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
routes are matched in declaration order, so declare specific paths ahead of broader ones that would
|
|
82
|
+
also match.
|
|
83
|
+
|
|
81
84
|
configure `type` to control page instance lifetimes:
|
|
82
85
|
|
|
83
86
|
```ts
|
|
@@ -110,6 +113,19 @@ route({
|
|
|
110
113
|
path parameters are always required. query parameters without a default or optional codec must be
|
|
111
114
|
present in the URL to match the route.
|
|
112
115
|
|
|
116
|
+
end a path with `*name` to capture the rest of the URL, separators included. a splat also matches
|
|
117
|
+
its bare parent path, where the remainder is empty:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
route({ component: Docs, params: { rest: string() }, path: '/docs/*rest' });
|
|
121
|
+
|
|
122
|
+
// /docs/guide/intro -> { rest: 'guide/intro' }
|
|
123
|
+
// /docs -> { rest: '' }
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
swap `string()` for `nonEmpty()` to reject the empty remainder, which leaves `/docs` to fall through
|
|
127
|
+
to the next matching route.
|
|
128
|
+
|
|
113
129
|
write custom codecs by defining `decode` and `encode` methods:
|
|
114
130
|
|
|
115
131
|
```ts
|
package/dist/index.d.mts
CHANGED
|
@@ -74,6 +74,16 @@ declare const boolean: () => Codec<boolean>;
|
|
|
74
74
|
* @returns the enum codec
|
|
75
75
|
*/
|
|
76
76
|
declare const enumOf: <const V extends readonly string[]>(values: V) => Codec<V[number]>;
|
|
77
|
+
/**
|
|
78
|
+
* creates a codec for a string that rejects the empty value.
|
|
79
|
+
*
|
|
80
|
+
* this is how a splat route demands at least one trailing segment: `/docs/*rest` otherwise matches `/docs`
|
|
81
|
+
* itself with an empty remainder, and rejecting it lets the URL fall through to a later route. ordinary path
|
|
82
|
+
* params can never be empty, so the distinction only matters for splats and query params.
|
|
83
|
+
*
|
|
84
|
+
* @returns the non-empty string codec
|
|
85
|
+
*/
|
|
86
|
+
declare const nonEmpty: () => Codec<string>;
|
|
77
87
|
/**
|
|
78
88
|
* wraps a codec to allow its parameter to be absent.
|
|
79
89
|
*
|
|
@@ -545,4 +555,4 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'
|
|
|
545
555
|
*/
|
|
546
556
|
declare const Link: ({ children, onClick, replace, to, ...rest }: LinkProps) => ReactElement;
|
|
547
557
|
//#endregion
|
|
548
|
-
export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, type HistoryUpdate, type Infer, type InstanceNode, type LayoutConfig, type LayoutNode, type LeafType, Link, type LinkProps, type MatchedNode, NavigationHistory, type NavigationHistoryOptions, type OptionalCodec, Outlet, type ParamsOf, type QueryPatchOf, type ReadonlyURLSearchParams, type ResolvedLeaf, type ResolvedNode, type RouteChildren, type RouteConfig, type RouteLeaf, type RouteMatch, type RouteMeta, type RouteName, type RouteNode, type RouteRegistry, Router, type RouterHooks, type RouterOptions, RouterView, type View, type WhenContext, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|
|
558
|
+
export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, type HistoryUpdate, type Infer, type InstanceNode, type LayoutConfig, type LayoutNode, type LeafType, Link, type LinkProps, type MatchedNode, NavigationHistory, type NavigationHistoryOptions, type OptionalCodec, Outlet, type ParamsOf, type QueryPatchOf, type ReadonlyURLSearchParams, type ResolvedLeaf, type ResolvedNode, type RouteChildren, type RouteConfig, type RouteLeaf, type RouteMatch, type RouteMeta, type RouteName, type RouteNode, type RouteRegistry, Router, type RouterHooks, type RouterOptions, RouterView, type View, type WhenContext, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as parsePath, n as decodeRemainder, r as encodeRemainder, t as createPath } from "./url-gf-m_-s3.mjs";
|
|
2
2
|
import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
|
|
3
3
|
import { Suspense, createContext, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
|
|
4
4
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
@@ -59,6 +59,22 @@ const enumOf = (values) => {
|
|
|
59
59
|
};
|
|
60
60
|
};
|
|
61
61
|
/**
|
|
62
|
+
* creates a codec for a string that rejects the empty value.
|
|
63
|
+
*
|
|
64
|
+
* this is how a splat route demands at least one trailing segment: `/docs/*rest` otherwise matches `/docs`
|
|
65
|
+
* itself with an empty remainder, and rejecting it lets the URL fall through to a later route. ordinary path
|
|
66
|
+
* params can never be empty, so the distinction only matters for splats and query params.
|
|
67
|
+
*
|
|
68
|
+
* @returns the non-empty string codec
|
|
69
|
+
*/
|
|
70
|
+
const nonEmpty = () => ({
|
|
71
|
+
decode: (raw) => raw === "" ? void 0 : raw,
|
|
72
|
+
encode: (value) => {
|
|
73
|
+
if (value === "") throw new Error("stacker: nonEmpty() cannot encode an empty string");
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
/**
|
|
62
78
|
* wraps a codec to allow its parameter to be absent.
|
|
63
79
|
*
|
|
64
80
|
* @param codec the inner codec
|
|
@@ -110,14 +126,40 @@ const layout = (config) => ({
|
|
|
110
126
|
...config
|
|
111
127
|
});
|
|
112
128
|
const PATH_PARAM = /:([A-Za-z_]\w*)/g;
|
|
129
|
+
const SPLAT = /\/\*([A-Za-z_]\w*)$/;
|
|
130
|
+
/**
|
|
131
|
+
* splits a route pattern into the part before its trailing splat and the splat parameter name.
|
|
132
|
+
*
|
|
133
|
+
* @param path the route path pattern
|
|
134
|
+
* @returns the head preceding the splat, and the splat name when the pattern declares one
|
|
135
|
+
*/
|
|
136
|
+
const splitSplat = (path) => {
|
|
137
|
+
const match = SPLAT.exec(path);
|
|
138
|
+
return match === null ? {
|
|
139
|
+
head: path,
|
|
140
|
+
splat: void 0
|
|
141
|
+
} : {
|
|
142
|
+
head: path.slice(0, match.index),
|
|
143
|
+
splat: match[1]
|
|
144
|
+
};
|
|
145
|
+
};
|
|
113
146
|
const pathParamNames = (path) => {
|
|
147
|
+
const { head, splat } = splitSplat(path);
|
|
114
148
|
const names = [];
|
|
115
|
-
for (const match of
|
|
149
|
+
for (const match of head.matchAll(PATH_PARAM)) {
|
|
116
150
|
const name = match[1];
|
|
117
151
|
if (name !== void 0) names.push(name);
|
|
118
152
|
}
|
|
153
|
+
if (splat !== void 0) names.push(splat);
|
|
119
154
|
return names;
|
|
120
155
|
};
|
|
156
|
+
/**
|
|
157
|
+
* rejects a `*` that is not a well-formed trailing splat, so that a typo fails at load time rather than
|
|
158
|
+
* silently compiling into a literal asterisk.
|
|
159
|
+
*/
|
|
160
|
+
const assertSplatPlacement = (key, path) => {
|
|
161
|
+
if (splitSplat(path).head.includes("*")) throw new Error(`stacker: route '${key}' path '${path}' may only use '*' as a named trailing splat, as in '/docs/*rest'`);
|
|
162
|
+
};
|
|
121
163
|
const sameKeySet = (a, b) => {
|
|
122
164
|
if (a.length !== b.length) return false;
|
|
123
165
|
const set = new Set(a);
|
|
@@ -155,6 +197,7 @@ const defineRoutes = (tree) => {
|
|
|
155
197
|
}
|
|
156
198
|
if (leaves.has(key)) throw new Error(`stacker: duplicate route name '${key}'`);
|
|
157
199
|
if (!node.path.startsWith("/")) throw new Error(`stacker: route '${key}' path '${node.path}' must start with '/'`);
|
|
200
|
+
assertSplatPlacement(key, node.path);
|
|
158
201
|
const query = node.query ?? {};
|
|
159
202
|
const ownPathParams = pathParamNames(node.path);
|
|
160
203
|
const declaredParams = Object.keys(params);
|
|
@@ -199,20 +242,30 @@ const resolveMeta = (match, key) => {
|
|
|
199
242
|
const SEGMENT$1 = /:[A-Za-z_]\w*/g;
|
|
200
243
|
const escapeRegExp = (segment) => segment.replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&");
|
|
201
244
|
const compile = (path) => {
|
|
245
|
+
const { head, splat } = splitSplat(path);
|
|
202
246
|
const paramNames = [];
|
|
203
247
|
let pattern = "";
|
|
204
248
|
let lastIndex = 0;
|
|
205
|
-
for (const match of
|
|
249
|
+
for (const match of head.matchAll(SEGMENT$1)) {
|
|
206
250
|
const whole = match[0];
|
|
207
251
|
const at = match.index;
|
|
208
252
|
if (at === void 0) continue;
|
|
209
253
|
paramNames.push(whole.slice(1));
|
|
210
|
-
pattern += `${escapeRegExp(
|
|
254
|
+
pattern += `${escapeRegExp(head.slice(lastIndex, at))}([^/]+)`;
|
|
211
255
|
lastIndex = at + whole.length;
|
|
212
256
|
}
|
|
213
|
-
pattern += escapeRegExp(
|
|
257
|
+
pattern += escapeRegExp(head.slice(lastIndex));
|
|
258
|
+
if (splat !== void 0) {
|
|
259
|
+
paramNames.push(splat);
|
|
260
|
+
return {
|
|
261
|
+
hasSplat: true,
|
|
262
|
+
paramNames,
|
|
263
|
+
regex: new RegExp(`^${pattern}(?:/(.*))?$`)
|
|
264
|
+
};
|
|
265
|
+
}
|
|
214
266
|
const suffix = pattern.endsWith("/") ? "" : "/?";
|
|
215
267
|
return {
|
|
268
|
+
hasSplat: false,
|
|
216
269
|
paramNames,
|
|
217
270
|
regex: new RegExp(`^${pattern}${suffix}$`)
|
|
218
271
|
};
|
|
@@ -222,8 +275,9 @@ var Matcher = class {
|
|
|
222
275
|
#compiled;
|
|
223
276
|
constructor(registry) {
|
|
224
277
|
this.#compiled = [...registry.leaves.values()].map((leaf) => {
|
|
225
|
-
const { paramNames, regex } = compile(leaf.path);
|
|
278
|
+
const { hasSplat, paramNames, regex } = compile(leaf.path);
|
|
226
279
|
return {
|
|
280
|
+
hasSplat,
|
|
227
281
|
leaf,
|
|
228
282
|
paramNames,
|
|
229
283
|
regex
|
|
@@ -238,10 +292,11 @@ var Matcher = class {
|
|
|
238
292
|
rawSearch,
|
|
239
293
|
search
|
|
240
294
|
};
|
|
241
|
-
for (const
|
|
295
|
+
for (const compiled of this.#compiled) {
|
|
296
|
+
const { leaf, regex } = compiled;
|
|
242
297
|
const execed = regex.exec(pathname);
|
|
243
298
|
if (execed === null) continue;
|
|
244
|
-
const raw = this.#rawValues(
|
|
299
|
+
const raw = this.#rawValues(compiled, execed);
|
|
245
300
|
if (raw === void 0) continue;
|
|
246
301
|
const perNode = this.#decodeChain(leaf.chain, raw);
|
|
247
302
|
if (perNode === void 0) continue;
|
|
@@ -266,10 +321,19 @@ var Matcher = class {
|
|
|
266
321
|
};
|
|
267
322
|
}
|
|
268
323
|
}
|
|
269
|
-
#rawValues(paramNames, execed) {
|
|
324
|
+
#rawValues({ hasSplat, paramNames }, execed) {
|
|
325
|
+
const splatIndex = hasSplat ? paramNames.length - 1 : -1;
|
|
270
326
|
const raw = {};
|
|
271
327
|
for (const [i, name] of paramNames.entries()) {
|
|
272
328
|
const value = execed[i + 1];
|
|
329
|
+
if (i === splatIndex) {
|
|
330
|
+
try {
|
|
331
|
+
raw[name] = decodeRemainder(value ?? "");
|
|
332
|
+
} catch {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
273
337
|
if (value === void 0) return;
|
|
274
338
|
try {
|
|
275
339
|
raw[name] = decodeURIComponent(value);
|
|
@@ -465,12 +529,26 @@ var Builder = class {
|
|
|
465
529
|
buildPath(name, params = {}) {
|
|
466
530
|
const leaf = this.#registry.leaves.get(name);
|
|
467
531
|
if (leaf === void 0) throw new Error(`stacker: unknown route '${name}'`);
|
|
468
|
-
const
|
|
532
|
+
const encodeParam = (paramName) => {
|
|
469
533
|
const codec = leaf.params[paramName];
|
|
470
534
|
const value = params[paramName];
|
|
471
535
|
if (codec === void 0 || value === void 0) throw new Error(`stacker: missing path param '${paramName}' for route '${name}'`);
|
|
472
|
-
return
|
|
536
|
+
return codec.encode(value);
|
|
537
|
+
};
|
|
538
|
+
const rejectDotSegments = (segments, paramName) => {
|
|
539
|
+
for (const segment of segments) if (segment === "." || segment === "..") throw new Error(`stacker: path param '${paramName}' for route '${name}' cannot contain a '${segment}' segment`);
|
|
540
|
+
};
|
|
541
|
+
const { head, splat } = splitSplat(leaf.path);
|
|
542
|
+
let pathname = head.replaceAll(SEGMENT, (_full, paramName) => {
|
|
543
|
+
const encoded = encodeParam(paramName);
|
|
544
|
+
rejectDotSegments([encoded], paramName);
|
|
545
|
+
return encodeURIComponent(encoded);
|
|
473
546
|
});
|
|
547
|
+
if (splat !== void 0) {
|
|
548
|
+
const remainder = encodeParam(splat);
|
|
549
|
+
rejectDotSegments(remainder.split("/"), splat);
|
|
550
|
+
if (remainder !== "") pathname += `/${encodeRemainder(remainder)}`;
|
|
551
|
+
}
|
|
474
552
|
const search = new URLSearchParams();
|
|
475
553
|
for (const [paramName, codec] of Object.entries(leaf.query)) {
|
|
476
554
|
const value = params[paramName];
|
|
@@ -1099,4 +1177,4 @@ const Link = ({ children, onClick, replace, to, ...rest }) => {
|
|
|
1099
1177
|
});
|
|
1100
1178
|
};
|
|
1101
1179
|
//#endregion
|
|
1102
|
-
export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|
|
1180
|
+
export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
|
package/dist/testing.mjs
CHANGED
|
@@ -27,6 +27,14 @@ const resolvePath = (to, base) => {
|
|
|
27
27
|
search: resolved.search
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
|
+
/**
|
|
31
|
+
* decodes a splat remainder one segment at a time, so that separators survive decoding.
|
|
32
|
+
*
|
|
33
|
+
* an encoded `%2F` therefore decodes to a literal `/` and is indistinguishable from a real separator.
|
|
34
|
+
*/
|
|
35
|
+
const decodeRemainder = (raw) => raw.split("/").map(decodeURIComponent).join("/");
|
|
36
|
+
/** encodes a splat remainder one segment at a time, the inverse of {@link decodeRemainder}. */
|
|
37
|
+
const encodeRemainder = (value) => value.split("/").map(encodeURIComponent).join("/");
|
|
30
38
|
const createPath = ({ hash, pathname, search }) => {
|
|
31
39
|
let out = pathname || "/";
|
|
32
40
|
if (search && search !== "?") out += search.startsWith("?") ? search : `?${search}`;
|
|
@@ -34,4 +42,4 @@ const createPath = ({ hash, pathname, search }) => {
|
|
|
34
42
|
return out;
|
|
35
43
|
};
|
|
36
44
|
//#endregion
|
|
37
|
-
export { parsePath as n,
|
|
45
|
+
export { resolvePath as a, parsePath as i, decodeRemainder as n, encodeRemainder as r, createPath as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oomfware/stacker",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "type-safe stack router for React",
|
|
5
5
|
"license": "0BSD",
|
|
6
6
|
"repository": {
|
|
@@ -8,12 +8,7 @@
|
|
|
8
8
|
"url": "https://codeberg.org/oomfware/stacker"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
|
-
"dist/"
|
|
12
|
-
"src/",
|
|
13
|
-
"!src/**/*.test.ts",
|
|
14
|
-
"!src/**/*.test.tsx",
|
|
15
|
-
"!src/**/*.test-d.ts",
|
|
16
|
-
"!src/test-support.ts"
|
|
11
|
+
"dist/"
|
|
17
12
|
],
|
|
18
13
|
"type": "module",
|
|
19
14
|
"types": "./dist/index.d.mts",
|
package/src/build.ts
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import { getDefault, isOptional } from './codec.ts';
|
|
2
|
-
import type { BuildParamsOf, RouteName, RouteRegistry } from './routes.ts';
|
|
3
|
-
import { createPath } from './url.ts';
|
|
4
|
-
|
|
5
|
-
const SEGMENT = /:([A-Za-z_]\w*)/g;
|
|
6
|
-
|
|
7
|
-
export type BuildArgs<R, K extends RouteName<R>> =
|
|
8
|
-
Record<never, never> extends BuildParamsOf<R, K>
|
|
9
|
-
? [params?: BuildParamsOf<R, K>]
|
|
10
|
-
: [params: BuildParamsOf<R, K>];
|
|
11
|
-
|
|
12
|
-
export class Builder<R extends RouteRegistry<unknown> = RouteRegistry<unknown>> {
|
|
13
|
-
readonly #registry: R;
|
|
14
|
-
|
|
15
|
-
constructor(registry: R) {
|
|
16
|
-
this.#registry = registry;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
build<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): string {
|
|
20
|
-
return this.buildPath(name, args[0] ?? {});
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
buildPath(name: string, params: Readonly<Record<string, unknown>> = {}): string {
|
|
24
|
-
const leaf = this.#registry.leaves.get(name);
|
|
25
|
-
if (leaf === undefined) {
|
|
26
|
-
throw new Error(`stacker: unknown route '${name}'`);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const pathname = leaf.path.replaceAll(SEGMENT, (_full, paramName: string) => {
|
|
30
|
-
const codec = leaf.params[paramName];
|
|
31
|
-
const value = params[paramName];
|
|
32
|
-
if (codec === undefined || value === undefined) {
|
|
33
|
-
throw new Error(`stacker: missing path param '${paramName}' for route '${name}'`);
|
|
34
|
-
}
|
|
35
|
-
return encodeURIComponent(codec.encode(value));
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
const search = new URLSearchParams();
|
|
39
|
-
for (const [paramName, codec] of Object.entries(leaf.query)) {
|
|
40
|
-
const value = params[paramName];
|
|
41
|
-
if (value === undefined) {
|
|
42
|
-
if (!isOptional(codec) && getDefault(codec) === undefined) {
|
|
43
|
-
throw new Error(`stacker: missing required query param '${paramName}' for route '${name}'`);
|
|
44
|
-
}
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
|
-
search.set(paramName, codec.encode(value));
|
|
48
|
-
}
|
|
49
|
-
const query = search.toString();
|
|
50
|
-
|
|
51
|
-
return createPath({ hash: '', pathname, search: query ? `?${query}` : '' });
|
|
52
|
-
}
|
|
53
|
-
}
|
package/src/cache.ts
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
export interface CacheEntryRef {
|
|
2
|
-
readonly index: number;
|
|
3
|
-
readonly key: string;
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
export interface CachePolicy {
|
|
7
|
-
readonly max: number;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* computes which history entries to keep warm based on active index and recency.
|
|
12
|
-
*
|
|
13
|
-
* retains the active entry plus backward entries using an LRU policy. forward entries are dropped.
|
|
14
|
-
*/
|
|
15
|
-
export const computeCachedKeys = (
|
|
16
|
-
entries: readonly CacheEntryRef[],
|
|
17
|
-
activeIndex: number,
|
|
18
|
-
recency: readonly string[],
|
|
19
|
-
policy: CachePolicy,
|
|
20
|
-
): Set<string> => {
|
|
21
|
-
const cached = new Set<string>();
|
|
22
|
-
|
|
23
|
-
const active = entries.find((entry) => entry.index === activeIndex);
|
|
24
|
-
if (active === undefined) {
|
|
25
|
-
throw new Error(`stacker: no history entry at active index ${activeIndex}`);
|
|
26
|
-
}
|
|
27
|
-
cached.add(active.key);
|
|
28
|
-
|
|
29
|
-
const backward = new Map<string, CacheEntryRef>();
|
|
30
|
-
for (const entry of entries) {
|
|
31
|
-
if (entry.index < activeIndex) {
|
|
32
|
-
backward.set(entry.key, entry);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
let kept = 0;
|
|
37
|
-
const take = (key: string): void => {
|
|
38
|
-
if (kept >= policy.max || cached.has(key) || !backward.has(key)) {
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
cached.add(key);
|
|
42
|
-
kept += 1;
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
for (const key of recency) {
|
|
46
|
-
take(key);
|
|
47
|
-
}
|
|
48
|
-
for (const entry of [...backward.values()].toSorted((a, b) => b.index - a.index)) {
|
|
49
|
-
take(entry.key);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
return cached;
|
|
53
|
-
};
|
package/src/codec.ts
DELETED
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
// #region codec primitive
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* a bidirectional codec for a single route parameter.
|
|
5
|
-
*
|
|
6
|
-
* returning `undefined` from `decode` signals validation failure, which causes the matcher to skip the
|
|
7
|
-
* candidate route.
|
|
8
|
-
*/
|
|
9
|
-
export interface Codec<T> {
|
|
10
|
-
/**
|
|
11
|
-
* parses a raw URL segment.
|
|
12
|
-
*
|
|
13
|
-
* @param raw the percent-decoded path segment or query value
|
|
14
|
-
* @returns the decoded value, or `undefined` if the segment is invalid
|
|
15
|
-
*/
|
|
16
|
-
decode(raw: string): T | undefined;
|
|
17
|
-
/**
|
|
18
|
-
* serializes a value to a raw URL segment.
|
|
19
|
-
*
|
|
20
|
-
* @param value the value to serialize
|
|
21
|
-
* @returns the raw string value
|
|
22
|
-
*/
|
|
23
|
-
encode(value: T): string;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const OPTIONAL: unique symbol = Symbol('stacker.optional');
|
|
27
|
-
const DEFAULT: unique symbol = Symbol('stacker.default');
|
|
28
|
-
|
|
29
|
-
/** a codec whose parameter may be absent. */
|
|
30
|
-
export interface OptionalCodec<T> extends Codec<T> {
|
|
31
|
-
readonly [OPTIONAL]: true;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** a codec whose parameter has a default fallback. */
|
|
35
|
-
export interface DefaultedCodec<T> extends Codec<T> {
|
|
36
|
-
readonly [DEFAULT]: T;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** extracts the value type a codec decodes to. */
|
|
40
|
-
export type Infer<C> = C extends Codec<infer T> ? T : never;
|
|
41
|
-
|
|
42
|
-
// #endregion
|
|
43
|
-
|
|
44
|
-
// #region type-level param shapes
|
|
45
|
-
|
|
46
|
-
// `Codec<T>` is invariant, so the bound must use `any`; `const` generics preserve each exact codec type.
|
|
47
|
-
// oxlint-disable-next-line typescript/no-explicit-any -- invariance bound, see note above
|
|
48
|
-
export type CodecRecord = { readonly [name: string]: Codec<any> };
|
|
49
|
-
|
|
50
|
-
type Prettify<T> = { [K in keyof T]: T[K] } & {};
|
|
51
|
-
|
|
52
|
-
type AnyOptional = { readonly [OPTIONAL]: true };
|
|
53
|
-
type AnyDefaulted = { readonly [DEFAULT]: unknown };
|
|
54
|
-
|
|
55
|
-
type OptionalKeys<P extends CodecRecord> = {
|
|
56
|
-
[K in keyof P]: P[K] extends AnyOptional ? K : never;
|
|
57
|
-
}[keyof P];
|
|
58
|
-
|
|
59
|
-
type DefaultedKeys<P extends CodecRecord> = {
|
|
60
|
-
[K in keyof P]: P[K] extends AnyDefaulted ? K : never;
|
|
61
|
-
}[keyof P];
|
|
62
|
-
|
|
63
|
-
export type DecodeShape<P extends CodecRecord> = Prettify<
|
|
64
|
-
{ [K in Exclude<keyof P, OptionalKeys<P>>]: Infer<P[K]> } & { [K in OptionalKeys<P>]?: Infer<P[K]> }
|
|
65
|
-
>;
|
|
66
|
-
|
|
67
|
-
export type BuildShape<P extends CodecRecord> = Prettify<
|
|
68
|
-
{ [K in Exclude<keyof P, DefaultedKeys<P> | OptionalKeys<P>>]: Infer<P[K]> } & {
|
|
69
|
-
[K in DefaultedKeys<P> | OptionalKeys<P>]?: Infer<P[K]>;
|
|
70
|
-
}
|
|
71
|
-
>;
|
|
72
|
-
|
|
73
|
-
// #endregion
|
|
74
|
-
|
|
75
|
-
// #region primitives
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* creates a codec for a string segment.
|
|
79
|
-
*
|
|
80
|
-
* @returns the string codec
|
|
81
|
-
*/
|
|
82
|
-
export const string = (): Codec<string> => ({
|
|
83
|
-
decode: (raw) => raw,
|
|
84
|
-
encode: (value) => value,
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* creates a codec for a safe integer.
|
|
89
|
-
*
|
|
90
|
-
* @returns the integer codec
|
|
91
|
-
*/
|
|
92
|
-
export const integer = (): Codec<number> => ({
|
|
93
|
-
decode: (raw) => {
|
|
94
|
-
// reject leading zeros, `-0`, a leading `+`, exponents, and decimals to ensure round-tripping.
|
|
95
|
-
if (!/^(?:0|-[1-9]\d*|[1-9]\d*)$/.test(raw)) {
|
|
96
|
-
return undefined;
|
|
97
|
-
}
|
|
98
|
-
const value = Number(raw);
|
|
99
|
-
return Number.isSafeInteger(value) ? value : undefined;
|
|
100
|
-
},
|
|
101
|
-
encode: (value) => {
|
|
102
|
-
if (!Number.isSafeInteger(value) || Object.is(value, -0)) {
|
|
103
|
-
throw new Error(`stacker: integer() cannot encode ${value}`);
|
|
104
|
-
}
|
|
105
|
-
return String(value);
|
|
106
|
-
},
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* creates a codec for a boolean value.
|
|
111
|
-
*
|
|
112
|
-
* @returns the boolean codec
|
|
113
|
-
*/
|
|
114
|
-
export const boolean = (): Codec<boolean> => ({
|
|
115
|
-
decode: (raw) => {
|
|
116
|
-
switch (raw) {
|
|
117
|
-
case 'false': {
|
|
118
|
-
return false;
|
|
119
|
-
}
|
|
120
|
-
case 'true': {
|
|
121
|
-
return true;
|
|
122
|
-
}
|
|
123
|
-
default: {
|
|
124
|
-
return undefined;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
},
|
|
128
|
-
encode: (value) => (value ? 'true' : 'false'),
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* creates a codec for a fixed set of string values.
|
|
133
|
-
*
|
|
134
|
-
* @param values the allowed string values
|
|
135
|
-
* @returns the enum codec
|
|
136
|
-
*/
|
|
137
|
-
export const enumOf = <const V extends readonly string[]>(values: V): Codec<V[number]> => {
|
|
138
|
-
const set: ReadonlySet<string> = new Set(values);
|
|
139
|
-
return {
|
|
140
|
-
decode: (raw) => (set.has(raw) ? raw : undefined),
|
|
141
|
-
encode: (value) => value,
|
|
142
|
-
};
|
|
143
|
-
};
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* wraps a codec to allow its parameter to be absent.
|
|
147
|
-
*
|
|
148
|
-
* @param codec the inner codec
|
|
149
|
-
* @returns the optional codec
|
|
150
|
-
*/
|
|
151
|
-
export const optional = <T>(codec: Codec<T>): OptionalCodec<T> => ({
|
|
152
|
-
decode: (raw) => codec.decode(raw),
|
|
153
|
-
encode: (value) => codec.encode(value),
|
|
154
|
-
[OPTIONAL]: true,
|
|
155
|
-
});
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* wraps a codec with a default value.
|
|
159
|
-
*
|
|
160
|
-
* @param codec the inner codec
|
|
161
|
-
* @param fallback the default value
|
|
162
|
-
* @returns the defaulted codec
|
|
163
|
-
*/
|
|
164
|
-
export const withDefault = <T>(codec: Codec<T>, fallback: T): DefaultedCodec<T> => ({
|
|
165
|
-
decode: (raw) => codec.decode(raw),
|
|
166
|
-
encode: (value) => codec.encode(value),
|
|
167
|
-
[DEFAULT]: fallback,
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
// #endregion
|
|
171
|
-
|
|
172
|
-
// #region runtime reflection
|
|
173
|
-
|
|
174
|
-
export const isOptional = (codec: Codec<unknown>): codec is OptionalCodec<unknown> => {
|
|
175
|
-
return OPTIONAL in codec;
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
export const getDefault = (codec: Codec<unknown>): readonly [unknown] | undefined => {
|
|
179
|
-
return DEFAULT in codec ? [(codec as DefaultedCodec<unknown>)[DEFAULT]] : undefined;
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
// #endregion
|