@kamod-ch/signals 1.0.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/package.json +48 -0
- package/src/drivers.ts +470 -0
- package/src/index.ts +11 -0
- package/src/persistedSignal.ts +307 -0
- package/src/shared.ts +25 -0
- package/src/types.ts +41 -0
- package/src/usePersistedSignal.ts +52 -0
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kamod-ch/signals",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Persisted Preact signals with localStorage, sessionStorage, IndexedDB, cookie, and memory drivers.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Klaus Zahiragic <watzak>",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/kamod-ch/kamod-signals.git",
|
|
11
|
+
"directory": "packages/core"
|
|
12
|
+
},
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"main": "./src/index.ts",
|
|
17
|
+
"types": "./src/index.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./src/index.ts",
|
|
21
|
+
"import": "./src/index.ts"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"src",
|
|
26
|
+
"!src/**/*.spec.ts"
|
|
27
|
+
],
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"@preact/signals": "^2.0.0",
|
|
31
|
+
"preact": "^10.0.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@preact/signals": "^2.9.2",
|
|
35
|
+
"@types/node": "^26.1.0",
|
|
36
|
+
"jsdom": "^29.1.1",
|
|
37
|
+
"preact": "^10.29.4",
|
|
38
|
+
"tsup": "^8.5.1",
|
|
39
|
+
"typescript": "^6.0.3",
|
|
40
|
+
"vitest": "^4.1.10"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsup",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"test:watch": "vitest"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/drivers.ts
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { isBrowser, type StorageDriver } from "./shared";
|
|
2
|
+
import type { CookieContext, CookieOptions, PersistedSignalOptions, PersistedStorage } from "./types";
|
|
3
|
+
|
|
4
|
+
const CHANNEL_PREFIX = "@kamod-ch/signals";
|
|
5
|
+
const INDEXED_DB_NAME = "@kamod-ch/signals";
|
|
6
|
+
const INDEXED_DB_STORE = "signals";
|
|
7
|
+
const memoryStore = new Map<string, string>();
|
|
8
|
+
const memoryListeners = new Map<string, Set<() => void>>();
|
|
9
|
+
const indexedDbConnections = new Map<string, Promise<IDBDatabase>>();
|
|
10
|
+
|
|
11
|
+
const channelName = (storage: PersistedStorage, key: string) => `${CHANNEL_PREFIX}:${storage}:${key}`;
|
|
12
|
+
|
|
13
|
+
const emitChannel = (storage: PersistedStorage, key: string) => {
|
|
14
|
+
const name = channelName(storage, key);
|
|
15
|
+
|
|
16
|
+
if (isBrowser) {
|
|
17
|
+
window.dispatchEvent(new CustomEvent(name));
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const listeners = memoryListeners.get(name);
|
|
22
|
+
if (!listeners) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
for (const listener of listeners) {
|
|
27
|
+
listener();
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const subscribeChannel = (storage: PersistedStorage, key: string, callback: () => void) => {
|
|
32
|
+
const name = channelName(storage, key);
|
|
33
|
+
|
|
34
|
+
if (isBrowser) {
|
|
35
|
+
const browserListener = () => callback();
|
|
36
|
+
window.addEventListener(name, browserListener as EventListener);
|
|
37
|
+
return () => {
|
|
38
|
+
window.removeEventListener(name, browserListener as EventListener);
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const listeners = memoryListeners.get(name) ?? new Set<() => void>();
|
|
43
|
+
listeners.add(callback);
|
|
44
|
+
memoryListeners.set(name, listeners);
|
|
45
|
+
|
|
46
|
+
return () => {
|
|
47
|
+
listeners.delete(callback);
|
|
48
|
+
if (listeners.size === 0) {
|
|
49
|
+
memoryListeners.delete(name);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const createWebStorageDriver = (type: "local" | "session", getStorage: () => Storage): StorageDriver => ({
|
|
55
|
+
type,
|
|
56
|
+
isAvailable() {
|
|
57
|
+
if (!isBrowser) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
const storage = getStorage();
|
|
63
|
+
const probe = `${CHANNEL_PREFIX}:probe`;
|
|
64
|
+
storage.setItem(probe, probe);
|
|
65
|
+
storage.removeItem(probe);
|
|
66
|
+
return true;
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
get(key) {
|
|
72
|
+
try {
|
|
73
|
+
return getStorage().getItem(key);
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
set(key, value) {
|
|
79
|
+
try {
|
|
80
|
+
getStorage().setItem(key, value);
|
|
81
|
+
} finally {
|
|
82
|
+
emitChannel(type, key);
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
remove(key) {
|
|
86
|
+
try {
|
|
87
|
+
getStorage().removeItem(key);
|
|
88
|
+
} finally {
|
|
89
|
+
emitChannel(type, key);
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
subscribe(key, callback) {
|
|
93
|
+
const unsubscribeChannelListener = subscribeChannel(type, key, callback);
|
|
94
|
+
|
|
95
|
+
if (!isBrowser) {
|
|
96
|
+
return unsubscribeChannelListener;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const onStorage = (event: StorageEvent) => {
|
|
100
|
+
if (event.key === key && event.storageArea === getStorage()) {
|
|
101
|
+
callback();
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
window.addEventListener("storage", onStorage);
|
|
106
|
+
|
|
107
|
+
return () => {
|
|
108
|
+
unsubscribeChannelListener();
|
|
109
|
+
window.removeEventListener("storage", onStorage);
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
const encodeCookieValue = (value: string) => encodeURIComponent(value);
|
|
115
|
+
const decodeCookieValue = (value: string) => decodeURIComponent(value);
|
|
116
|
+
|
|
117
|
+
const parseCookieHeader = (cookieHeader: string | null | undefined) => {
|
|
118
|
+
const result = new Map<string, string>();
|
|
119
|
+
|
|
120
|
+
if (!cookieHeader) {
|
|
121
|
+
return result;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
for (const part of cookieHeader.split(";")) {
|
|
125
|
+
const trimmed = part.trim();
|
|
126
|
+
if (!trimmed) {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const separatorIndex = trimmed.indexOf("=");
|
|
131
|
+
if (separatorIndex === -1) {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const key = trimmed.slice(0, separatorIndex).trim();
|
|
136
|
+
const value = trimmed.slice(separatorIndex + 1).trim();
|
|
137
|
+
result.set(key, decodeCookieValue(value));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return result;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export const serializeCookie = (key: string, value: string, options: CookieOptions = {}) => {
|
|
144
|
+
const parts = [`${key}=${encodeCookieValue(value)}`];
|
|
145
|
+
parts.push(`Path=${options.path ?? "/"}`);
|
|
146
|
+
|
|
147
|
+
if (options.expires !== undefined) {
|
|
148
|
+
const expires =
|
|
149
|
+
typeof options.expires === "number"
|
|
150
|
+
? new Date(Date.now() + options.expires * 24 * 60 * 60 * 1000)
|
|
151
|
+
: options.expires;
|
|
152
|
+
parts.push(`Expires=${expires.toUTCString()}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (options.domain) {
|
|
156
|
+
parts.push(`Domain=${options.domain}`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (options.sameSite) {
|
|
160
|
+
parts.push(`SameSite=${options.sameSite}`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (options.secure) {
|
|
164
|
+
parts.push("Secure");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return parts.join("; ");
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const expireCookie = (key: string, options: CookieOptions = {}) =>
|
|
171
|
+
serializeCookie(key, "", { ...options, expires: new Date(0) });
|
|
172
|
+
|
|
173
|
+
const createMemoryCookieContext = (
|
|
174
|
+
cookieHeader?: string,
|
|
175
|
+
onSetCookie?: (header: string) => void,
|
|
176
|
+
): CookieContext => {
|
|
177
|
+
const store = parseCookieHeader(cookieHeader);
|
|
178
|
+
const pendingHeaders: string[] = [];
|
|
179
|
+
const listeners = new Map<string, Set<() => void>>();
|
|
180
|
+
|
|
181
|
+
const emit = (key: string) => {
|
|
182
|
+
const callbacks = listeners.get(key);
|
|
183
|
+
if (!callbacks) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
for (const callback of callbacks) {
|
|
188
|
+
callback();
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
get(key) {
|
|
194
|
+
return store.get(key) ?? null;
|
|
195
|
+
},
|
|
196
|
+
set(key, value, options) {
|
|
197
|
+
store.set(key, value);
|
|
198
|
+
const header = serializeCookie(key, value, options);
|
|
199
|
+
pendingHeaders.push(header);
|
|
200
|
+
onSetCookie?.(header);
|
|
201
|
+
emit(key);
|
|
202
|
+
},
|
|
203
|
+
remove(key, options) {
|
|
204
|
+
store.delete(key);
|
|
205
|
+
const header = expireCookie(key, options);
|
|
206
|
+
pendingHeaders.push(header);
|
|
207
|
+
onSetCookie?.(header);
|
|
208
|
+
emit(key);
|
|
209
|
+
},
|
|
210
|
+
subscribe(key, callback) {
|
|
211
|
+
const callbacks = listeners.get(key) ?? new Set<() => void>();
|
|
212
|
+
callbacks.add(callback);
|
|
213
|
+
listeners.set(key, callbacks);
|
|
214
|
+
|
|
215
|
+
return () => {
|
|
216
|
+
callbacks.delete(callback);
|
|
217
|
+
if (callbacks.size === 0) {
|
|
218
|
+
listeners.delete(key);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
},
|
|
222
|
+
toSetCookieHeaders() {
|
|
223
|
+
return [...pendingHeaders];
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
type CookieContextInput = {
|
|
229
|
+
cookie?: string | Headers | null;
|
|
230
|
+
onSetCookie?: (header: string) => void;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
export const createCookieContext = (
|
|
234
|
+
input?: string | Headers | CookieContextInput,
|
|
235
|
+
): CookieContext => {
|
|
236
|
+
if (typeof Headers !== "undefined" && input instanceof Headers) {
|
|
237
|
+
return createMemoryCookieContext(input.get("cookie") ?? undefined);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (typeof input === "string") {
|
|
241
|
+
return createMemoryCookieContext(input);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const objectInput = input as CookieContextInput | undefined;
|
|
245
|
+
const cookieSource = objectInput?.cookie;
|
|
246
|
+
const onSetCookie = objectInput?.onSetCookie;
|
|
247
|
+
|
|
248
|
+
if (typeof Headers !== "undefined" && cookieSource instanceof Headers) {
|
|
249
|
+
return createMemoryCookieContext(cookieSource.get("cookie") ?? undefined, onSetCookie);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return createMemoryCookieContext(typeof cookieSource === "string" ? cookieSource : undefined, onSetCookie);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const getCookieContext = (options?: PersistedSignalOptions<unknown>) => options?.cookieContext;
|
|
256
|
+
|
|
257
|
+
const getCookie = (key: string, options?: PersistedSignalOptions<unknown>) => {
|
|
258
|
+
const context = getCookieContext(options);
|
|
259
|
+
if (context) {
|
|
260
|
+
return context.get(key);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (!isBrowser) {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
268
|
+
const match = document.cookie.match(new RegExp(`(?:^|; )${escapedKey}=([^;]*)`));
|
|
269
|
+
return match ? decodeCookieValue(match[1]) : null;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const setCookie = (key: string, value: string, options?: PersistedSignalOptions<unknown>) => {
|
|
273
|
+
const context = getCookieContext(options);
|
|
274
|
+
if (context) {
|
|
275
|
+
context.set(key, value, options?.cookie);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (!isBrowser) {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
document.cookie = serializeCookie(key, value, options?.cookie);
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
const removeCookie = (key: string, options?: PersistedSignalOptions<unknown>) => {
|
|
287
|
+
const context = getCookieContext(options);
|
|
288
|
+
if (context) {
|
|
289
|
+
context.remove(key, options?.cookie);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (!isBrowser) {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
document.cookie = expireCookie(key, options?.cookie);
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const cookieDriver: StorageDriver = {
|
|
301
|
+
type: "cookie",
|
|
302
|
+
isAvailable(options) {
|
|
303
|
+
return Boolean(options?.cookieContext) || isBrowser;
|
|
304
|
+
},
|
|
305
|
+
get(key, options) {
|
|
306
|
+
return getCookie(key, options);
|
|
307
|
+
},
|
|
308
|
+
set(key, value, options) {
|
|
309
|
+
setCookie(key, value, options);
|
|
310
|
+
emitChannel("cookie", key);
|
|
311
|
+
},
|
|
312
|
+
remove(key, options) {
|
|
313
|
+
removeCookie(key, options);
|
|
314
|
+
emitChannel("cookie", key);
|
|
315
|
+
},
|
|
316
|
+
subscribe(key, callback, options) {
|
|
317
|
+
const unsubscribeChannelListener = subscribeChannel("cookie", key, callback);
|
|
318
|
+
const unsubscribeContext = options?.cookieContext?.subscribe?.(key, callback) ?? (() => {});
|
|
319
|
+
|
|
320
|
+
return () => {
|
|
321
|
+
unsubscribeChannelListener();
|
|
322
|
+
unsubscribeContext();
|
|
323
|
+
};
|
|
324
|
+
},
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const memoryDriver: StorageDriver = {
|
|
328
|
+
type: "memory",
|
|
329
|
+
isAvailable: () => true,
|
|
330
|
+
get(key) {
|
|
331
|
+
return memoryStore.get(key) ?? null;
|
|
332
|
+
},
|
|
333
|
+
set(key, value) {
|
|
334
|
+
memoryStore.set(key, value);
|
|
335
|
+
emitChannel("memory", key);
|
|
336
|
+
},
|
|
337
|
+
remove(key) {
|
|
338
|
+
memoryStore.delete(key);
|
|
339
|
+
emitChannel("memory", key);
|
|
340
|
+
},
|
|
341
|
+
subscribe(key, callback) {
|
|
342
|
+
return subscribeChannel("memory", key, callback);
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
const getIndexedDbConfig = (options?: PersistedSignalOptions<unknown>) => ({
|
|
347
|
+
database: options?.indexedDB?.database ?? INDEXED_DB_NAME,
|
|
348
|
+
store: options?.indexedDB?.store ?? INDEXED_DB_STORE,
|
|
349
|
+
version: options?.indexedDB?.version ?? 1,
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const requestToPromise = <T>(request: IDBRequest<T>) =>
|
|
353
|
+
new Promise<T>((resolve, reject) => {
|
|
354
|
+
request.onsuccess = () => resolve(request.result);
|
|
355
|
+
request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
const openIndexedDb = async (database: string, store: string, version: number): Promise<IDBDatabase> => {
|
|
359
|
+
const cacheKey = `${database}:${store}:${version}`;
|
|
360
|
+
const existing = indexedDbConnections.get(cacheKey);
|
|
361
|
+
if (existing) {
|
|
362
|
+
return existing;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const connection = new Promise<IDBDatabase>((resolve, reject) => {
|
|
366
|
+
const request = indexedDB.open(database, version);
|
|
367
|
+
|
|
368
|
+
request.onupgradeneeded = () => {
|
|
369
|
+
const db = request.result;
|
|
370
|
+
if (!db.objectStoreNames.contains(store)) {
|
|
371
|
+
db.createObjectStore(store);
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
request.onsuccess = () => {
|
|
376
|
+
const db = request.result;
|
|
377
|
+
|
|
378
|
+
if (!db.objectStoreNames.contains(store)) {
|
|
379
|
+
db.close();
|
|
380
|
+
indexedDbConnections.delete(cacheKey);
|
|
381
|
+
openIndexedDb(database, store, version + 1).then(resolve, reject);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
db.onversionchange = () => {
|
|
386
|
+
db.close();
|
|
387
|
+
indexedDbConnections.delete(cacheKey);
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
resolve(db);
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
request.onerror = () => {
|
|
394
|
+
indexedDbConnections.delete(cacheKey);
|
|
395
|
+
reject(request.error ?? new Error("Failed to open IndexedDB"));
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
request.onblocked = () => {
|
|
399
|
+
indexedDbConnections.delete(cacheKey);
|
|
400
|
+
reject(new Error("IndexedDB open blocked"));
|
|
401
|
+
};
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
indexedDbConnections.set(cacheKey, connection);
|
|
405
|
+
return connection;
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const runIndexedDbTransaction = async <T>(
|
|
409
|
+
mode: IDBTransactionMode,
|
|
410
|
+
key: string,
|
|
411
|
+
options: PersistedSignalOptions<unknown> | undefined,
|
|
412
|
+
operation: (store: IDBObjectStore) => IDBRequest<T>,
|
|
413
|
+
) => {
|
|
414
|
+
const { database, store, version } = getIndexedDbConfig(options);
|
|
415
|
+
const db = await openIndexedDb(database, store, version);
|
|
416
|
+
const transaction = db.transaction(store, mode);
|
|
417
|
+
return requestToPromise(operation(transaction.objectStore(store)));
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
const indexedDbDriver: StorageDriver = {
|
|
421
|
+
type: "indexeddb",
|
|
422
|
+
async: true,
|
|
423
|
+
isAvailable() {
|
|
424
|
+
return isBrowser && typeof indexedDB !== "undefined";
|
|
425
|
+
},
|
|
426
|
+
async get(key, options) {
|
|
427
|
+
try {
|
|
428
|
+
const result = await runIndexedDbTransaction("readonly", key, options, (store) => store.get(key));
|
|
429
|
+
return typeof result === "string" ? result : null;
|
|
430
|
+
} catch {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
},
|
|
434
|
+
async set(key, value, options) {
|
|
435
|
+
try {
|
|
436
|
+
await runIndexedDbTransaction("readwrite", key, options, (store) => store.put(value, key));
|
|
437
|
+
} finally {
|
|
438
|
+
emitChannel("indexeddb", key);
|
|
439
|
+
}
|
|
440
|
+
},
|
|
441
|
+
async remove(key, options) {
|
|
442
|
+
try {
|
|
443
|
+
await runIndexedDbTransaction("readwrite", key, options, (store) => store.delete(key));
|
|
444
|
+
} finally {
|
|
445
|
+
emitChannel("indexeddb", key);
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
subscribe(key, callback) {
|
|
449
|
+
return subscribeChannel("indexeddb", key, callback);
|
|
450
|
+
},
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
const localDriver = createWebStorageDriver("local", () => window.localStorage);
|
|
454
|
+
const sessionDriver = createWebStorageDriver("session", () => window.sessionStorage);
|
|
455
|
+
|
|
456
|
+
export const drivers: Record<PersistedStorage, StorageDriver> = {
|
|
457
|
+
local: localDriver,
|
|
458
|
+
session: sessionDriver,
|
|
459
|
+
cookie: cookieDriver,
|
|
460
|
+
memory: memoryDriver,
|
|
461
|
+
indexeddb: indexedDbDriver,
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
export const resolveDriver = (
|
|
465
|
+
storage: PersistedStorage,
|
|
466
|
+
options?: PersistedSignalOptions<unknown>,
|
|
467
|
+
): StorageDriver => {
|
|
468
|
+
const preferred = drivers[storage];
|
|
469
|
+
return preferred.isAvailable(options) ? preferred : memoryDriver;
|
|
470
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type {
|
|
2
|
+
CookieContext,
|
|
3
|
+
CookieOptions,
|
|
4
|
+
IndexedDBOptions,
|
|
5
|
+
PersistedSignal,
|
|
6
|
+
PersistedSignalOptions,
|
|
7
|
+
PersistedStorage,
|
|
8
|
+
} from "./types";
|
|
9
|
+
export { createCookieContext, serializeCookie } from "./drivers";
|
|
10
|
+
export { persistedSignal } from "./persistedSignal";
|
|
11
|
+
export { usePersistedSignal } from "./usePersistedSignal";
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { effect, signal } from "@preact/signals";
|
|
2
|
+
import { drivers, resolveDriver } from "./drivers";
|
|
3
|
+
import {
|
|
4
|
+
defaultDeserialize,
|
|
5
|
+
defaultSerialize,
|
|
6
|
+
registryKey,
|
|
7
|
+
resolveStorageType,
|
|
8
|
+
type PersistedSignalController,
|
|
9
|
+
} from "./shared";
|
|
10
|
+
import type { CookieOptions, PersistedSignal, PersistedSignalOptions, PersistedStorage } from "./types";
|
|
11
|
+
|
|
12
|
+
type NormalizedCookieOptions = {
|
|
13
|
+
expires: string | number | undefined;
|
|
14
|
+
path: string;
|
|
15
|
+
domain: string | undefined;
|
|
16
|
+
secure: boolean | undefined;
|
|
17
|
+
sameSite: CookieOptions["sameSite"] | undefined;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
type CompatibilitySnapshot = {
|
|
21
|
+
storage: PersistedStorage;
|
|
22
|
+
serialize: unknown;
|
|
23
|
+
deserialize: unknown;
|
|
24
|
+
sync: boolean;
|
|
25
|
+
removeOnUndefined: boolean;
|
|
26
|
+
cookie: NormalizedCookieOptions | undefined;
|
|
27
|
+
indexedDB:
|
|
28
|
+
| {
|
|
29
|
+
database: string;
|
|
30
|
+
store: string;
|
|
31
|
+
version: number;
|
|
32
|
+
}
|
|
33
|
+
| undefined;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
type RegistryEntry = {
|
|
37
|
+
controller: PersistedSignalController<unknown>;
|
|
38
|
+
snapshot: CompatibilitySnapshot;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const globalRegistry = new Map<string, RegistryEntry>();
|
|
42
|
+
const cookieContextRegistry = new WeakMap<object, Map<string, RegistryEntry>>();
|
|
43
|
+
const UNDEFINED_TOKEN = "__KAMOD_SIGNALS_UNDEFINED__";
|
|
44
|
+
|
|
45
|
+
const isPromiseLike = <T>(value: unknown): value is Promise<T> =>
|
|
46
|
+
typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
47
|
+
|
|
48
|
+
const parseStoredValue = <T>(raw: string | null, initialValue: T, deserialize: (raw: string) => T): T => {
|
|
49
|
+
if (raw === null) {
|
|
50
|
+
return initialValue;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (raw === UNDEFINED_TOKEN) {
|
|
54
|
+
return undefined as T;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
return deserialize(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
return initialValue;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const readInitialValue = <T>(
|
|
65
|
+
key: string,
|
|
66
|
+
initialValue: T,
|
|
67
|
+
options: PersistedSignalOptions<T>,
|
|
68
|
+
driver = resolveDriver(resolveStorageType(options.storage), options as PersistedSignalOptions<unknown>),
|
|
69
|
+
): T => {
|
|
70
|
+
const deserialize = options.deserialize ?? defaultDeserialize<T>;
|
|
71
|
+
const raw = driver.get(key, options as PersistedSignalOptions<unknown>);
|
|
72
|
+
|
|
73
|
+
if (isPromiseLike<string | null>(raw)) {
|
|
74
|
+
return initialValue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return parseStoredValue(raw, initialValue, deserialize);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const normalizeCookieOptions = (cookie?: CookieOptions): NormalizedCookieOptions => ({
|
|
81
|
+
expires: cookie?.expires instanceof Date ? cookie.expires.toUTCString() : cookie?.expires,
|
|
82
|
+
path: cookie?.path ?? "/",
|
|
83
|
+
domain: cookie?.domain,
|
|
84
|
+
secure: cookie?.secure,
|
|
85
|
+
sameSite: cookie?.sameSite,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const createCompatibilitySnapshot = <T>(options: PersistedSignalOptions<T>): CompatibilitySnapshot => {
|
|
89
|
+
const storage = resolveStorageType(options.storage);
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
storage,
|
|
93
|
+
serialize: options.serialize ?? defaultSerialize<T>,
|
|
94
|
+
deserialize: options.deserialize ?? defaultDeserialize<T>,
|
|
95
|
+
sync: options.sync ?? true,
|
|
96
|
+
removeOnUndefined: options.removeOnUndefined ?? true,
|
|
97
|
+
cookie: storage === "cookie" ? normalizeCookieOptions(options.cookie) : undefined,
|
|
98
|
+
indexedDB:
|
|
99
|
+
storage === "indexeddb"
|
|
100
|
+
? {
|
|
101
|
+
database: options.indexedDB?.database ?? "@kamod-ch/signals",
|
|
102
|
+
store: options.indexedDB?.store ?? "signals",
|
|
103
|
+
version: options.indexedDB?.version ?? 1,
|
|
104
|
+
}
|
|
105
|
+
: undefined,
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const snapshotsMatch = (left: CompatibilitySnapshot, right: CompatibilitySnapshot) =>
|
|
110
|
+
left.storage === right.storage &&
|
|
111
|
+
left.serialize === right.serialize &&
|
|
112
|
+
left.deserialize === right.deserialize &&
|
|
113
|
+
left.sync === right.sync &&
|
|
114
|
+
left.removeOnUndefined === right.removeOnUndefined &&
|
|
115
|
+
JSON.stringify(left.cookie) === JSON.stringify(right.cookie) &&
|
|
116
|
+
JSON.stringify(left.indexedDB) === JSON.stringify(right.indexedDB);
|
|
117
|
+
|
|
118
|
+
const createOptionConflictError = (id: string) =>
|
|
119
|
+
new Error(`persistedSignal(${id}) received conflicting options for an existing global signal`);
|
|
120
|
+
|
|
121
|
+
const getCompatibleEntry = <T>(entry: RegistryEntry | undefined, snapshot: CompatibilitySnapshot, id: string) => {
|
|
122
|
+
if (!entry) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!snapshotsMatch(entry.snapshot, snapshot)) {
|
|
127
|
+
throw createOptionConflictError(id);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return entry.controller as PersistedSignalController<T>;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const createController = <T>(
|
|
134
|
+
key: string,
|
|
135
|
+
initialValue: T,
|
|
136
|
+
options: PersistedSignalOptions<T> = {},
|
|
137
|
+
): PersistedSignalController<T> => {
|
|
138
|
+
const storage = resolveStorageType(options.storage);
|
|
139
|
+
const driver = resolveDriver(storage, options as PersistedSignalOptions<unknown>);
|
|
140
|
+
const serialize = options.serialize ?? defaultSerialize<T>;
|
|
141
|
+
const deserialize = options.deserialize ?? defaultDeserialize<T>;
|
|
142
|
+
const removeOnUndefined = options.removeOnUndefined ?? true;
|
|
143
|
+
const state = signal<T>(readInitialValue(key, initialValue, options, driver)) as PersistedSignal<T>;
|
|
144
|
+
let isApplyingExternalValue = false;
|
|
145
|
+
let isHydrating = Boolean(driver.async);
|
|
146
|
+
let observedValue = state.value;
|
|
147
|
+
let hasPendingHydrationChange = false;
|
|
148
|
+
|
|
149
|
+
const persistValue = (value: T) => {
|
|
150
|
+
try {
|
|
151
|
+
if (value === undefined && removeOnUndefined) {
|
|
152
|
+
return driver.remove(key, options as PersistedSignalOptions<unknown>);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return driver.set(
|
|
156
|
+
key,
|
|
157
|
+
value === undefined ? UNDEFINED_TOKEN : serialize(value),
|
|
158
|
+
options as PersistedSignalOptions<unknown>,
|
|
159
|
+
);
|
|
160
|
+
} catch {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
state.clear = () => {
|
|
166
|
+
isApplyingExternalValue = true;
|
|
167
|
+
driver.remove(key, options as PersistedSignalOptions<unknown>);
|
|
168
|
+
state.value = initialValue;
|
|
169
|
+
observedValue = state.value;
|
|
170
|
+
isApplyingExternalValue = false;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
state.reset = () => {
|
|
174
|
+
state.value = initialValue;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const stopEffect = effect(() => {
|
|
178
|
+
const value = state.value;
|
|
179
|
+
|
|
180
|
+
if (isApplyingExternalValue) {
|
|
181
|
+
observedValue = value;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (isHydrating) {
|
|
186
|
+
if (!Object.is(value, observedValue)) {
|
|
187
|
+
hasPendingHydrationChange = true;
|
|
188
|
+
}
|
|
189
|
+
observedValue = value;
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
observedValue = value;
|
|
194
|
+
persistValue(value);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
if (driver.async) {
|
|
198
|
+
Promise.resolve(driver.get(key, options as PersistedSignalOptions<unknown>))
|
|
199
|
+
.then((raw) => {
|
|
200
|
+
if (!hasPendingHydrationChange) {
|
|
201
|
+
const nextValue = parseStoredValue(raw, initialValue, deserialize);
|
|
202
|
+
if (!Object.is(nextValue, state.value)) {
|
|
203
|
+
isApplyingExternalValue = true;
|
|
204
|
+
state.value = nextValue;
|
|
205
|
+
observedValue = nextValue;
|
|
206
|
+
isApplyingExternalValue = false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
isHydrating = false;
|
|
211
|
+
|
|
212
|
+
if (hasPendingHydrationChange) {
|
|
213
|
+
persistValue(state.value);
|
|
214
|
+
}
|
|
215
|
+
})
|
|
216
|
+
.catch(() => {
|
|
217
|
+
isHydrating = false;
|
|
218
|
+
if (hasPendingHydrationChange) {
|
|
219
|
+
persistValue(state.value);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const applyExternalRaw = (raw: string | null) => {
|
|
225
|
+
const nextValue = parseStoredValue(raw, initialValue, deserialize);
|
|
226
|
+
|
|
227
|
+
if (Object.is(nextValue, state.value)) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
isApplyingExternalValue = true;
|
|
232
|
+
state.value = nextValue;
|
|
233
|
+
observedValue = nextValue;
|
|
234
|
+
isApplyingExternalValue = false;
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const stopSync = options.sync === false || !driver.subscribe
|
|
238
|
+
? () => {}
|
|
239
|
+
: driver.subscribe(key, () => {
|
|
240
|
+
try {
|
|
241
|
+
const raw = driver.get(key, options as PersistedSignalOptions<unknown>);
|
|
242
|
+
|
|
243
|
+
if (isPromiseLike<string | null>(raw)) {
|
|
244
|
+
raw
|
|
245
|
+
.then((value) => {
|
|
246
|
+
applyExternalRaw(value);
|
|
247
|
+
})
|
|
248
|
+
.catch(() => {
|
|
249
|
+
// ignore malformed external updates
|
|
250
|
+
});
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
applyExternalRaw(raw);
|
|
255
|
+
} catch {
|
|
256
|
+
// ignore malformed external updates
|
|
257
|
+
}
|
|
258
|
+
}, options as PersistedSignalOptions<unknown>);
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
signal: state,
|
|
262
|
+
dispose() {
|
|
263
|
+
stopSync();
|
|
264
|
+
stopEffect();
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
export const persistedSignal = <T>(
|
|
270
|
+
key: string,
|
|
271
|
+
initialValue: T,
|
|
272
|
+
options: PersistedSignalOptions<T> = {},
|
|
273
|
+
): PersistedSignal<T> => {
|
|
274
|
+
const storage = resolveStorageType(options.storage);
|
|
275
|
+
const id = registryKey(storage, key);
|
|
276
|
+
const snapshot = createCompatibilitySnapshot(options);
|
|
277
|
+
const context = storage === "cookie" ? options.cookieContext : undefined;
|
|
278
|
+
|
|
279
|
+
if (context) {
|
|
280
|
+
let scopedRegistry = cookieContextRegistry.get(context as object);
|
|
281
|
+
if (!scopedRegistry) {
|
|
282
|
+
scopedRegistry = new Map<string, RegistryEntry>();
|
|
283
|
+
cookieContextRegistry.set(context as object, scopedRegistry);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const existing = getCompatibleEntry<T>(scopedRegistry.get(id), snapshot, id);
|
|
287
|
+
if (existing) {
|
|
288
|
+
return existing.signal;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const controller = createController(key, initialValue, options);
|
|
292
|
+
scopedRegistry.set(id, { controller: controller as PersistedSignalController<unknown>, snapshot });
|
|
293
|
+
return controller.signal;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const existing = getCompatibleEntry<T>(globalRegistry.get(id), snapshot, id);
|
|
297
|
+
if (existing) {
|
|
298
|
+
return existing.signal;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const controller = createController(key, initialValue, options);
|
|
302
|
+
globalRegistry.set(id, { controller: controller as PersistedSignalController<unknown>, snapshot });
|
|
303
|
+
return controller.signal;
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
export const createPersistedSignal = createController;
|
|
307
|
+
export const __private__ = { createController, readInitialValue, drivers, globalRegistry };
|
package/src/shared.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { PersistedSignal, PersistedSignalOptions, PersistedStorage } from "./types";
|
|
2
|
+
|
|
3
|
+
export interface StorageDriver {
|
|
4
|
+
readonly type: PersistedStorage;
|
|
5
|
+
readonly async?: boolean;
|
|
6
|
+
isAvailable(options?: PersistedSignalOptions<unknown>): boolean;
|
|
7
|
+
get(key: string, options?: PersistedSignalOptions<unknown>): string | null | Promise<string | null>;
|
|
8
|
+
set(key: string, value: string, options?: PersistedSignalOptions<unknown>): void | Promise<void>;
|
|
9
|
+
remove(key: string, options?: PersistedSignalOptions<unknown>): void | Promise<void>;
|
|
10
|
+
subscribe?(key: string, callback: () => void, options?: PersistedSignalOptions<unknown>): () => void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PersistedSignalController<T> {
|
|
14
|
+
signal: PersistedSignal<T>;
|
|
15
|
+
dispose: () => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
|
|
19
|
+
|
|
20
|
+
export const defaultSerialize = <T>(value: T) => JSON.stringify(value);
|
|
21
|
+
export const defaultDeserialize = <T>(raw: string) => JSON.parse(raw) as T;
|
|
22
|
+
|
|
23
|
+
export const resolveStorageType = (storage?: PersistedStorage): PersistedStorage => storage ?? "local";
|
|
24
|
+
|
|
25
|
+
export const registryKey = (storage: PersistedStorage, key: string) => `${storage}:${key}`;
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Signal } from "@preact/signals";
|
|
2
|
+
|
|
3
|
+
export type PersistedStorage = "local" | "session" | "cookie" | "memory" | "indexeddb";
|
|
4
|
+
|
|
5
|
+
export interface CookieOptions {
|
|
6
|
+
expires?: number | Date;
|
|
7
|
+
path?: string;
|
|
8
|
+
domain?: string;
|
|
9
|
+
secure?: boolean;
|
|
10
|
+
sameSite?: "Lax" | "Strict" | "None";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface CookieContext {
|
|
14
|
+
get(key: string): string | null;
|
|
15
|
+
set(key: string, value: string, options?: CookieOptions): void;
|
|
16
|
+
remove(key: string, options?: CookieOptions): void;
|
|
17
|
+
subscribe?(key: string, callback: () => void): () => void;
|
|
18
|
+
toSetCookieHeaders?(): string[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface IndexedDBOptions {
|
|
22
|
+
database?: string;
|
|
23
|
+
store?: string;
|
|
24
|
+
version?: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface PersistedSignalOptions<T> {
|
|
28
|
+
storage?: PersistedStorage;
|
|
29
|
+
serialize?: (value: T) => string;
|
|
30
|
+
deserialize?: (raw: string) => T;
|
|
31
|
+
sync?: boolean;
|
|
32
|
+
removeOnUndefined?: boolean;
|
|
33
|
+
cookie?: CookieOptions;
|
|
34
|
+
cookieContext?: CookieContext;
|
|
35
|
+
indexedDB?: IndexedDBOptions;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface PersistedSignal<T> extends Signal<T> {
|
|
39
|
+
clear(): void;
|
|
40
|
+
reset(): void;
|
|
41
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { useEffect, useMemo } from "preact/hooks";
|
|
2
|
+
import { createPersistedSignal } from "./persistedSignal";
|
|
3
|
+
import { resolveStorageType } from "./shared";
|
|
4
|
+
import type { PersistedSignal, PersistedSignalOptions } from "./types";
|
|
5
|
+
|
|
6
|
+
const cookieDependencyKey = (options: PersistedSignalOptions<unknown>) => {
|
|
7
|
+
const cookie = options.cookie;
|
|
8
|
+
if (!cookie) {
|
|
9
|
+
return "";
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
return JSON.stringify([
|
|
13
|
+
cookie.expires instanceof Date ? cookie.expires.toUTCString() : cookie.expires,
|
|
14
|
+
cookie.path,
|
|
15
|
+
cookie.domain,
|
|
16
|
+
cookie.secure,
|
|
17
|
+
cookie.sameSite,
|
|
18
|
+
]);
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const indexedDbDependencyKey = (options: PersistedSignalOptions<unknown>) =>
|
|
22
|
+
JSON.stringify([
|
|
23
|
+
options.indexedDB?.database ?? "@kamod-ch/signals",
|
|
24
|
+
options.indexedDB?.store ?? "signals",
|
|
25
|
+
options.indexedDB?.version ?? 1,
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
export const usePersistedSignal = <T>(
|
|
29
|
+
key: string,
|
|
30
|
+
initialValue: T,
|
|
31
|
+
options: PersistedSignalOptions<T> = {},
|
|
32
|
+
): PersistedSignal<T> => {
|
|
33
|
+
const controller = useMemo(
|
|
34
|
+
() => createPersistedSignal(key, initialValue, options),
|
|
35
|
+
[
|
|
36
|
+
key,
|
|
37
|
+
initialValue,
|
|
38
|
+
resolveStorageType(options.storage),
|
|
39
|
+
options.sync,
|
|
40
|
+
options.serialize,
|
|
41
|
+
options.deserialize,
|
|
42
|
+
options.removeOnUndefined,
|
|
43
|
+
options.cookieContext,
|
|
44
|
+
cookieDependencyKey(options as PersistedSignalOptions<unknown>),
|
|
45
|
+
indexedDbDependencyKey(options as PersistedSignalOptions<unknown>),
|
|
46
|
+
],
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
useEffect(() => () => controller.dispose(), [controller]);
|
|
50
|
+
|
|
51
|
+
return controller.signal;
|
|
52
|
+
};
|