@baukit/preferences-core 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Koss
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # @baukit/preferences-core
2
+
3
+ `@baukit/preferences-core` defines typed preferences and their update behavior. Products provide
4
+ the definitions, storage adapter, and any effects caused by a change.
5
+
6
+ ## Update model
7
+
8
+ Each definition supplies a key, default value, normalizer, and scope. Hydration reads the store,
9
+ normalizes every stored field, and fills omitted fields from their definitions. A local update is
10
+ visible immediately, then written as a patch. If the write fails, the controller restores the
11
+ previous visible values and records the error.
12
+
13
+ Call `switchIdentity` with the next identity's store when the authenticated subject changes. The
14
+ controller publishes defaults before it starts the new read. A slow read or write for the old
15
+ identity cannot put that identity's preferences back into visible state, and a reported
16
+ side-effect failure that belongs to the replaced identity does not land on the new one.
17
+
18
+ Call `stop()` when whatever owns `onVisibleChange` goes away, such as a React provider
19
+ unmounting. In-flight work still settles and `getState()` stays accurate; the callback just stops
20
+ firing. Consumers do not need their own mounted flag around `onVisibleChange`.
21
+
22
+ Wire codecs distinguish three states by checking whether a payload owns a field:
23
+
24
+ - absent means an older peer did not send the setting, so no patch is made;
25
+ - null means the peer explicitly cleared a nullable setting;
26
+ - value contains the setting's decoded value.
27
+
28
+ An optional TypeScript property does not carry this distinction by itself.
29
+
30
+ ## Side-effect ordering
31
+
32
+ The default policy is `after-persistence`. Locale changes, permission prompts, reminder
33
+ rescheduling, analytics changes, and network-query enablement should run only after the local
34
+ write succeeds. Every hook declares `onError: "report" | "ignore"`. A reported effect error stays
35
+ in controller state, while the persisted and visible preference remains unchanged.
36
+
37
+ Some visual changes need an immediate preview. A definition can opt into
38
+ `preview-with-rollback`, provide the preview operation, and provide its inverse. The controller
39
+ runs that rollback if preview or persistence fails. Its optional `afterPersistence` hook still
40
+ runs only after the write.
41
+
42
+ ## Storage adapter tests
43
+
44
+ Adapters implement `PreferenceStore.read` and `PreferenceStore.patch`. Import
45
+ `describePreferenceStoreContract` from `@baukit/preferences-core/vitest` to run the shared Vitest
46
+ contract. `InMemoryPreferenceStore` is suitable for tests and small in-process consumers.
47
+
48
+ `RepositoryPreferenceStore` (or `createRepositoryPreferenceStore`) adapts a repository keyed by a
49
+ subject id, which is how most products already store a settings row. Give it the repository, the
50
+ subject id, and the two projections:
51
+
52
+ ```ts
53
+ const store = createRepositoryPreferenceStore({
54
+ repository: repositories.settings,
55
+ subjectId: userId,
56
+ toValues: (record) => ({ mode: record.theme, accent: record.accent_color }),
57
+ toRecordPatch: (patch) => ({
58
+ ...(patch.mode === undefined ? {} : { theme: patch.mode }),
59
+ ...(patch.accent === undefined ? {} : { accent_color: patch.accent }),
60
+ }),
61
+ });
62
+ ```
63
+
64
+ `toRecordPatch` must omit keys the patch does not carry, so an untouched preference is never
65
+ written back. `read` resolves to `undefined` when the repository returns `null` or `undefined` for
66
+ that subject, which is what makes the controller fall back to definition defaults.
67
+
68
+ ## Boundaries
69
+
70
+ This package does not generate SQL, choose a storage schema, run migrations, or render a settings
71
+ interface. Products still decide which preferences exist, where each scope is stored, what users
72
+ see, and how synchronized payloads reach a server.
@@ -0,0 +1,30 @@
1
+ import { type PreferenceKey, type PreferenceRegistry } from './definitions.js';
2
+ import type { PreferenceStore } from './store.js';
3
+ import type { OptionalWireValue } from './wire.js';
4
+ export type PreferenceControllerStatus = 'idle' | 'hydrating' | 'ready';
5
+ export interface PreferenceControllerState<TValues extends object> {
6
+ readonly values: TValues;
7
+ readonly status: PreferenceControllerStatus;
8
+ readonly error: Error | null;
9
+ }
10
+ export interface PreferenceController<TValues extends object> {
11
+ getState(): PreferenceControllerState<TValues>;
12
+ hydrate(): Promise<TValues>;
13
+ update(patch: Partial<TValues>): Promise<TValues>;
14
+ applyWireValue<TKey extends PreferenceKey<TValues>>(key: TKey, value: OptionalWireValue<Exclude<TValues[TKey], null>>): Promise<TValues>;
15
+ switchIdentity(store: PreferenceStore<TValues>): Promise<TValues>;
16
+ /**
17
+ * Stops publishing to `onVisibleChange`. Call it when the consumer that owns the
18
+ * callback goes away, such as a React provider unmounting. In-flight reads and
19
+ * writes still settle and still update `getState()`; they just stop being
20
+ * published. Stopping is permanent for this controller instance.
21
+ */
22
+ stop(): void;
23
+ }
24
+ export interface CreatePreferenceControllerOptions<TValues extends object> {
25
+ readonly definitions: PreferenceRegistry<TValues>;
26
+ readonly store: PreferenceStore<TValues>;
27
+ readonly onVisibleChange: (values: TValues) => void;
28
+ }
29
+ export declare function createPreferenceController<TValues extends object>(options: CreatePreferenceControllerOptions<TValues>): PreferenceController<TValues>;
30
+ //# sourceMappingURL=controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../src/controller.ts"],"names":[],"mappings":"AAA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AQ,CAAC,eAAe,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CACrD;AAiOD,wBAAgB,0BAA0B,CAAC,OAAO,SAAS,MAAM,EAC/D,OAAO,EAAE,iCAAiC,CAAC,OAAO,CAAC,GAClD,oBAAoB,CAAC,OAAO,CAAC,CAE/B"}
@@ -0,0 +1,186 @@
1
+ import { normalizePreferences, } from './definitions.js';
2
+ class DefaultPreferenceController {
3
+ #definitions;
4
+ #onVisibleChange;
5
+ #store;
6
+ #state;
7
+ #identityRevision = 0;
8
+ #stopped = false;
9
+ constructor(options) {
10
+ this.#definitions = options.definitions;
11
+ this.#store = options.store;
12
+ this.#onVisibleChange = options.onVisibleChange;
13
+ this.#state = {
14
+ values: normalizePreferences(this.#definitions, undefined),
15
+ status: 'idle',
16
+ error: null,
17
+ };
18
+ }
19
+ getState() {
20
+ return this.#state;
21
+ }
22
+ async hydrate() {
23
+ const revision = this.#identityRevision;
24
+ this.#setState({ ...this.#state, status: 'hydrating', error: null });
25
+ try {
26
+ const stored = await this.#store.read();
27
+ const values = normalizePreferences(this.#definitions, stored);
28
+ if (!this.#setVisible(values, 'ready', null, revision)) {
29
+ return this.#state.values;
30
+ }
31
+ return values;
32
+ }
33
+ catch (error) {
34
+ const values = normalizePreferences(this.#definitions, undefined);
35
+ this.#setVisible(values, 'ready', asError(error), revision);
36
+ throw asError(error);
37
+ }
38
+ }
39
+ async update(patch) {
40
+ const revision = this.#identityRevision;
41
+ const store = this.#store;
42
+ const previousValues = this.#state.values;
43
+ const normalizedPatch = this.#normalizePatch(patch);
44
+ const values = { ...previousValues, ...normalizedPatch };
45
+ const changedKeys = this.#changedKeys(previousValues, values, normalizedPatch);
46
+ this.#setVisible(values, 'ready', null, revision);
47
+ const previewed = [];
48
+ let persisted;
49
+ try {
50
+ for (const key of changedKeys) {
51
+ const effect = this.#definitions[key].sideEffect;
52
+ if (effect?.mode === 'preview-with-rollback') {
53
+ previewed.push(key);
54
+ try {
55
+ await effect.preview(this.#effectContext(key, previousValues, values));
56
+ }
57
+ catch (error) {
58
+ if (effect.onError === 'report') {
59
+ throw error;
60
+ }
61
+ }
62
+ }
63
+ }
64
+ persisted = normalizePreferences(this.#definitions, await store.patch(normalizedPatch));
65
+ }
66
+ catch (error) {
67
+ const updateError = asError(error);
68
+ const rollbackError = await this.#rollbackPreviews(previewed, previousValues, values);
69
+ const reportedError = rollbackError
70
+ ? new AggregateError([updateError, rollbackError], 'Preference update and preview rollback failed')
71
+ : updateError;
72
+ this.#setVisible(previousValues, 'ready', reportedError, revision);
73
+ throw reportedError;
74
+ }
75
+ if (!this.#setVisible(persisted, 'ready', null, revision)) {
76
+ await this.#rollbackPreviews(previewed, previousValues, values);
77
+ return this.#state.values;
78
+ }
79
+ await this.#runPersistedEffects(changedKeys, previousValues, persisted, revision);
80
+ return persisted;
81
+ }
82
+ applyWireValue(key, value) {
83
+ if (value.state === 'absent') {
84
+ return Promise.resolve(this.#state.values);
85
+ }
86
+ const patch = {
87
+ [key]: value.state === 'null' ? null : value.value,
88
+ };
89
+ return this.update(patch);
90
+ }
91
+ switchIdentity(store) {
92
+ this.#identityRevision += 1;
93
+ this.#store = store;
94
+ const defaults = normalizePreferences(this.#definitions, undefined);
95
+ this.#setVisible(defaults, 'idle', null);
96
+ return this.hydrate();
97
+ }
98
+ stop() {
99
+ this.#stopped = true;
100
+ }
101
+ #setState(state) {
102
+ this.#state = state;
103
+ }
104
+ #setVisible(values, status, error, revision = this.#identityRevision) {
105
+ if (revision !== this.#identityRevision) {
106
+ return false;
107
+ }
108
+ this.#state = { values, status, error };
109
+ if (!this.#stopped) {
110
+ this.#onVisibleChange(values);
111
+ }
112
+ return true;
113
+ }
114
+ #normalizePatch(patch) {
115
+ const normalized = {};
116
+ for (const key of Object.keys(patch)) {
117
+ if (!Object.hasOwn(this.#definitions, key)) {
118
+ throw new TypeError(`Unknown preference key: ${key}`);
119
+ }
120
+ const typedKey = key;
121
+ normalized[key] = this.#definitions[typedKey].normalize(patch[typedKey]);
122
+ }
123
+ return normalized;
124
+ }
125
+ #changedKeys(previousValues, values, patch) {
126
+ return Object.keys(patch).filter((key) => !Object.is(previousValues[key], values[key]));
127
+ }
128
+ #effectContext(key, previousValues, values) {
129
+ return {
130
+ key,
131
+ previousValue: previousValues[key],
132
+ value: values[key],
133
+ previousValues,
134
+ values,
135
+ };
136
+ }
137
+ async #rollbackPreviews(keys, previousValues, values) {
138
+ let firstError = null;
139
+ for (const key of [...keys].reverse()) {
140
+ const effect = this.#definitions[key].sideEffect;
141
+ if (effect?.mode !== 'preview-with-rollback') {
142
+ continue;
143
+ }
144
+ try {
145
+ await effect.rollback(this.#effectContext(key, previousValues, values));
146
+ }
147
+ catch (error) {
148
+ firstError ??= asError(error);
149
+ }
150
+ }
151
+ return firstError;
152
+ }
153
+ async #runPersistedEffects(keys, previousValues, values, revision) {
154
+ for (const key of keys) {
155
+ const effect = this.#definitions[key].sideEffect;
156
+ if (!effect) {
157
+ continue;
158
+ }
159
+ const run = effect.mode === 'after-persistence' ? effect.run : effect.afterPersistence;
160
+ if (!run) {
161
+ continue;
162
+ }
163
+ try {
164
+ await run(this.#effectContext(key, previousValues, values));
165
+ }
166
+ catch (error) {
167
+ if (effect.onError === 'report') {
168
+ const effectError = asError(error);
169
+ if (revision === this.#identityRevision) {
170
+ this.#setState({ ...this.#state, error: effectError });
171
+ }
172
+ throw effectError;
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+ function asError(reason) {
179
+ return reason instanceof Error
180
+ ? reason
181
+ : new Error('Preference operation failed', { cause: reason });
182
+ }
183
+ export function createPreferenceController(options) {
184
+ return new DefaultPreferenceController(options);
185
+ }
186
+ //# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.js","sourceRoot":"","sources":["../src/controller.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,GAIrB,MAAM,kBAAkB,CAAC;AAoC1B,MAAM,2BAA2B;IACtB,YAAY,C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QAC5B,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,IAAI,KAAK,CAAC,6BAA6B,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,OAAmD;IAEnD,OAAO,IAAI,2BAA2B,CAAC,OAAO,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,36 @@
1
+ export type PreferenceScope = 'device' | 'identity' | 'synced';
2
+ export type PreferenceSideEffectFailurePolicy = 'ignore' | 'report';
3
+ export interface PreferenceSideEffectContext<TKey extends string, TValue, TValues extends object> {
4
+ readonly key: TKey;
5
+ readonly previousValue: TValue;
6
+ readonly value: TValue;
7
+ readonly previousValues: TValues;
8
+ readonly values: TValues;
9
+ }
10
+ export interface AfterPersistencePreferenceSideEffect<TKey extends string, TValue, TValues extends object> {
11
+ readonly mode: 'after-persistence';
12
+ readonly onError: PreferenceSideEffectFailurePolicy;
13
+ readonly run: (context: PreferenceSideEffectContext<TKey, TValue, TValues>) => Promise<void> | void;
14
+ }
15
+ export interface PreviewPreferenceSideEffect<TKey extends string, TValue, TValues extends object> {
16
+ readonly mode: 'preview-with-rollback';
17
+ readonly onError: PreferenceSideEffectFailurePolicy;
18
+ readonly preview: (context: PreferenceSideEffectContext<TKey, TValue, TValues>) => Promise<void> | void;
19
+ readonly rollback: (context: PreferenceSideEffectContext<TKey, TValue, TValues>) => Promise<void> | void;
20
+ readonly afterPersistence?: (context: PreferenceSideEffectContext<TKey, TValue, TValues>) => Promise<void> | void;
21
+ }
22
+ export type PreferenceSideEffect<TKey extends string, TValue, TValues extends object> = AfterPersistencePreferenceSideEffect<TKey, TValue, TValues> | PreviewPreferenceSideEffect<TKey, TValue, TValues>;
23
+ export interface PreferenceDefinition<TKey extends string, TValue, TValues extends object = Record<TKey, TValue>> {
24
+ readonly key: TKey;
25
+ readonly defaultValue: TValue;
26
+ readonly normalize: (value: unknown) => TValue;
27
+ readonly scope: PreferenceScope;
28
+ readonly sideEffect?: PreferenceSideEffect<TKey, TValue, TValues>;
29
+ }
30
+ export type PreferenceKey<TValues extends object> = Extract<keyof TValues, string>;
31
+ export type PreferenceRegistry<TValues extends object> = {
32
+ readonly [TKey in PreferenceKey<TValues>]: PreferenceDefinition<TKey, TValues[TKey], TValues>;
33
+ };
34
+ export declare function definePreferenceRegistry<TValues extends object>(registry: PreferenceRegistry<TValues>): PreferenceRegistry<TValues>;
35
+ export declare function normalizePreferences<TValues extends object>(definitions: PreferenceRegistry<TValues>, input: Partial<TValues> | undefined): TValues;
36
+ //# sourceMappingURL=definitions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definitions.d.ts","sourceRoot":"","sources":["../src/definitions.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,UAAU,GAAG,QAAQ,CAAC;AAE/D,MAAM,MAAM,iCAAiC,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAEpE,MAAM,WAAW,2BAA2B,CAAC,IAAI,SAAS,MAAM,EAAE,MAAM,EAAE,OAAO,SAAS,MAAM;IAC9F,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC;IACnB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,oCAAoC,CACnD,IAAI,SAAS,MAAM,EACnB,MAAM,EACN,OAAO,SAAS,MAAM;IAEtB,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,iCAAiC,CAAC;IACpD,QAAQ,CAAC,GAAG,EAAE,CACZ,OAAO,EAAE,2BAA2B,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,KACxD,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAA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BAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;CACnE;AAED,MAAM,MAAM,aAAa,CAAC,OAAO,SAAS,MAAM,IAAI,OAAO,CAAC,MAAM,OAAO,EAAE,MAAM,CAAC,CAAC;AAEnF,MAAM,MAAM,kBAAkB,CAAC,OAAO,SAAS,MAAM,IAAI;IACvD,QAAQ,EAAE,IAAI,IAAI,aAAa,CAAC,OAAO,CAAC,GAAG,oBAAoB,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;CAC9F,CAAC;AAEF,wBAAgB,wBAAwB,CAAC,OAAO,SAAS,MAAM,EAC7D,QAAQ,EAAE,kBAAkB,CAAC,OAAO,CAAC,GACpC,kBAAkB,CAAC,OAAO,CAAC,CAE7B;AAED,wBAAgB,oBAAoB,CAAC,OAAO,SAAS,MAAM,EACzD,WAAW,EAAE,kBAAkB,CAAC,OAAO,CAAC,EACxC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,SAAS,GAClC,OAAO,CAQT"}
@@ -0,0 +1,13 @@
1
+ export function definePreferenceRegistry(registry) {
2
+ return registry;
3
+ }
4
+ export function normalizePreferences(definitions, input) {
5
+ const normalized = {};
6
+ for (const key of Object.keys(definitions)) {
7
+ const definition = definitions[key];
8
+ const value = input && Object.hasOwn(input, key) ? input[key] : definition.defaultValue;
9
+ normalized[key] = definition.normalize(value);
10
+ }
11
+ return normalized;
12
+ }
13
+ //# sourceMappingURL=definitions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../src/definitions.ts"],"names":[],"mappings":"AA4DA,MAAM,UAAU,wBAAwB,CACtC,QAAqC;IAErC,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,WAAwC,EACxC,KAAmC;IAEnC,MAAM,UAAU,GAA4B,EAAE,CAAC;IAC/C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAA6B,EAAE,CAAC;QACvE,MAAM,UAAU,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,MAAM,KAAK,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,YAAY,CAAC;QACxF,UAAU,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,UAAqB,CAAC;AAC/B,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from './controller.js';
2
+ export * from './definitions.js';
3
+ export * from './store.js';
4
+ export * from './wire.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './controller.js';
2
+ export * from './definitions.js';
3
+ export * from './store.js';
4
+ export * from './wire.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,43 @@
1
+ export interface PreferenceStore<TValues extends object> {
2
+ read(): Promise<TValues | undefined>;
3
+ patch(patch: Partial<TValues>): Promise<TValues>;
4
+ }
5
+ /**
6
+ * The slice of a record-keyed repository this package needs. Products usually already
7
+ * have a repository of this shape for the row that holds a subject's settings.
8
+ *
9
+ * @typeParam TSubjectId - identifier the repository is keyed by, such as a user id.
10
+ * @typeParam TRecord - the stored record.
11
+ * @typeParam TRecordPatch - the partial record the repository accepts on write.
12
+ */
13
+ export interface PreferenceRecordRepository<TSubjectId, TRecord, TRecordPatch> {
14
+ get(subjectId: TSubjectId): Promise<TRecord | null | undefined>;
15
+ upsert(subjectId: TSubjectId, patch: TRecordPatch): Promise<TRecord>;
16
+ }
17
+ export interface RepositoryPreferenceStoreOptions<TValues extends object, TSubjectId, TRecord, TRecordPatch> {
18
+ readonly repository: PreferenceRecordRepository<TSubjectId, TRecord, TRecordPatch>;
19
+ readonly subjectId: TSubjectId;
20
+ /** Projects a stored record onto preference values. */
21
+ readonly toValues: (record: TRecord) => TValues;
22
+ /** Projects a preference patch onto the record patch the repository accepts. */
23
+ readonly toRecordPatch: (patch: Partial<TValues>) => TRecordPatch;
24
+ }
25
+ /**
26
+ * Adapts a record-keyed repository to {@link PreferenceStore}. It owns the mapping
27
+ * between preference values and stored columns, so the controller never sees the
28
+ * record shape and the repository never sees preference keys.
29
+ */
30
+ export declare class RepositoryPreferenceStore<TValues extends object, TSubjectId, TRecord, TRecordPatch> implements PreferenceStore<TValues> {
31
+ #private;
32
+ constructor(options: RepositoryPreferenceStoreOptions<TValues, TSubjectId, TRecord, TRecordPatch>);
33
+ read(): Promise<TValues | undefined>;
34
+ patch(patch: Partial<TValues>): Promise<TValues>;
35
+ }
36
+ export declare function createRepositoryPreferenceStore<TValues extends object, TSubjectId, TRecord, TRecordPatch>(options: RepositoryPreferenceStoreOptions<TValues, TSubjectId, TRecord, TRecordPatch>): PreferenceStore<TValues>;
37
+ export declare class InMemoryPreferenceStore<TValues extends object> implements PreferenceStore<TValues> {
38
+ #private;
39
+ constructor(defaults: TValues, initialValues?: TValues);
40
+ read(): Promise<TValues | undefined>;
41
+ patch(patch: Partial<TValues>): Promise<TValues>;
42
+ }
43
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store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,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;CAIvD;AAED,wBAAgB,+BAA+B,CAC7C,OAAO,SAAS,MAAM,EACtB,UAAU,EACV,OAAO,EACP,YAAY,EAEZ,OAAO,EAAE,gCAAgC,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,CAAC,GACpF,eAAe,CAAC,OAAO,CAAC,CAE1B;AAED,qBAAa,uBAAuB,CAAC,OAAO,SAAS,MAAM,CAAE,YAAW,eAAe,CAAC,OAAO,CAAC;;gBAIlF,QAAQ,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,OAAO;IAKtD,IAAI,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC;IAIpC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;CAIjD"}
package/dist/store.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Adapts a record-keyed repository to {@link PreferenceStore}. It owns the mapping
3
+ * between preference values and stored columns, so the controller never sees the
4
+ * record shape and the repository never sees preference keys.
5
+ */
6
+ export class RepositoryPreferenceStore {
7
+ #repository;
8
+ #subjectId;
9
+ #toValues;
10
+ #toRecordPatch;
11
+ constructor(options) {
12
+ this.#repository = options.repository;
13
+ this.#subjectId = options.subjectId;
14
+ this.#toValues = options.toValues;
15
+ this.#toRecordPatch = options.toRecordPatch;
16
+ }
17
+ async read() {
18
+ const record = await this.#repository.get(this.#subjectId);
19
+ return record == null ? undefined : this.#toValues(record);
20
+ }
21
+ async patch(patch) {
22
+ const record = await this.#repository.upsert(this.#subjectId, this.#toRecordPatch(patch));
23
+ return this.#toValues(record);
24
+ }
25
+ }
26
+ export function createRepositoryPreferenceStore(options) {
27
+ return new RepositoryPreferenceStore(options);
28
+ }
29
+ export class InMemoryPreferenceStore {
30
+ #defaults;
31
+ #values;
32
+ constructor(defaults, initialValues) {
33
+ this.#defaults = { ...defaults };
34
+ this.#values = initialValues ? { ...initialValues } : undefined;
35
+ }
36
+ read() {
37
+ return Promise.resolve(this.#values ? { ...this.#values } : undefined);
38
+ }
39
+ patch(patch) {
40
+ this.#values = { ...this.#defaults, ...this.#values, ...patch };
41
+ return Promise.resolve({ ...this.#values });
42
+ }
43
+ }
44
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAgCA;;;;GAIG;AACH,MAAM,OAAO,yBAAyB;IAM3B,WAAW,CAAgE;IAC3E,UAAU,CAAa;IACvB,SAAS,CAA+B;IACxC,cAAc,CAA4C;IAEnE,YACE,OAAqF;QAErF,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC;QAClC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC3D,OAAO,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAC7D,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,KAAuB;QACjC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;QAC1F,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAChC,CAAC;CACF;AAED,MAAM,UAAU,+BAA+B,CAM7C,OAAqF;IAErF,OAAO,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,OAAO,uBAAuB;IACzB,SAAS,CAAU;IAC5B,OAAO,CAAsB;IAE7B,YAAY,QAAiB,EAAE,aAAuB;QACpD,IAAI,CAAC,SAAS,GAAG,EAAE,GAAG,QAAQ,EAAE,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC,EAAE,GAAG,aAAa,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IAClE,CAAC;IAED,IAAI;QACF,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IACzE,CAAC;IAED,KAAK,CAAC,KAAuB;QAC3B,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,KAAK,EAAE,CAAC;QAChE,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IAC9C,CAAC;CACF"}
@@ -0,0 +1,9 @@
1
+ import type { PreferenceStore } from './store.js';
2
+ export type PreferenceStoreFactory<TValues extends object> = (initialValues?: TValues) => PreferenceStore<TValues> | Promise<PreferenceStore<TValues>>;
3
+ export interface PreferenceStoreContractOptions<TValues extends object> {
4
+ readonly initialValues: TValues;
5
+ readonly patch: Partial<TValues>;
6
+ readonly expectedValues: TValues;
7
+ }
8
+ export declare function describePreferenceStoreContract<TValues extends object>(makeStore: PreferenceStoreFactory<TValues>, options: PreferenceStoreContractOptions<TValues>): void;
9
+ //# sourceMappingURL=vitest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vitest.d.ts","sourceRoot":"","sources":["../src/vitest.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,MAAM,MAAM,sBAAsB,CAAC,OAAO,SAAS,MAAM,IAAI,CAC3D,aAAa,CAAC,EAAE,OAAO,KACpB,eAAe,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AAElE,MAAM,WAAW,8BAA8B,CAAC,OAAO,SAAS,MAAM;IACpE,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACjC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;CAClC;AAED,wBAAgB,+BAA+B,CAAC,OAAO,SAAS,MAAM,EACpE,SAAS,EAAE,sBAAsB,CAAC,OAAO,CAAC,EAC1C,OAAO,EAAE,8BAA8B,CAAC,OAAO,CAAC,GAC/C,IAAI,CAiCN"}
package/dist/vitest.js ADDED
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ export function describePreferenceStoreContract(makeStore, options) {
3
+ describe('PreferenceStore contract', () => {
4
+ it('returns undefined when no values have been stored', async () => {
5
+ const store = await makeStore();
6
+ await expect(store.read()).resolves.toBeUndefined();
7
+ });
8
+ it('reads its initial values', async () => {
9
+ const store = await makeStore(options.initialValues);
10
+ await expect(store.read()).resolves.toEqual(options.initialValues);
11
+ });
12
+ it('merges a patch and returns the complete stored values', async () => {
13
+ const store = await makeStore(options.initialValues);
14
+ await expect(store.patch(options.patch)).resolves.toEqual(options.expectedValues);
15
+ await expect(store.read()).resolves.toEqual(options.expectedValues);
16
+ });
17
+ it('returns complete values when patching an empty store', async () => {
18
+ const store = await makeStore();
19
+ await expect(store.patch(options.patch)).resolves.toEqual(options.expectedValues);
20
+ await expect(store.read()).resolves.toEqual(options.expectedValues);
21
+ });
22
+ it('does not mutate the initial value or patch objects', async () => {
23
+ const initialSnapshot = { ...options.initialValues };
24
+ const patchSnapshot = { ...options.patch };
25
+ const store = await makeStore(options.initialValues);
26
+ await store.patch(options.patch);
27
+ expect(options.initialValues).toEqual(initialSnapshot);
28
+ expect(options.patch).toEqual(patchSnapshot);
29
+ });
30
+ });
31
+ }
32
+ //# sourceMappingURL=vitest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vitest.js","sourceRoot":"","sources":["../src/vitest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAc9C,MAAM,UAAU,+BAA+B,CAC7C,SAA0C,EAC1C,OAAgD;IAEhD,QAAQ,CAAC,0BAA0B,EAAE,GAAG,EAAE;QACxC,EAAE,CAAC,mDAAmD,EAAE,KAAK,IAAI,EAAE;YACjE,MAAM,KAAK,GAAG,MAAM,SAAS,EAAE,CAAC;YAChC,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC;QACtD,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,0BAA0B,EAAE,KAAK,IAAI,EAAE;YACxC,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YACrD,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;QACrE,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,uDAAuD,EAAE,KAAK,IAAI,EAAE;YACrE,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YACrD,MAAM,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;YAClF,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,sDAAsD,EAAE,KAAK,IAAI,EAAE;YACpE,MAAM,KAAK,GAAG,MAAM,SAAS,EAAE,CAAC;YAChC,MAAM,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;YAClF,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,oDAAoD,EAAE,KAAK,IAAI,EAAE;YAClE,MAAM,eAAe,GAAG,EAAE,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;YACrD,MAAM,aAAa,GAAG,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC;YAC3C,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YACrD,MAAM,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACjC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;YACvD,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
package/dist/wire.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export type OptionalWireValue<T> = {
2
+ readonly state: 'absent';
3
+ } | {
4
+ readonly state: 'null';
5
+ } | {
6
+ readonly state: 'value';
7
+ readonly value: T;
8
+ };
9
+ export declare function decodeOptionalWireValue<T>(payload: unknown, key: string, decodeValue: (value: unknown) => T): OptionalWireValue<T>;
10
+ export declare function encodeOptionalWireValue<TKey extends string, TValue>(key: TKey, value: OptionalWireValue<TValue>): Partial<Record<TKey, TValue | null>>;
11
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,iBAAiB,CAAC,CAAC,IAC3B;IAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC1B;IAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC;AAEnD,wBAAgB,uBAAuB,CAAC,CAAC,EACvC,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,MAAM,EACX,WAAW,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,CAAC,GACjC,iBAAiB,CAAC,CAAC,CAAC,CAStB;AAED,wBAAgB,uBAAuB,CAAC,IAAI,SAAS,MAAM,EAAE,MAAM,EACjE,GAAG,EAAE,IAAI,EACT,KAAK,EAAE,iBAAiB,CAAC,MAAM,CAAC,GAC/B,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAStC"}
package/dist/wire.js ADDED
@@ -0,0 +1,21 @@
1
+ export function decodeOptionalWireValue(payload, key, decodeValue) {
2
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
3
+ throw new TypeError('Optional wire payload must be an object');
4
+ }
5
+ if (!Object.hasOwn(payload, key)) {
6
+ return { state: 'absent' };
7
+ }
8
+ const value = payload[key];
9
+ return value === null ? { state: 'null' } : { state: 'value', value: decodeValue(value) };
10
+ }
11
+ export function encodeOptionalWireValue(key, value) {
12
+ switch (value.state) {
13
+ case 'absent':
14
+ return {};
15
+ case 'null':
16
+ return { [key]: null };
17
+ case 'value':
18
+ return { [key]: value.value };
19
+ }
20
+ }
21
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAKA,MAAM,UAAU,uBAAuB,CACrC,OAAgB,EAChB,GAAW,EACX,WAAkC;IAElC,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9E,MAAM,IAAI,SAAS,CAAC,yCAAyC,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;QACjC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;IAC7B,CAAC;IACD,MAAM,KAAK,GAAI,OAAmC,CAAC,GAAG,CAAC,CAAC;IACxD,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;AAC5F,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,GAAS,EACT,KAAgC;IAEhC,QAAQ,KAAK,CAAC,KAAK,EAAE,CAAC;QACpB,KAAK,QAAQ;YACX,OAAO,EAAE,CAAC;QACZ,KAAK,MAAM;YACT,OAAO,EAAE,CAAC,GAAG,CAAC,EAAE,IAAI,EAAwB,CAAC;QAC/C,KAAK,OAAO;YACV,OAAO,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,KAAK,EAA0B,CAAC;IAC1D,CAAC;AACH,CAAC"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@baukit/preferences-core",
3
+ "version": "0.1.0",
4
+ "description": "Typed preferences and their update behavior, with storage and effects supplied by the product.",
5
+ "license": "MIT",
6
+ "author": "Patrick Koss",
7
+ "homepage": "https://github.com/PatrickKoss/baukit#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/PatrickKoss/baukit.git",
11
+ "directory": "typescript/packages/preferences-core"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/PatrickKoss/baukit/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "type": "module",
20
+ "engines": {
21
+ "node": ">=24.0.0"
22
+ },
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ },
29
+ "./vitest": {
30
+ "types": "./dist/vitest.d.ts",
31
+ "import": "./dist/vitest.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "devDependencies": {
40
+ "typescript": "6.0.3",
41
+ "vitest": "4.1.10"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json",
45
+ "test": "vitest run --config ../../vitest.config.ts",
46
+ "lint": "eslint src --max-warnings=0",
47
+ "format:check": "prettier --check src package.json tsconfig.json"
48
+ }
49
+ }