@baukit/data-contracts 0.7.2 → 0.7.4

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,95 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { describeKeyValueContract } from './vitest.js';
4
+ import { type WebStorageLike, WebStorageKeyValueStore } from './web-storage.js';
5
+
6
+ class MapStorage implements WebStorageLike {
7
+ readonly items = new Map<string, string>();
8
+ failure: Error | null = null;
9
+
10
+ get length(): number {
11
+ return this.items.size;
12
+ }
13
+
14
+ key(index: number): string | null {
15
+ return [...this.items.keys()][index] ?? null;
16
+ }
17
+
18
+ getItem(key: string): string | null {
19
+ this.#throwIfFailing();
20
+ return this.items.get(key) ?? null;
21
+ }
22
+
23
+ setItem(key: string, value: string): void {
24
+ this.#throwIfFailing();
25
+ this.items.set(key, value);
26
+ }
27
+
28
+ removeItem(key: string): void {
29
+ this.#throwIfFailing();
30
+ this.items.delete(key);
31
+ }
32
+
33
+ #throwIfFailing(): void {
34
+ if (this.failure !== null) {
35
+ throw this.failure;
36
+ }
37
+ }
38
+ }
39
+
40
+ function namedError(name: string): Error {
41
+ const error = new Error('provider text');
42
+ error.name = name;
43
+ return error;
44
+ }
45
+
46
+ describeKeyValueContract(() => new WebStorageKeyValueStore(new MapStorage(), 'app:'));
47
+
48
+ describe('WebStorageKeyValueStore', () => {
49
+ it('rejects an empty namespace', () => {
50
+ expect(() => new WebStorageKeyValueStore(new MapStorage(), '')).toThrow(RangeError);
51
+ });
52
+
53
+ it('stores JSON under the namespace and leaves other keys of the origin alone', async () => {
54
+ const storage = new MapStorage();
55
+ storage.items.set('foreign', 'kept');
56
+ storage.items.set('app-other:a', 'kept');
57
+ const store = new WebStorageKeyValueStore(storage, 'app:');
58
+
59
+ await store.set('a', { ready: true });
60
+ expect(storage.items.get('app:a')).toBe('{"ready":true}');
61
+
62
+ await store.clear();
63
+ expect([...storage.items.keys()]).toEqual(['foreign', 'app-other:a']);
64
+ });
65
+
66
+ it('reports quota failures as StorageError', async () => {
67
+ const storage = new MapStorage();
68
+ storage.failure = namedError('QuotaExceededError');
69
+ const store = new WebStorageKeyValueStore(storage, 'app:');
70
+
71
+ await expect(store.set('a', 1)).rejects.toMatchObject({
72
+ name: 'StorageError',
73
+ code: 'storage_quota_exceeded',
74
+ });
75
+ });
76
+
77
+ it('rejects instead of throwing when storage access is denied', async () => {
78
+ const storage = new MapStorage();
79
+ storage.failure = namedError('SecurityError');
80
+ const store = new WebStorageKeyValueStore(storage, 'app:');
81
+
82
+ const read = store.get('a');
83
+ await expect(read).rejects.toMatchObject({ name: 'SecurityError' });
84
+ await expect(store.set('a', 1)).rejects.toMatchObject({ name: 'SecurityError' });
85
+ });
86
+
87
+ it('rejects a payload that is not JSON without echoing it', async () => {
88
+ const storage = new MapStorage();
89
+ storage.items.set('app:a', 'secret{');
90
+ const store = new WebStorageKeyValueStore(storage, 'app:');
91
+
92
+ await expect(store.get('a')).rejects.toThrow(TypeError);
93
+ await expect(store.get('a')).rejects.not.toThrow(/secret/);
94
+ });
95
+ });
@@ -0,0 +1,88 @@
1
+ import { type JsonValue, type KeyValueStore, normalizeStorageError } from './contracts.js';
2
+
3
+ /** The part of the Web Storage API (`sessionStorage`, `localStorage`) the adapter uses. */
4
+ export interface WebStorageLike {
5
+ readonly length: number;
6
+ key(index: number): string | null;
7
+ getItem(key: string): string | null;
8
+ setItem(key: string, value: string): void;
9
+ removeItem(key: string): void;
10
+ }
11
+
12
+ /**
13
+ * A `KeyValueStore` over Web Storage. Every key is stored under `namespace`, so `clear` and
14
+ * `clearPrefix` never touch other data of the origin. Values are stored as JSON text.
15
+ */
16
+ export class WebStorageKeyValueStore implements KeyValueStore {
17
+ readonly #storage: WebStorageLike;
18
+ readonly #namespace: string;
19
+
20
+ public constructor(storage: WebStorageLike, namespace: string) {
21
+ if (namespace === '') {
22
+ throw new RangeError('Web Storage namespace must not be empty.');
23
+ }
24
+ this.#storage = storage;
25
+ this.#namespace = namespace;
26
+ }
27
+
28
+ public get(key: string): Promise<JsonValue | undefined> {
29
+ return run(() => {
30
+ const payload = this.#storage.getItem(this.#namespace + key);
31
+ return payload === null ? undefined : parsePayload(payload);
32
+ });
33
+ }
34
+
35
+ public set(key: string, value: JsonValue): Promise<void> {
36
+ return run(() => {
37
+ this.#storage.setItem(this.#namespace + key, JSON.stringify(value));
38
+ });
39
+ }
40
+
41
+ public delete(key: string): Promise<void> {
42
+ return run(() => {
43
+ this.#storage.removeItem(this.#namespace + key);
44
+ });
45
+ }
46
+
47
+ public clear(): Promise<void> {
48
+ return this.clearPrefix('');
49
+ }
50
+
51
+ public clearPrefix(prefix: string): Promise<void> {
52
+ return run(() => {
53
+ const storedPrefix = this.#namespace + prefix;
54
+ for (const storedKey of this.#storedKeys()) {
55
+ if (storedKey.startsWith(storedPrefix)) {
56
+ this.#storage.removeItem(storedKey);
57
+ }
58
+ }
59
+ });
60
+ }
61
+
62
+ #storedKeys(): string[] {
63
+ const keys: string[] = [];
64
+ for (let index = 0; index < this.#storage.length; index += 1) {
65
+ const key = this.#storage.key(index);
66
+ if (key !== null) {
67
+ keys.push(key);
68
+ }
69
+ }
70
+ return keys;
71
+ }
72
+ }
73
+
74
+ function run<TResult>(operation: () => TResult): Promise<TResult> {
75
+ return Promise.resolve()
76
+ .then(operation)
77
+ .catch((cause: unknown) => {
78
+ throw normalizeStorageError(cause);
79
+ });
80
+ }
81
+
82
+ function parsePayload(payload: string): JsonValue {
83
+ try {
84
+ return JSON.parse(payload) as JsonValue;
85
+ } catch {
86
+ throw new TypeError('Web Storage contains an invalid key/value payload.');
87
+ }
88
+ }