@baukit/preferences-core 0.7.2 → 0.7.3

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.
@@ -0,0 +1,362 @@
1
+ import {
2
+ normalizePreferences,
3
+ type PreferenceKey,
4
+ type PreferenceRegistry,
5
+ type PreferenceSideEffectContext,
6
+ } from './definitions.js';
7
+ import type { PreferenceStore } from './store.js';
8
+ import type { OptionalWireValue } from './wire.js';
9
+
10
+ export type PreferenceControllerStatus = 'idle' | 'hydrating' | 'ready';
11
+
12
+ export interface PreferenceControllerState<TValues extends object> {
13
+ readonly values: TValues;
14
+ readonly status: PreferenceControllerStatus;
15
+ readonly error: Error | null;
16
+ }
17
+
18
+ export interface SerializedPreferenceControllerState<
19
+ TValues extends object,
20
+ > extends PreferenceControllerState<TValues> {
21
+ readonly pendingCount: number;
22
+ }
23
+
24
+ export interface PreferenceController<TValues extends object> {
25
+ getState(): PreferenceControllerState<TValues>;
26
+ hydrate(): Promise<TValues>;
27
+ update(patch: Partial<TValues>): Promise<TValues>;
28
+ applyWireValue<TKey extends PreferenceKey<TValues>>(
29
+ key: TKey,
30
+ value: OptionalWireValue<Exclude<TValues[TKey], null>>,
31
+ ): Promise<TValues>;
32
+ switchIdentity(store: PreferenceStore<TValues>): Promise<TValues>;
33
+ /**
34
+ * Stops publishing to `onVisibleChange`. Call it when the consumer that owns the
35
+ * callback goes away, such as a React provider unmounting. In-flight reads and
36
+ * writes still settle and still update `getState()`; they just stop being
37
+ * published. Stopping is permanent for this controller instance.
38
+ */
39
+ stop(): void;
40
+ }
41
+
42
+ export interface SerializedPreferenceController<
43
+ TValues extends object,
44
+ > extends PreferenceController<TValues> {
45
+ getState(): SerializedPreferenceControllerState<TValues>;
46
+ }
47
+
48
+ export type PreferenceUpdateMode = 'optimistic' | 'serialized';
49
+
50
+ export interface CreatePreferenceControllerOptions<TValues extends object> {
51
+ readonly definitions: PreferenceRegistry<TValues>;
52
+ readonly store: PreferenceStore<TValues>;
53
+ readonly onVisibleChange: (values: TValues) => void;
54
+ readonly updateMode?: PreferenceUpdateMode;
55
+ }
56
+
57
+ class DefaultPreferenceController<TValues extends object> implements PreferenceController<TValues> {
58
+ readonly #definitions: PreferenceRegistry<TValues>;
59
+ readonly #onVisibleChange: (values: TValues) => void;
60
+ readonly #updateMode: PreferenceUpdateMode;
61
+ #store: PreferenceStore<TValues>;
62
+ #state: PreferenceControllerState<TValues>;
63
+ #identityRevision = 0;
64
+ #pendingCount = 0;
65
+ #updateTail: Promise<void> = Promise.resolve();
66
+ #stopped = false;
67
+
68
+ constructor(options: CreatePreferenceControllerOptions<TValues>) {
69
+ this.#definitions = options.definitions;
70
+ this.#store = options.store;
71
+ this.#onVisibleChange = options.onVisibleChange;
72
+ this.#updateMode = options.updateMode ?? 'optimistic';
73
+ this.#state = this.#withPendingCount({
74
+ values: normalizePreferences(this.#definitions, undefined),
75
+ status: 'idle',
76
+ error: null,
77
+ });
78
+ }
79
+
80
+ getState(): PreferenceControllerState<TValues> {
81
+ return this.#state;
82
+ }
83
+
84
+ async hydrate(): Promise<TValues> {
85
+ const revision = this.#identityRevision;
86
+ this.#setState({ ...this.#state, status: 'hydrating', error: null });
87
+ try {
88
+ const stored = await this.#store.read();
89
+ const values = normalizePreferences(this.#definitions, stored);
90
+ if (!this.#setVisible(values, 'ready', null, revision)) {
91
+ return this.#state.values;
92
+ }
93
+ return values;
94
+ } catch (error) {
95
+ const values = normalizePreferences(this.#definitions, undefined);
96
+ this.#setVisible(values, 'ready', asError(error), revision);
97
+ throw asError(error);
98
+ }
99
+ }
100
+
101
+ update(patch: Partial<TValues>): Promise<TValues> {
102
+ if (this.#updateMode === 'serialized') {
103
+ let normalizedPatch: Partial<TValues>;
104
+ try {
105
+ normalizedPatch = this.#normalizePatch(patch);
106
+ } catch (error) {
107
+ return Promise.reject(asError(error));
108
+ }
109
+ return this.#enqueueSerializedUpdate(normalizedPatch);
110
+ }
111
+ return this.#runUpdate(patch, this.#identityRevision, this.#store, true);
112
+ }
113
+
114
+ async #runUpdate(
115
+ patch: Partial<TValues>,
116
+ revision: number,
117
+ store: PreferenceStore<TValues>,
118
+ optimistic: boolean,
119
+ ): Promise<TValues> {
120
+ if (revision !== this.#identityRevision) {
121
+ return this.#state.values;
122
+ }
123
+ const previousValues = this.#state.values;
124
+ const normalizedPatch = optimistic ? this.#normalizePatch(patch) : patch;
125
+ const values = { ...previousValues, ...normalizedPatch };
126
+ const changedKeys = this.#changedKeys(previousValues, values, normalizedPatch);
127
+
128
+ if (optimistic) {
129
+ this.#setVisible(values, 'ready', null, revision);
130
+ }
131
+ const previewed: PreferenceKey<TValues>[] = [];
132
+ let persisted: TValues;
133
+ try {
134
+ for (const key of changedKeys) {
135
+ const effect = this.#definitions[key].sideEffect;
136
+ if (effect?.mode === 'preview-with-rollback') {
137
+ previewed.push(key);
138
+ try {
139
+ await effect.preview(this.#effectContext(key, previousValues, values));
140
+ } catch (error) {
141
+ if (effect.onError === 'report') {
142
+ throw error;
143
+ }
144
+ }
145
+ }
146
+ }
147
+ persisted = normalizePreferences(this.#definitions, await store.patch(normalizedPatch));
148
+ } catch (error) {
149
+ const updateError = asError(error);
150
+ const rollbackError = await this.#rollbackPreviews(previewed, previousValues, values);
151
+ const reportedError = rollbackError
152
+ ? new AggregateError(
153
+ [updateError, rollbackError],
154
+ 'Preference update and preview rollback failed',
155
+ )
156
+ : updateError;
157
+ if (optimistic) {
158
+ this.#setVisible(previousValues, 'ready', reportedError, revision);
159
+ }
160
+ throw reportedError;
161
+ }
162
+ if (!this.#setVisible(persisted, 'ready', null, revision)) {
163
+ await this.#rollbackPreviews(previewed, previousValues, values);
164
+ return this.#state.values;
165
+ }
166
+ await this.#runPersistedEffects(changedKeys, previousValues, persisted, revision);
167
+ return persisted;
168
+ }
169
+
170
+ #enqueueSerializedUpdate(patch: Partial<TValues>): Promise<TValues> {
171
+ const revision = this.#identityRevision;
172
+ const store = this.#store;
173
+ const startImmediately = this.#pendingCount === 0;
174
+ this.#pendingCount += 1;
175
+ this.#setVisible(this.#state.values, this.#state.status, null, revision);
176
+
177
+ const run = () => this.#runUpdate(patch, revision, store, false);
178
+ const write = startImmediately ? run() : this.#updateTail.then(run);
179
+ const operation = write.then(
180
+ (values) => {
181
+ this.#finishSerializedUpdate(revision, null);
182
+ return values;
183
+ },
184
+ (reason: unknown) => {
185
+ const error = asError(reason);
186
+ this.#finishSerializedUpdate(revision, error);
187
+ throw error;
188
+ },
189
+ );
190
+ this.#updateTail = operation.then(
191
+ () => undefined,
192
+ () => undefined,
193
+ );
194
+ return operation;
195
+ }
196
+
197
+ #finishSerializedUpdate(revision: number, error: Error | null): void {
198
+ if (revision !== this.#identityRevision) {
199
+ return;
200
+ }
201
+ this.#pendingCount = Math.max(0, this.#pendingCount - 1);
202
+ this.#setVisible(this.#state.values, 'ready', error, revision);
203
+ }
204
+
205
+ applyWireValue<TKey extends PreferenceKey<TValues>>(
206
+ key: TKey,
207
+ value: OptionalWireValue<Exclude<TValues[TKey], null>>,
208
+ ): Promise<TValues> {
209
+ if (value.state === 'absent') {
210
+ return Promise.resolve(this.#state.values);
211
+ }
212
+ const patch: Record<string, unknown> = {
213
+ [key]: value.state === 'null' ? null : value.value,
214
+ };
215
+ return this.update(patch as Partial<TValues>);
216
+ }
217
+
218
+ switchIdentity(store: PreferenceStore<TValues>): Promise<TValues> {
219
+ this.#identityRevision += 1;
220
+ this.#pendingCount = 0;
221
+ this.#updateTail = Promise.resolve();
222
+ this.#store = store;
223
+ const defaults = normalizePreferences(this.#definitions, undefined);
224
+ this.#setVisible(defaults, 'idle', null);
225
+ return this.hydrate();
226
+ }
227
+
228
+ stop(): void {
229
+ this.#stopped = true;
230
+ }
231
+
232
+ #setState(state: PreferenceControllerState<TValues>): void {
233
+ this.#state = this.#withPendingCount(state);
234
+ }
235
+
236
+ #setVisible(
237
+ values: TValues,
238
+ status: PreferenceControllerStatus,
239
+ error: Error | null,
240
+ revision: number = this.#identityRevision,
241
+ ): boolean {
242
+ if (revision !== this.#identityRevision) {
243
+ return false;
244
+ }
245
+ this.#state = this.#withPendingCount({ values, status, error });
246
+ if (!this.#stopped) {
247
+ this.#onVisibleChange(values);
248
+ }
249
+ return true;
250
+ }
251
+
252
+ #withPendingCount(
253
+ state: PreferenceControllerState<TValues>,
254
+ ): PreferenceControllerState<TValues> | SerializedPreferenceControllerState<TValues> {
255
+ return this.#updateMode === 'serialized'
256
+ ? { ...state, pendingCount: this.#pendingCount }
257
+ : state;
258
+ }
259
+
260
+ #normalizePatch(patch: Partial<TValues>): Partial<TValues> {
261
+ const normalized: Record<string, unknown> = {};
262
+ for (const key of Object.keys(patch)) {
263
+ if (!Object.hasOwn(this.#definitions, key)) {
264
+ throw new TypeError(`Unknown preference key: ${key}`);
265
+ }
266
+ const typedKey = key as PreferenceKey<TValues>;
267
+ normalized[key] = this.#definitions[typedKey].normalize(patch[typedKey]);
268
+ }
269
+ return normalized as Partial<TValues>;
270
+ }
271
+
272
+ #changedKeys(
273
+ previousValues: TValues,
274
+ values: TValues,
275
+ patch: Partial<TValues>,
276
+ ): PreferenceKey<TValues>[] {
277
+ return (Object.keys(patch) as PreferenceKey<TValues>[]).filter(
278
+ (key) => !Object.is(previousValues[key], values[key]),
279
+ );
280
+ }
281
+
282
+ #effectContext<TKey extends PreferenceKey<TValues>>(
283
+ key: TKey,
284
+ previousValues: TValues,
285
+ values: TValues,
286
+ ): PreferenceSideEffectContext<TKey, TValues[TKey], TValues> {
287
+ return {
288
+ key,
289
+ previousValue: previousValues[key],
290
+ value: values[key],
291
+ previousValues,
292
+ values,
293
+ };
294
+ }
295
+
296
+ async #rollbackPreviews(
297
+ keys: readonly PreferenceKey<TValues>[],
298
+ previousValues: TValues,
299
+ values: TValues,
300
+ ): Promise<Error | null> {
301
+ let firstError: Error | null = null;
302
+ for (const key of [...keys].reverse()) {
303
+ const effect = this.#definitions[key].sideEffect;
304
+ if (effect?.mode !== 'preview-with-rollback') {
305
+ continue;
306
+ }
307
+ try {
308
+ await effect.rollback(this.#effectContext(key, previousValues, values));
309
+ } catch (error) {
310
+ firstError ??= asError(error);
311
+ }
312
+ }
313
+ return firstError;
314
+ }
315
+
316
+ async #runPersistedEffects(
317
+ keys: readonly PreferenceKey<TValues>[],
318
+ previousValues: TValues,
319
+ values: TValues,
320
+ revision: number,
321
+ ): Promise<void> {
322
+ for (const key of keys) {
323
+ const effect = this.#definitions[key].sideEffect;
324
+ if (!effect) {
325
+ continue;
326
+ }
327
+ const run = effect.mode === 'after-persistence' ? effect.run : effect.afterPersistence;
328
+ if (!run) {
329
+ continue;
330
+ }
331
+ try {
332
+ await run(this.#effectContext(key, previousValues, values));
333
+ } catch (error) {
334
+ if (effect.onError === 'report') {
335
+ const effectError = asError(error);
336
+ if (revision === this.#identityRevision) {
337
+ this.#setState({ ...this.#state, error: effectError });
338
+ }
339
+ throw effectError;
340
+ }
341
+ }
342
+ }
343
+ }
344
+ }
345
+
346
+ function asError(reason: unknown): Error {
347
+ return reason instanceof Error
348
+ ? reason
349
+ : new Error('Preference operation failed', { cause: reason });
350
+ }
351
+
352
+ export function createPreferenceController<TValues extends object>(
353
+ options: CreatePreferenceControllerOptions<TValues> & { readonly updateMode: 'serialized' },
354
+ ): SerializedPreferenceController<TValues>;
355
+ export function createPreferenceController<TValues extends object>(
356
+ options: CreatePreferenceControllerOptions<TValues>,
357
+ ): PreferenceController<TValues>;
358
+ export function createPreferenceController<TValues extends object>(
359
+ options: CreatePreferenceControllerOptions<TValues>,
360
+ ): PreferenceController<TValues> {
361
+ return new DefaultPreferenceController(options);
362
+ }
@@ -0,0 +1,78 @@
1
+ export type PreferenceScope = 'device' | 'identity' | 'synced';
2
+
3
+ export type PreferenceSideEffectFailurePolicy = 'ignore' | 'report';
4
+
5
+ export interface PreferenceSideEffectContext<TKey extends string, TValue, TValues extends object> {
6
+ readonly key: TKey;
7
+ readonly previousValue: TValue;
8
+ readonly value: TValue;
9
+ readonly previousValues: TValues;
10
+ readonly values: TValues;
11
+ }
12
+
13
+ export interface AfterPersistencePreferenceSideEffect<
14
+ TKey extends string,
15
+ TValue,
16
+ TValues extends object,
17
+ > {
18
+ readonly mode: 'after-persistence';
19
+ readonly onError: PreferenceSideEffectFailurePolicy;
20
+ readonly run: (
21
+ context: PreferenceSideEffectContext<TKey, TValue, TValues>,
22
+ ) => Promise<void> | void;
23
+ }
24
+
25
+ export interface PreviewPreferenceSideEffect<TKey extends string, TValue, TValues extends object> {
26
+ readonly mode: 'preview-with-rollback';
27
+ readonly onError: PreferenceSideEffectFailurePolicy;
28
+ readonly preview: (
29
+ context: PreferenceSideEffectContext<TKey, TValue, TValues>,
30
+ ) => Promise<void> | void;
31
+ readonly rollback: (
32
+ context: PreferenceSideEffectContext<TKey, TValue, TValues>,
33
+ ) => Promise<void> | void;
34
+ readonly afterPersistence?: (
35
+ context: PreferenceSideEffectContext<TKey, TValue, TValues>,
36
+ ) => Promise<void> | void;
37
+ }
38
+
39
+ export type PreferenceSideEffect<TKey extends string, TValue, TValues extends object> =
40
+ | AfterPersistencePreferenceSideEffect<TKey, TValue, TValues>
41
+ | PreviewPreferenceSideEffect<TKey, TValue, TValues>;
42
+
43
+ export interface PreferenceDefinition<
44
+ TKey extends string,
45
+ TValue,
46
+ TValues extends object = Record<TKey, TValue>,
47
+ > {
48
+ readonly key: TKey;
49
+ readonly defaultValue: TValue;
50
+ readonly normalize: (value: unknown) => TValue;
51
+ readonly scope: PreferenceScope;
52
+ readonly sideEffect?: PreferenceSideEffect<TKey, TValue, TValues>;
53
+ }
54
+
55
+ export type PreferenceKey<TValues extends object> = Extract<keyof TValues, string>;
56
+
57
+ export type PreferenceRegistry<TValues extends object> = {
58
+ readonly [TKey in PreferenceKey<TValues>]: PreferenceDefinition<TKey, TValues[TKey], TValues>;
59
+ };
60
+
61
+ export function definePreferenceRegistry<TValues extends object>(
62
+ registry: PreferenceRegistry<TValues>,
63
+ ): PreferenceRegistry<TValues> {
64
+ return registry;
65
+ }
66
+
67
+ export function normalizePreferences<TValues extends object>(
68
+ definitions: PreferenceRegistry<TValues>,
69
+ input: Partial<TValues> | undefined,
70
+ ): TValues {
71
+ const normalized: Record<string, unknown> = {};
72
+ for (const key of Object.keys(definitions) as PreferenceKey<TValues>[]) {
73
+ const definition = definitions[key];
74
+ const value = input && Object.hasOwn(input, key) ? input[key] : definition.defaultValue;
75
+ normalized[key] = definition.normalize(value);
76
+ }
77
+ return normalized as TValues;
78
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './controller.js';
2
+ export * from './definitions.js';
3
+ export * from './store.js';
4
+ export * from './wire.js';
package/src/raw.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ declare module '*?raw' {
2
+ const content: string;
3
+ export default content;
4
+ }
@@ -0,0 +1,173 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import {
4
+ createRepositoryPreferenceStore,
5
+ RepositoryPreferenceStore,
6
+ type PreferenceRecordRepository,
7
+ } from './store.js';
8
+ import { describePreferenceStoreContract } from './vitest.js';
9
+
10
+ interface ContractPreferences {
11
+ readonly language: string;
12
+ readonly theme: string;
13
+ readonly gameLayerEnabled: boolean;
14
+ }
15
+
16
+ /** A stored record whose column names deliberately differ from the preference keys. */
17
+ interface SettingsRecord {
18
+ readonly subject_id: string;
19
+ readonly language: string;
20
+ readonly theme: string;
21
+ readonly game_layer_enabled: boolean;
22
+ readonly updated_at: string;
23
+ }
24
+
25
+ type SettingsRecordPatch = Partial<Omit<SettingsRecord, 'subject_id' | 'updated_at'>>;
26
+
27
+ const defaults: ContractPreferences = {
28
+ language: 'system',
29
+ theme: 'dark',
30
+ gameLayerEnabled: false,
31
+ };
32
+
33
+ const SUBJECT = 'subject-1';
34
+
35
+ class FakeSettingsRepository implements PreferenceRecordRepository<
36
+ string,
37
+ SettingsRecord,
38
+ SettingsRecordPatch
39
+ > {
40
+ readonly #records = new Map<string, SettingsRecord>();
41
+ upsertCalls = 0;
42
+
43
+ seed(subjectId: string, values: ContractPreferences): void {
44
+ this.#records.set(subjectId, {
45
+ subject_id: subjectId,
46
+ language: values.language,
47
+ theme: values.theme,
48
+ game_layer_enabled: values.gameLayerEnabled,
49
+ updated_at: '2026-01-01T00:00:00.000Z',
50
+ });
51
+ }
52
+
53
+ get(subjectId: string): Promise<SettingsRecord | undefined> {
54
+ return Promise.resolve(this.#records.get(subjectId));
55
+ }
56
+
57
+ upsert(subjectId: string, patch: SettingsRecordPatch): Promise<SettingsRecord> {
58
+ this.upsertCalls += 1;
59
+ const existing = this.#records.get(subjectId);
60
+ const next: SettingsRecord = {
61
+ subject_id: subjectId,
62
+ language: patch.language ?? existing?.language ?? defaults.language,
63
+ theme: patch.theme ?? existing?.theme ?? defaults.theme,
64
+ game_layer_enabled:
65
+ patch.game_layer_enabled ?? existing?.game_layer_enabled ?? defaults.gameLayerEnabled,
66
+ updated_at: '2026-01-02T00:00:00.000Z',
67
+ };
68
+ this.#records.set(subjectId, next);
69
+ return Promise.resolve(next);
70
+ }
71
+ }
72
+
73
+ function toValues(record: SettingsRecord): ContractPreferences {
74
+ return {
75
+ language: record.language,
76
+ theme: record.theme,
77
+ gameLayerEnabled: record.game_layer_enabled,
78
+ };
79
+ }
80
+
81
+ function toRecordPatch(patch: Partial<ContractPreferences>): SettingsRecordPatch {
82
+ return {
83
+ ...(patch.language === undefined ? {} : { language: patch.language }),
84
+ ...(patch.theme === undefined ? {} : { theme: patch.theme }),
85
+ ...(patch.gameLayerEnabled === undefined ? {} : { game_layer_enabled: patch.gameLayerEnabled }),
86
+ };
87
+ }
88
+
89
+ describePreferenceStoreContract(
90
+ (initialValues?: ContractPreferences) => {
91
+ const repository = new FakeSettingsRepository();
92
+ if (initialValues) {
93
+ repository.seed(SUBJECT, initialValues);
94
+ }
95
+ return createRepositoryPreferenceStore({
96
+ repository,
97
+ subjectId: SUBJECT,
98
+ toValues,
99
+ toRecordPatch,
100
+ });
101
+ },
102
+ {
103
+ initialValues: defaults,
104
+ patch: { language: 'de', gameLayerEnabled: true },
105
+ expectedValues: { language: 'de', theme: 'dark', gameLayerEnabled: true },
106
+ },
107
+ );
108
+
109
+ describe('RepositoryPreferenceStore', () => {
110
+ it('treats a null repository result as a missing record', async () => {
111
+ const store = new RepositoryPreferenceStore({
112
+ repository: {
113
+ get: () => Promise.resolve(null),
114
+ upsert: () => Promise.reject(new Error('unused')),
115
+ },
116
+ subjectId: SUBJECT,
117
+ toValues,
118
+ toRecordPatch,
119
+ });
120
+
121
+ await expect(store.read()).resolves.toBeUndefined();
122
+ });
123
+
124
+ it('reads only the record belonging to its own subject', async () => {
125
+ const repository = new FakeSettingsRepository();
126
+ repository.seed('other-subject', { ...defaults, language: 'fr' });
127
+ const store = new RepositoryPreferenceStore({
128
+ repository,
129
+ subjectId: SUBJECT,
130
+ toValues,
131
+ toRecordPatch,
132
+ });
133
+
134
+ await expect(store.read()).resolves.toBeUndefined();
135
+ });
136
+
137
+ it('omits untouched preferences from the record patch', async () => {
138
+ const repository = new FakeSettingsRepository();
139
+ repository.seed(SUBJECT, defaults);
140
+ const seen: SettingsRecordPatch[] = [];
141
+ const store = new RepositoryPreferenceStore({
142
+ repository,
143
+ subjectId: SUBJECT,
144
+ toValues,
145
+ toRecordPatch: (patch) => {
146
+ const recordPatch = toRecordPatch(patch);
147
+ seen.push(recordPatch);
148
+ return recordPatch;
149
+ },
150
+ });
151
+
152
+ await store.patch({ theme: 'light' });
153
+
154
+ expect(seen).toEqual([{ theme: 'light' }]);
155
+ });
156
+
157
+ it('projects the record the repository returns rather than the requested patch', async () => {
158
+ const repository = new FakeSettingsRepository();
159
+ repository.seed(SUBJECT, defaults);
160
+ const store = new RepositoryPreferenceStore({
161
+ repository,
162
+ subjectId: SUBJECT,
163
+ toValues,
164
+ toRecordPatch,
165
+ });
166
+
167
+ await expect(store.patch({ language: 'de' })).resolves.toEqual({
168
+ ...defaults,
169
+ language: 'de',
170
+ });
171
+ expect(repository.upsertCalls).toBe(1);
172
+ });
173
+ });
@@ -0,0 +1,27 @@
1
+ import { describePreferenceStoreContract } from './vitest.js';
2
+ import { InMemoryPreferenceStore } from './store.js';
3
+
4
+ interface ContractPreferences {
5
+ readonly language: string;
6
+ readonly theme: string;
7
+ readonly gameLayerEnabled: boolean;
8
+ }
9
+
10
+ const defaults: ContractPreferences = {
11
+ language: 'system',
12
+ theme: 'dark',
13
+ gameLayerEnabled: false,
14
+ };
15
+
16
+ describePreferenceStoreContract(
17
+ (initialValues?: ContractPreferences) => new InMemoryPreferenceStore(defaults, initialValues),
18
+ {
19
+ initialValues: defaults,
20
+ patch: { language: 'de', gameLayerEnabled: true },
21
+ expectedValues: {
22
+ language: 'de',
23
+ theme: 'dark',
24
+ gameLayerEnabled: true,
25
+ },
26
+ },
27
+ );