import { vi } from 'vitest' import type { ClientSettingsScope, ClientSettingsSnapshot } from '../../src/host/protocol.ts' export function readySnapshot(value: T, overrides: Partial> = {}): ClientSettingsSnapshot { return { status: 'ready', value, base: {} as T, user: {} as T, revision: 0, writable: true, mode: 'host', ...overrides } } /** * Settings scope fake over one published snapshot. Reads go through the * receiver like DSH's own scopes, so an unbound read fails the test; writes * reach `mutate`, which callers pass in when they assert on it. */ export function settingsScope(snapshot: ClientSettingsSnapshot, mutate: ClientSettingsScope['mutate'] = vi.fn(async () => {})) { return { snapshot, getSnapshot() { return this.snapshot }, subscribe: () => () => {}, mutate, } satisfies ClientSettingsScope & { snapshot: ClientSettingsSnapshot } } /** * Settings scope fake that publishes each write as the next snapshot, as DSH's * scopes do once the Host saves it, so a control that applies at once shows * what it saved. `mutate` sees every write first and can refuse it. */ export function liveSettingsScope(snapshot: ClientSettingsSnapshot, mutate: ClientSettingsScope['mutate'] = vi.fn(async () => {}), readback?: (value: T) => T) { const listeners = new Set<() => void>() const scope = { snapshot: snapshot.value === undefined || readback === undefined ? snapshot : { ...snapshot, value: readback(snapshot.value) }, getSnapshot() { return this.snapshot }, subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener) } }, publish(next: ClientSettingsSnapshot) { scope.snapshot = next for (const listener of [...listeners]) listener() }, async mutate(operations: Parameters['mutate']>[0]) { await mutate(operations) const value = structuredClone(scope.snapshot.value ?? {}) as Record for (const operation of operations) { let target = value for (const segment of operation.path.slice(0, -1)) target = (target[segment] ??= {}) as Record const last = operation.path.at(-1)! if (operation.op === 'unset') delete target[last] else target[last] = structuredClone(operation.value) } scope.snapshot = { ...scope.snapshot, value: readback === undefined ? value as T : readback(value as T), revision: (scope.snapshot.revision ?? 0) + 1 } for (const listener of listeners) listener() }, } satisfies ClientSettingsScope & { snapshot: ClientSettingsSnapshot; publish: (next: ClientSettingsSnapshot) => void } return scope }