@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/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
@@ -1,155 +0,0 @@
1
- import { SimpleEventEmitter } from '@mary-ext/simple-event-emitter';
2
-
3
- import { createPath, resolvePath } from '../url.ts';
4
- import type { PathParts } from '../url.ts';
5
-
6
- import type {
7
- History,
8
- HistoryEntry,
9
- HistoryListener,
10
- HistoryLocation,
11
- HistoryNavigateOptions,
12
- HistoryUpdate,
13
- } from './types.ts';
14
-
15
- const ROOT: PathParts = { hash: '', pathname: '/', search: '' };
16
-
17
- /** options for the memory history constructor. */
18
- export interface MemoryHistoryOptions {
19
- /** initially active entry index. */
20
- readonly index?: number;
21
- /** initial entry relative URLs. */
22
- readonly initialEntries?: readonly string[];
23
- }
24
-
25
- /**
26
- * in-memory history manager for testing.
27
- *
28
- * replicates browser navigation ledger semantics, including history replacement, entry stack pruning, and
29
- * state traversal.
30
- */
31
- export class MemoryHistory implements History {
32
- #entries: HistoryLocation[];
33
- #index: number;
34
- #idSeq = 0;
35
- #keySeq = 0;
36
- #updates = new SimpleEventEmitter<[update: HistoryUpdate]>();
37
-
38
- constructor(options: MemoryHistoryOptions = {}) {
39
- const initialEntries = options.initialEntries ?? ['/'];
40
- this.#entries = initialEntries.map((to, i) =>
41
- this.#make(to, ROOT, this.#nextId(), this.#nextKey(), i, null),
42
- );
43
- this.#index = Math.max(0, Math.min(options.index ?? this.#entries.length - 1, this.#entries.length - 1));
44
- }
45
-
46
- get location(): HistoryLocation {
47
- return this.#current();
48
- }
49
-
50
- get canGoBack(): boolean {
51
- return this.#index > 0;
52
- }
53
-
54
- get canGoForward(): boolean {
55
- return this.#index < this.#entries.length - 1;
56
- }
57
-
58
- entries(): readonly HistoryEntry[] {
59
- return this.#entries.map((location) => ({
60
- id: location.id,
61
- index: location.index,
62
- key: location.key,
63
- sameDocument: true,
64
- state: location.state,
65
- url: createPath(location),
66
- }));
67
- }
68
-
69
- push(to: string, options: HistoryNavigateOptions = {}): void {
70
- const base = this.#current();
71
- this.#index += 1;
72
- const location = this.#make(
73
- to,
74
- base,
75
- this.#nextId(),
76
- this.#nextKey(),
77
- this.#index,
78
- options.state ?? null,
79
- );
80
- this.#entries = [...this.#entries.slice(0, this.#index), location];
81
- this.#emit({ action: 'push', info: options.info, location });
82
- }
83
-
84
- replace(to: string, options: HistoryNavigateOptions = {}): void {
85
- const current = this.#current();
86
- const location = this.#make(to, current, this.#nextId(), current.key, this.#index, options.state ?? null);
87
- this.#entries = this.#entries.with(this.#index, location);
88
- this.#emit({ action: 'replace', info: options.info, location });
89
- }
90
-
91
- traverseTo(key: string): void {
92
- const index = this.#entries.findIndex((entry) => entry.key === key);
93
- if (index === -1) {
94
- throw new Error(`stacker: no history entry with key '${key}'`);
95
- }
96
- this.go(index - this.#index);
97
- }
98
-
99
- go(delta: number): void {
100
- const next = Math.max(0, Math.min(this.#index + delta, this.#entries.length - 1));
101
- if (next === this.#index) {
102
- return;
103
- }
104
- this.#index = next;
105
- this.#emit({ action: 'traverse', info: undefined, location: this.#current() });
106
- }
107
-
108
- back(): void {
109
- this.go(-1);
110
- }
111
-
112
- forward(): void {
113
- this.go(1);
114
- }
115
-
116
- listen(listener: HistoryListener): () => void {
117
- return this.#updates.subscribe(listener);
118
- }
119
-
120
- dispose(): void {
121
- this.#updates = new SimpleEventEmitter();
122
- }
123
-
124
- #nextId(): string {
125
- return `i${this.#idSeq++}`;
126
- }
127
-
128
- #nextKey(): string {
129
- return `k${this.#keySeq++}`;
130
- }
131
-
132
- #make(
133
- to: string,
134
- base: PathParts,
135
- id: string,
136
- key: string,
137
- index: number,
138
- state: unknown,
139
- ): HistoryLocation {
140
- const { hash, pathname, search } = resolvePath(to, base);
141
- return { hash, id, index, key, pathname, search, state };
142
- }
143
-
144
- #current(): HistoryLocation {
145
- const location = this.#entries[this.#index];
146
- if (location === undefined) {
147
- throw new Error('stacker: memory history has no active entry');
148
- }
149
- return location;
150
- }
151
-
152
- #emit(update: HistoryUpdate): void {
153
- this.#updates.emit(update);
154
- }
155
- }
@@ -1,213 +0,0 @@
1
- import type {
2
- History,
3
- HistoryAction,
4
- HistoryEntry,
5
- HistoryListener,
6
- HistoryLocation,
7
- HistoryNavigateOptions,
8
- HistoryScrollBehavior,
9
- HistoryUpdate,
10
- } from './types.ts';
11
-
12
- /** options for navigation-api history. */
13
- export interface NavigationHistoryOptions {
14
- /**
15
- * same-origin destinations the server owns, which the browser should load as a real page rather than the
16
- * router rendering in-app — an OAuth entry point, a server-rendered admin area, a static file. without this
17
- * every same-origin URL is handled in-app, since the browser offers to intercept a navigation whenever the
18
- * origin matches, whatever the destination is.
19
- *
20
- * consulted for pushes and replaces only. a traversal is always handled: declining one loads nothing, it
21
- * just moves the browser to an entry this document never rendered.
22
- *
23
- * @param url destination URL
24
- * @returns true to leave the navigation to the browser
25
- */
26
- readonly ignore?: (url: URL) => boolean;
27
- /** window instance to bind to; defaults to global window. */
28
- readonly window?: Window;
29
- }
30
-
31
- const ENVELOPE = Symbol('stacker.historyInfo');
32
-
33
- interface Envelope {
34
- readonly [ENVELOPE]: true;
35
- readonly info: unknown;
36
- readonly scroll: HistoryScrollBehavior;
37
- }
38
-
39
- const isEnvelope = (value: unknown): value is Envelope =>
40
- typeof value === 'object' && value !== null && ENVELOPE in value;
41
-
42
- const toAction = (type: NavigationType): HistoryAction | undefined => {
43
- switch (type) {
44
- case 'push':
45
- case 'replace':
46
- case 'traverse':
47
- return type;
48
- default:
49
- return undefined;
50
- }
51
- };
52
-
53
- const ignore = (result: NavigationResult): void => {
54
- result.committed?.catch(() => {});
55
- result.finished?.catch(() => {});
56
- };
57
-
58
- /**
59
- * history implementation backed by the web navigation API.
60
- *
61
- * intercepting same-document navigations converts standard page loads into in-app renders. per-revision
62
- * metadata and indices are managed natively by the browser.
63
- */
64
- export class NavigationHistory implements History {
65
- readonly #win: Window;
66
- readonly #nav: Navigation;
67
- readonly #ignore: ((url: URL) => boolean) | undefined;
68
- readonly #listeners = new Set<HistoryListener>();
69
- #location: HistoryLocation;
70
-
71
- constructor(options: NavigationHistoryOptions = {}) {
72
- this.#win = options.window ?? window;
73
- this.#nav = this.#win.navigation;
74
- this.#ignore = options.ignore;
75
- this.#location = this.#read();
76
- this.#nav.addEventListener('navigate', this.#onNavigate);
77
- }
78
-
79
- get location(): HistoryLocation {
80
- return this.#location;
81
- }
82
-
83
- get canGoBack(): boolean {
84
- return this.#nav.canGoBack;
85
- }
86
-
87
- get canGoForward(): boolean {
88
- return this.#nav.canGoForward;
89
- }
90
-
91
- entries(): readonly HistoryEntry[] {
92
- return this.#nav.entries().map((entry) => ({
93
- id: entry.id,
94
- index: entry.index,
95
- key: entry.key,
96
- sameDocument: entry.sameDocument,
97
- state: entry.getState(),
98
- url: toRelative(entry.url),
99
- }));
100
- }
101
-
102
- push(to: string, options: HistoryNavigateOptions = {}): void {
103
- this.#navigate(to, 'push', options);
104
- }
105
-
106
- replace(to: string, options: HistoryNavigateOptions = {}): void {
107
- this.#navigate(to, 'replace', options);
108
- }
109
-
110
- traverseTo(key: string): void {
111
- ignore(this.#nav.traverseTo(key));
112
- }
113
-
114
- go(delta: number): void {
115
- const entries = this.#nav.entries();
116
- const target = entries[Math.max(0, Math.min(this.#location.index + delta, entries.length - 1))];
117
- if (target === undefined || target.key === this.#location.key) {
118
- return;
119
- }
120
- this.traverseTo(target.key);
121
- }
122
-
123
- back(): void {
124
- if (this.#nav.canGoBack) {
125
- ignore(this.#nav.back());
126
- }
127
- }
128
-
129
- forward(): void {
130
- if (this.#nav.canGoForward) {
131
- ignore(this.#nav.forward());
132
- }
133
- }
134
-
135
- listen(listener: HistoryListener): () => void {
136
- this.#listeners.add(listener);
137
- return () => {
138
- this.#listeners.delete(listener);
139
- };
140
- }
141
-
142
- dispose(): void {
143
- this.#nav.removeEventListener('navigate', this.#onNavigate);
144
- this.#listeners.clear();
145
- }
146
-
147
- #navigate(to: string, history: NavigationHistoryBehavior, options: HistoryNavigateOptions): void {
148
- // resolve against the live document URL so a cross-origin destination keeps its origin and reaches
149
- // the browser as a real navigation, rather than being flattened onto this origin's path.
150
- const url = new URL(to, this.#win.location.href).href;
151
- const envelope: Envelope = {
152
- [ENVELOPE]: true,
153
- info: options.info,
154
- scroll: options.scroll ?? 'auto',
155
- };
156
- ignore(this.#nav.navigate(url, { history, info: envelope, state: options.state ?? null }));
157
- }
158
-
159
- #read(): HistoryLocation {
160
- const entry = this.#nav.currentEntry;
161
- if (entry === null) {
162
- throw new Error('stacker: the navigation API has no current entry (an opaque origin?)');
163
- }
164
- const { hash, pathname, search } = new URL(entry.url ?? this.#win.location.href);
165
- return {
166
- hash,
167
- id: entry.id,
168
- index: entry.index,
169
- key: entry.key,
170
- pathname,
171
- search,
172
- state: entry.getState(),
173
- };
174
- }
175
-
176
- readonly #onNavigate = (event: NavigateEvent): void => {
177
- const action = toAction(event.navigationType);
178
- if (action === undefined || !event.canIntercept) {
179
- return;
180
- }
181
- if (event.downloadRequest !== null || event.formData !== null) {
182
- return;
183
- }
184
- // ignored writes load a new document, while an ignored traversal would only desynchronize this one.
185
- if (action !== 'traverse' && this.#ignore?.(new URL(event.destination.url))) {
186
- return;
187
- }
188
-
189
- const envelope: Envelope | undefined = isEnvelope(event.info) ? event.info : undefined;
190
- const info = envelope === undefined ? event.info : envelope.info;
191
- const scroll = envelope?.scroll ?? 'auto';
192
-
193
- // preserving an in-place update also prevents the platform from resetting the active element.
194
- const preserve = scroll === 'preserve';
195
- event.intercept({
196
- focusReset: preserve ? 'manual' : 'after-transition',
197
- scroll: preserve ? 'manual' : 'after-transition',
198
- handler: async () => {
199
- this.#location = this.#read();
200
- const update: HistoryUpdate = { action, info, location: this.#location };
201
- await Promise.all([...this.#listeners].map(async (listener) => listener(update)));
202
- },
203
- });
204
- };
205
- }
206
-
207
- const toRelative = (url: string | null): string | null => {
208
- if (url === null) {
209
- return null;
210
- }
211
- const { hash, pathname, search } = new URL(url);
212
- return `${pathname}${search}${hash}`;
213
- };
@@ -1,133 +0,0 @@
1
- /**
2
- * the type of navigation that produced a history update.
3
- *
4
- * - `push` — a new entry was added.
5
- * - `replace` — the active entry was replaced.
6
- * - `traverse` — navigation occurred to an existing entry.
7
- */
8
- export type HistoryAction = 'push' | 'replace' | 'traverse';
9
-
10
- /** an entry in the browser session history ledger. */
11
- export interface HistoryEntry {
12
- /** unique per-revision identifier. */
13
- readonly id: string;
14
- /** entry position in the ledger. */
15
- readonly index: number;
16
- /** slot identity preserved across replacements. */
17
- readonly key: string;
18
- /** whether traversal to this entry stays within the current document. */
19
- readonly sameDocument: boolean;
20
- /** state associated with the entry. */
21
- readonly state: unknown;
22
- /** entry URL or null if hidden. */
23
- readonly url: string | null;
24
- }
25
-
26
- /** active history entry with parsed URL components. */
27
- export interface HistoryLocation {
28
- /** URL fragment including the leading hash symbol. */
29
- readonly hash: string;
30
- /** per-revision identifier. */
31
- readonly id: string;
32
- /** entry position in the ledger. */
33
- readonly index: number;
34
- /** slot identity. */
35
- readonly key: string;
36
- /** URL pathname starting with a slash. */
37
- readonly pathname: string;
38
- /** URL query string including the leading question mark. */
39
- readonly search: string;
40
- /** state associated with the entry. */
41
- readonly state: unknown;
42
- }
43
-
44
- /**
45
- * how a history write treats the user's place on the page — scroll position and focus, which the browser
46
- * resets together and which a write therefore cannot sensibly split apart.
47
- *
48
- * - `auto` — a new screen. the browser restores scroll on a traversal or resets it on a push, and moves focus
49
- * to the new content.
50
- * - `preserve` — the same screen with different state, like an in-place parameter patch. scroll and focus are
51
- * both left exactly where the user put them.
52
- */
53
- export type HistoryScrollBehavior = 'auto' | 'preserve';
54
-
55
- /** options for history write operations. */
56
- export interface HistoryNavigateOptions {
57
- /** arbitrary metadata passed to history listeners. */
58
- readonly info?: unknown;
59
- /** scroll and focus behavior. */
60
- readonly scroll?: HistoryScrollBehavior;
61
- /** state data associated with the entry. */
62
- readonly state?: unknown;
63
- }
64
-
65
- /** history update details dispatched to listeners. */
66
- export interface HistoryUpdate {
67
- readonly action: HistoryAction;
68
- /** metadata passed to the write operation. */
69
- readonly info: unknown;
70
- readonly location: HistoryLocation;
71
- }
72
-
73
- /**
74
- * history update callback subscriber.
75
- *
76
- * listeners can return a promise to defer scroll restoration and focus resets.
77
- */
78
- export type HistoryListener = (update: HistoryUpdate) => void | Promise<void>;
79
-
80
- /** history manager interface modeled on the web navigation API. */
81
- export interface History {
82
- /** whether a backward entry exists. */
83
- readonly canGoBack: boolean;
84
- /** whether a forward entry exists. */
85
- readonly canGoForward: boolean;
86
- /** active history location. */
87
- readonly location: HistoryLocation;
88
- /** navigates back one entry. */
89
- back(): void;
90
- /** detaches listeners and cleans up resources. */
91
- dispose(): void;
92
- /**
93
- * lists all entries in the ledger.
94
- *
95
- * @returns array of history entries
96
- */
97
- entries(): readonly HistoryEntry[];
98
- /** navigates forward one entry. */
99
- forward(): void;
100
- /**
101
- * navigates by a delta offset.
102
- *
103
- * @param delta number of entries to move
104
- */
105
- go(delta: number): void;
106
- /**
107
- * subscribes to history updates.
108
- *
109
- * @param listener update callback
110
- * @returns unsubscribe function
111
- */
112
- listen(listener: HistoryListener): () => void;
113
- /**
114
- * pushes a new history entry.
115
- *
116
- * @param to destination relative URL
117
- * @param options navigation options
118
- */
119
- push(to: string, options?: HistoryNavigateOptions): void;
120
- /**
121
- * replaces the active history entry.
122
- *
123
- * @param to destination relative URL
124
- * @param options navigation options
125
- */
126
- replace(to: string, options?: HistoryNavigateOptions): void;
127
- /**
128
- * navigates to an existing entry by key.
129
- *
130
- * @param key target entry key
131
- */
132
- traverseTo(key: string): void;
133
- }