@kamod-ch/signals 1.0.3 → 1.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/CHANGELOG.md +20 -0
- package/README.md +8 -2
- package/dist/createPersistedModel.d.ts +38 -0
- package/dist/devtools.d.ts +7 -0
- package/dist/devtools.js +31 -0
- package/dist/drivers.d.ts +11 -0
- package/dist/events.d.ts +23 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1160 -0
- package/dist/persistedSignal.d.ts +38 -0
- package/dist/shared.d.ts +19 -0
- package/dist/ssr.d.ts +18 -0
- package/dist/sync.d.ts +16 -0
- package/dist/types.d.ts +43 -0
- package/dist/usePersistedSignal.d.ts +2 -0
- package/dist/versioning.d.ts +32 -0
- package/package.json +21 -17
- package/src/drivers.ts +0 -470
- package/src/index.ts +0 -11
- package/src/persistedSignal.ts +0 -307
- package/src/shared.ts +0 -25
- package/src/types.ts +0 -41
- package/src/usePersistedSignal.ts +0 -52
package/dist/index.js
ADDED
|
@@ -0,0 +1,1160 @@
|
|
|
1
|
+
import { createModel, signal, effect } from '@preact/signals';
|
|
2
|
+
export { Signal, action, batch, computed, createModel, effect, signal, untracked, useModel } from '@preact/signals';
|
|
3
|
+
import { useMemo, useEffect } from 'preact/hooks';
|
|
4
|
+
|
|
5
|
+
// src/index.ts
|
|
6
|
+
|
|
7
|
+
// src/shared.ts
|
|
8
|
+
var isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
|
|
9
|
+
var defaultSerialize = (value) => JSON.stringify(value);
|
|
10
|
+
var defaultDeserialize = (raw) => JSON.parse(raw);
|
|
11
|
+
var resolveStorageType = (storage) => storage ?? "local";
|
|
12
|
+
var registryKey = (storage, key) => `${storage}:${key}`;
|
|
13
|
+
|
|
14
|
+
// src/drivers.ts
|
|
15
|
+
var CHANNEL_PREFIX = "@kamod-ch/signals";
|
|
16
|
+
var INDEXED_DB_NAME = "@kamod-ch/signals";
|
|
17
|
+
var INDEXED_DB_STORE = "signals";
|
|
18
|
+
var memoryStore = /* @__PURE__ */ new Map();
|
|
19
|
+
var memoryListeners = /* @__PURE__ */ new Map();
|
|
20
|
+
var indexedDbConnections = /* @__PURE__ */ new Map();
|
|
21
|
+
var channelName = (storage, key) => `${CHANNEL_PREFIX}:${storage}:${key}`;
|
|
22
|
+
var emitChannel = (storage, key) => {
|
|
23
|
+
const name = channelName(storage, key);
|
|
24
|
+
if (isBrowser) {
|
|
25
|
+
window.dispatchEvent(new CustomEvent(name));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const listeners = memoryListeners.get(name);
|
|
29
|
+
if (!listeners) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const listener of listeners) {
|
|
33
|
+
listener();
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var subscribeChannel = (storage, key, callback) => {
|
|
37
|
+
const name = channelName(storage, key);
|
|
38
|
+
if (isBrowser) {
|
|
39
|
+
const browserListener = () => callback();
|
|
40
|
+
window.addEventListener(name, browserListener);
|
|
41
|
+
return () => {
|
|
42
|
+
window.removeEventListener(name, browserListener);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const listeners = memoryListeners.get(name) ?? /* @__PURE__ */ new Set();
|
|
46
|
+
listeners.add(callback);
|
|
47
|
+
memoryListeners.set(name, listeners);
|
|
48
|
+
return () => {
|
|
49
|
+
listeners.delete(callback);
|
|
50
|
+
if (listeners.size === 0) {
|
|
51
|
+
memoryListeners.delete(name);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
var createWebStorageDriver = (type, getStorage) => ({
|
|
56
|
+
type,
|
|
57
|
+
isAvailable() {
|
|
58
|
+
if (!isBrowser) {
|
|
59
|
+
return false;
|
|
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
|
+
if (!isBrowser) {
|
|
95
|
+
return unsubscribeChannelListener;
|
|
96
|
+
}
|
|
97
|
+
const onStorage = (event) => {
|
|
98
|
+
if (event.key === key && event.storageArea === getStorage()) {
|
|
99
|
+
callback();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
window.addEventListener("storage", onStorage);
|
|
103
|
+
return () => {
|
|
104
|
+
unsubscribeChannelListener();
|
|
105
|
+
window.removeEventListener("storage", onStorage);
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
var encodeCookieValue = (value) => encodeURIComponent(value);
|
|
110
|
+
var decodeCookieValue = (value) => decodeURIComponent(value);
|
|
111
|
+
var parseCookieHeader = (cookieHeader) => {
|
|
112
|
+
const result = /* @__PURE__ */ new Map();
|
|
113
|
+
if (!cookieHeader) {
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
for (const part of cookieHeader.split(";")) {
|
|
117
|
+
const trimmed = part.trim();
|
|
118
|
+
if (!trimmed) {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const separatorIndex = trimmed.indexOf("=");
|
|
122
|
+
if (separatorIndex === -1) {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const key = trimmed.slice(0, separatorIndex).trim();
|
|
126
|
+
const value = trimmed.slice(separatorIndex + 1).trim();
|
|
127
|
+
result.set(key, decodeCookieValue(value));
|
|
128
|
+
}
|
|
129
|
+
return result;
|
|
130
|
+
};
|
|
131
|
+
var serializeCookie = (key, value, options = {}) => {
|
|
132
|
+
const parts = [`${key}=${encodeCookieValue(value)}`];
|
|
133
|
+
parts.push(`Path=${options.path ?? "/"}`);
|
|
134
|
+
if (options.expires !== void 0) {
|
|
135
|
+
const expires = typeof options.expires === "number" ? new Date(Date.now() + options.expires * 24 * 60 * 60 * 1e3) : options.expires;
|
|
136
|
+
parts.push(`Expires=${expires.toUTCString()}`);
|
|
137
|
+
}
|
|
138
|
+
if (options.domain) {
|
|
139
|
+
parts.push(`Domain=${options.domain}`);
|
|
140
|
+
}
|
|
141
|
+
if (options.sameSite) {
|
|
142
|
+
parts.push(`SameSite=${options.sameSite}`);
|
|
143
|
+
}
|
|
144
|
+
if (options.secure) {
|
|
145
|
+
parts.push("Secure");
|
|
146
|
+
}
|
|
147
|
+
return parts.join("; ");
|
|
148
|
+
};
|
|
149
|
+
var expireCookie = (key, options = {}) => serializeCookie(key, "", { ...options, expires: /* @__PURE__ */ new Date(0) });
|
|
150
|
+
var createMemoryCookieContext = (cookieHeader, onSetCookie) => {
|
|
151
|
+
const store = parseCookieHeader(cookieHeader);
|
|
152
|
+
const pendingHeaders = [];
|
|
153
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
154
|
+
const emit = (key) => {
|
|
155
|
+
const callbacks = listeners.get(key);
|
|
156
|
+
if (!callbacks) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
for (const callback of callbacks) {
|
|
160
|
+
callback();
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
get(key) {
|
|
165
|
+
return store.get(key) ?? null;
|
|
166
|
+
},
|
|
167
|
+
set(key, value, options) {
|
|
168
|
+
store.set(key, value);
|
|
169
|
+
const header = serializeCookie(key, value, options);
|
|
170
|
+
pendingHeaders.push(header);
|
|
171
|
+
onSetCookie?.(header);
|
|
172
|
+
emit(key);
|
|
173
|
+
},
|
|
174
|
+
remove(key, options) {
|
|
175
|
+
store.delete(key);
|
|
176
|
+
const header = expireCookie(key, options);
|
|
177
|
+
pendingHeaders.push(header);
|
|
178
|
+
onSetCookie?.(header);
|
|
179
|
+
emit(key);
|
|
180
|
+
},
|
|
181
|
+
subscribe(key, callback) {
|
|
182
|
+
const callbacks = listeners.get(key) ?? /* @__PURE__ */ new Set();
|
|
183
|
+
callbacks.add(callback);
|
|
184
|
+
listeners.set(key, callbacks);
|
|
185
|
+
return () => {
|
|
186
|
+
callbacks.delete(callback);
|
|
187
|
+
if (callbacks.size === 0) {
|
|
188
|
+
listeners.delete(key);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
toSetCookieHeaders() {
|
|
193
|
+
return [...pendingHeaders];
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
var createCookieContext = (input) => {
|
|
198
|
+
if (typeof Headers !== "undefined" && input instanceof Headers) {
|
|
199
|
+
return createMemoryCookieContext(input.get("cookie") ?? void 0);
|
|
200
|
+
}
|
|
201
|
+
if (typeof input === "string") {
|
|
202
|
+
return createMemoryCookieContext(input);
|
|
203
|
+
}
|
|
204
|
+
const objectInput = input;
|
|
205
|
+
const cookieSource = objectInput?.cookie;
|
|
206
|
+
const onSetCookie = objectInput?.onSetCookie;
|
|
207
|
+
if (typeof Headers !== "undefined" && cookieSource instanceof Headers) {
|
|
208
|
+
return createMemoryCookieContext(cookieSource.get("cookie") ?? void 0, onSetCookie);
|
|
209
|
+
}
|
|
210
|
+
return createMemoryCookieContext(typeof cookieSource === "string" ? cookieSource : void 0, onSetCookie);
|
|
211
|
+
};
|
|
212
|
+
var getCookieContext = (options) => options?.cookieContext;
|
|
213
|
+
var getCookie = (key, options) => {
|
|
214
|
+
const context = getCookieContext(options);
|
|
215
|
+
if (context) {
|
|
216
|
+
return context.get(key);
|
|
217
|
+
}
|
|
218
|
+
if (!isBrowser) {
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
222
|
+
const match = document.cookie.match(new RegExp(`(?:^|; )${escapedKey}=([^;]*)`));
|
|
223
|
+
return match ? decodeCookieValue(match[1]) : null;
|
|
224
|
+
};
|
|
225
|
+
var setCookie = (key, value, options) => {
|
|
226
|
+
const context = getCookieContext(options);
|
|
227
|
+
if (context) {
|
|
228
|
+
context.set(key, value, options?.cookie);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (!isBrowser) {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
document.cookie = serializeCookie(key, value, options?.cookie);
|
|
235
|
+
};
|
|
236
|
+
var removeCookie = (key, options) => {
|
|
237
|
+
const context = getCookieContext(options);
|
|
238
|
+
if (context) {
|
|
239
|
+
context.remove(key, options?.cookie);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (!isBrowser) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
document.cookie = expireCookie(key, options?.cookie);
|
|
246
|
+
};
|
|
247
|
+
var cookieDriver = {
|
|
248
|
+
type: "cookie",
|
|
249
|
+
isAvailable(options) {
|
|
250
|
+
return Boolean(options?.cookieContext) || isBrowser;
|
|
251
|
+
},
|
|
252
|
+
get(key, options) {
|
|
253
|
+
return getCookie(key, options);
|
|
254
|
+
},
|
|
255
|
+
set(key, value, options) {
|
|
256
|
+
setCookie(key, value, options);
|
|
257
|
+
emitChannel("cookie", key);
|
|
258
|
+
},
|
|
259
|
+
remove(key, options) {
|
|
260
|
+
removeCookie(key, options);
|
|
261
|
+
emitChannel("cookie", key);
|
|
262
|
+
},
|
|
263
|
+
subscribe(key, callback, options) {
|
|
264
|
+
const unsubscribeChannelListener = subscribeChannel("cookie", key, callback);
|
|
265
|
+
const unsubscribeContext = options?.cookieContext?.subscribe?.(key, callback) ?? (() => {
|
|
266
|
+
});
|
|
267
|
+
return () => {
|
|
268
|
+
unsubscribeChannelListener();
|
|
269
|
+
unsubscribeContext();
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
var memoryDriver = {
|
|
274
|
+
type: "memory",
|
|
275
|
+
isAvailable: () => true,
|
|
276
|
+
get(key) {
|
|
277
|
+
return memoryStore.get(key) ?? null;
|
|
278
|
+
},
|
|
279
|
+
set(key, value) {
|
|
280
|
+
memoryStore.set(key, value);
|
|
281
|
+
emitChannel("memory", key);
|
|
282
|
+
},
|
|
283
|
+
remove(key) {
|
|
284
|
+
memoryStore.delete(key);
|
|
285
|
+
emitChannel("memory", key);
|
|
286
|
+
},
|
|
287
|
+
subscribe(key, callback) {
|
|
288
|
+
return subscribeChannel("memory", key, callback);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
var getIndexedDbConfig = (options) => ({
|
|
292
|
+
database: options?.indexedDB?.database ?? INDEXED_DB_NAME,
|
|
293
|
+
store: options?.indexedDB?.store ?? INDEXED_DB_STORE,
|
|
294
|
+
version: options?.indexedDB?.version ?? 1
|
|
295
|
+
});
|
|
296
|
+
var requestToPromise = (request) => new Promise((resolve, reject) => {
|
|
297
|
+
request.onsuccess = () => resolve(request.result);
|
|
298
|
+
request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));
|
|
299
|
+
});
|
|
300
|
+
var openIndexedDb = async (database, store, version) => {
|
|
301
|
+
const cacheKey = `${database}:${store}:${version}`;
|
|
302
|
+
const existing = indexedDbConnections.get(cacheKey);
|
|
303
|
+
if (existing) {
|
|
304
|
+
return existing;
|
|
305
|
+
}
|
|
306
|
+
const connection = new Promise((resolve, reject) => {
|
|
307
|
+
const request = indexedDB.open(database, version);
|
|
308
|
+
request.onupgradeneeded = () => {
|
|
309
|
+
const db = request.result;
|
|
310
|
+
if (!db.objectStoreNames.contains(store)) {
|
|
311
|
+
db.createObjectStore(store);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
request.onsuccess = () => {
|
|
315
|
+
const db = request.result;
|
|
316
|
+
if (!db.objectStoreNames.contains(store)) {
|
|
317
|
+
db.close();
|
|
318
|
+
indexedDbConnections.delete(cacheKey);
|
|
319
|
+
openIndexedDb(database, store, version + 1).then(resolve, reject);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
db.onversionchange = () => {
|
|
323
|
+
db.close();
|
|
324
|
+
indexedDbConnections.delete(cacheKey);
|
|
325
|
+
};
|
|
326
|
+
resolve(db);
|
|
327
|
+
};
|
|
328
|
+
request.onerror = () => {
|
|
329
|
+
indexedDbConnections.delete(cacheKey);
|
|
330
|
+
reject(request.error ?? new Error("Failed to open IndexedDB"));
|
|
331
|
+
};
|
|
332
|
+
request.onblocked = () => {
|
|
333
|
+
indexedDbConnections.delete(cacheKey);
|
|
334
|
+
reject(new Error("IndexedDB open blocked"));
|
|
335
|
+
};
|
|
336
|
+
});
|
|
337
|
+
indexedDbConnections.set(cacheKey, connection);
|
|
338
|
+
return connection;
|
|
339
|
+
};
|
|
340
|
+
var runIndexedDbTransaction = async (mode, key, options, operation) => {
|
|
341
|
+
const { database, store, version } = getIndexedDbConfig(options);
|
|
342
|
+
const db = await openIndexedDb(database, store, version);
|
|
343
|
+
const transaction = db.transaction(store, mode);
|
|
344
|
+
return requestToPromise(operation(transaction.objectStore(store)));
|
|
345
|
+
};
|
|
346
|
+
var indexedDbDriver = {
|
|
347
|
+
type: "indexeddb",
|
|
348
|
+
async: true,
|
|
349
|
+
isAvailable() {
|
|
350
|
+
return isBrowser && typeof indexedDB !== "undefined";
|
|
351
|
+
},
|
|
352
|
+
async get(key, options) {
|
|
353
|
+
try {
|
|
354
|
+
const result = await runIndexedDbTransaction("readonly", key, options, (store) => store.get(key));
|
|
355
|
+
return typeof result === "string" ? result : null;
|
|
356
|
+
} catch {
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
async set(key, value, options) {
|
|
361
|
+
try {
|
|
362
|
+
await runIndexedDbTransaction("readwrite", key, options, (store) => store.put(value, key));
|
|
363
|
+
} finally {
|
|
364
|
+
emitChannel("indexeddb", key);
|
|
365
|
+
}
|
|
366
|
+
},
|
|
367
|
+
async remove(key, options) {
|
|
368
|
+
try {
|
|
369
|
+
await runIndexedDbTransaction("readwrite", key, options, (store) => store.delete(key));
|
|
370
|
+
} finally {
|
|
371
|
+
emitChannel("indexeddb", key);
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
subscribe(key, callback) {
|
|
375
|
+
return subscribeChannel("indexeddb", key, callback);
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
var localDriver = createWebStorageDriver("local", () => window.localStorage);
|
|
379
|
+
var sessionDriver = createWebStorageDriver("session", () => window.sessionStorage);
|
|
380
|
+
var drivers = {
|
|
381
|
+
local: localDriver,
|
|
382
|
+
session: sessionDriver,
|
|
383
|
+
cookie: cookieDriver,
|
|
384
|
+
memory: memoryDriver,
|
|
385
|
+
indexeddb: indexedDbDriver
|
|
386
|
+
};
|
|
387
|
+
var resolveDriver = (storage, options) => {
|
|
388
|
+
const preferred = drivers[storage];
|
|
389
|
+
return preferred.isAvailable(options) ? preferred : memoryDriver;
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
// src/events.ts
|
|
393
|
+
var createPersistedEventTarget = (options = {}) => {
|
|
394
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
395
|
+
return {
|
|
396
|
+
subscribe(listener) {
|
|
397
|
+
listeners.add(listener);
|
|
398
|
+
return () => listeners.delete(listener);
|
|
399
|
+
},
|
|
400
|
+
emit(event) {
|
|
401
|
+
const safeEvent = options.includeSnapshots ? event : { ...event, snapshot: event.snapshot === void 0 ? void 0 : "[redacted]" };
|
|
402
|
+
for (const listener of listeners) {
|
|
403
|
+
try {
|
|
404
|
+
listener(safeEvent);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
options.onListenerError?.(error, safeEvent);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
dispose() {
|
|
411
|
+
listeners.clear();
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
};
|
|
415
|
+
var emitPersistedEvent = (target, event) => {
|
|
416
|
+
target?.emit({ ...event, timestamp: Date.now() });
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
// src/ssr.ts
|
|
420
|
+
var globalHydrationState = /* @__PURE__ */ new Map();
|
|
421
|
+
var toMap = (state) => new Map(Object.entries(state ?? {}));
|
|
422
|
+
var createPersistedScope = (options = {}) => {
|
|
423
|
+
const snapshots = toMap(options.initialState);
|
|
424
|
+
let disposed = false;
|
|
425
|
+
return {
|
|
426
|
+
cookieContext: options.cookieContext,
|
|
427
|
+
get(key) {
|
|
428
|
+
return snapshots.get(key);
|
|
429
|
+
},
|
|
430
|
+
set(key, value) {
|
|
431
|
+
if (!disposed) {
|
|
432
|
+
snapshots.set(key, value);
|
|
433
|
+
}
|
|
434
|
+
},
|
|
435
|
+
dehydrate() {
|
|
436
|
+
return disposed ? {} : Object.fromEntries(snapshots.entries());
|
|
437
|
+
},
|
|
438
|
+
dispose() {
|
|
439
|
+
disposed = true;
|
|
440
|
+
snapshots.clear();
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
};
|
|
444
|
+
var dehydratePersisted = (scope) => scope.dehydrate();
|
|
445
|
+
var hydratePersisted = (state) => {
|
|
446
|
+
globalHydrationState = toMap(state);
|
|
447
|
+
};
|
|
448
|
+
var consumeHydratedPersistedValue = (key) => {
|
|
449
|
+
if (!globalHydrationState.has(key)) {
|
|
450
|
+
return void 0;
|
|
451
|
+
}
|
|
452
|
+
const value = globalHydrationState.get(key);
|
|
453
|
+
globalHydrationState.delete(key);
|
|
454
|
+
return value;
|
|
455
|
+
};
|
|
456
|
+
var serializePersistedStateForHtml = (state) => JSON.stringify(state).replace(/</g, "\\u003C").replace(/>/g, "\\u003E").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
457
|
+
|
|
458
|
+
// src/sync.ts
|
|
459
|
+
var STORAGE_PREFIX = "@kamod-ch/signals:sync:";
|
|
460
|
+
var sourceCounter = 0;
|
|
461
|
+
var createPersistedSyncSource = () => `${Date.now().toString(36)}-${(sourceCounter += 1).toString(36)}`;
|
|
462
|
+
var comparePersistedSyncMessages = (left, right) => {
|
|
463
|
+
if (left.revision !== right.revision) {
|
|
464
|
+
return left.revision - right.revision;
|
|
465
|
+
}
|
|
466
|
+
return left.source.localeCompare(right.source);
|
|
467
|
+
};
|
|
468
|
+
var createBroadcastSyncTransport = (channel) => {
|
|
469
|
+
if (typeof window === "undefined" || typeof document === "undefined") {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
if (typeof BroadcastChannel !== "undefined") {
|
|
473
|
+
const broadcastChannel = new BroadcastChannel(channel);
|
|
474
|
+
return {
|
|
475
|
+
post(message) {
|
|
476
|
+
broadcastChannel.postMessage(message);
|
|
477
|
+
},
|
|
478
|
+
subscribe(listener) {
|
|
479
|
+
const onMessage = (event) => listener(event.data);
|
|
480
|
+
broadcastChannel.addEventListener("message", onMessage);
|
|
481
|
+
return () => broadcastChannel.removeEventListener("message", onMessage);
|
|
482
|
+
},
|
|
483
|
+
dispose() {
|
|
484
|
+
broadcastChannel.close();
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
if (typeof window === "undefined" || typeof window.localStorage === "undefined") {
|
|
489
|
+
return null;
|
|
490
|
+
}
|
|
491
|
+
const storageKey = `${STORAGE_PREFIX}${channel}`;
|
|
492
|
+
return {
|
|
493
|
+
post(message) {
|
|
494
|
+
window.localStorage.setItem(storageKey, JSON.stringify(message));
|
|
495
|
+
},
|
|
496
|
+
subscribe(listener) {
|
|
497
|
+
const onStorage = (event) => {
|
|
498
|
+
if (event.key !== storageKey || !event.newValue) {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
try {
|
|
502
|
+
listener(JSON.parse(event.newValue));
|
|
503
|
+
} catch {
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
window.addEventListener("storage", onStorage);
|
|
507
|
+
return () => window.removeEventListener("storage", onStorage);
|
|
508
|
+
},
|
|
509
|
+
dispose() {
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
};
|
|
513
|
+
var memoryChannels = /* @__PURE__ */ new Map();
|
|
514
|
+
var createMemorySyncTransport = (channel) => {
|
|
515
|
+
let disposed = false;
|
|
516
|
+
const listeners = memoryChannels.get(channel) ?? /* @__PURE__ */ new Set();
|
|
517
|
+
memoryChannels.set(channel, listeners);
|
|
518
|
+
return {
|
|
519
|
+
post(message) {
|
|
520
|
+
if (disposed) {
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
for (const listener of listeners) {
|
|
524
|
+
queueMicrotask(() => listener(message));
|
|
525
|
+
}
|
|
526
|
+
},
|
|
527
|
+
subscribe(listener) {
|
|
528
|
+
const untypedListener = listener;
|
|
529
|
+
listeners.add(untypedListener);
|
|
530
|
+
return () => {
|
|
531
|
+
listeners.delete(untypedListener);
|
|
532
|
+
if (listeners.size === 0) {
|
|
533
|
+
memoryChannels.delete(channel);
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
},
|
|
537
|
+
dispose() {
|
|
538
|
+
disposed = true;
|
|
539
|
+
listeners.delete(() => {
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
// src/versioning.ts
|
|
546
|
+
var FuturePersistedVersionError = class extends Error {
|
|
547
|
+
constructor(persistedVersion, supportedVersion) {
|
|
548
|
+
super(`Persisted payload version ${persistedVersion} is newer than supported version ${supportedVersion}`);
|
|
549
|
+
this.persistedVersion = persistedVersion;
|
|
550
|
+
this.supportedVersion = supportedVersion;
|
|
551
|
+
this.name = "FuturePersistedVersionError";
|
|
552
|
+
}
|
|
553
|
+
persistedVersion;
|
|
554
|
+
supportedVersion;
|
|
555
|
+
};
|
|
556
|
+
var PersistedValidationError = class extends Error {
|
|
557
|
+
constructor() {
|
|
558
|
+
super("Persisted payload validation failed");
|
|
559
|
+
this.name = "PersistedValidationError";
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
var isPersistedEnvelope = (value) => typeof value === "object" && value !== null && value.__kamod === "signals" && typeof value.v === "number" && "data" in value;
|
|
563
|
+
var serializePersistedValue = (value, options, serialize) => {
|
|
564
|
+
if (options.version === void 0) {
|
|
565
|
+
return serialize(value);
|
|
566
|
+
}
|
|
567
|
+
return JSON.stringify({ __kamod: "signals", v: options.version, data: value });
|
|
568
|
+
};
|
|
569
|
+
var validateSnapshot = (snapshot, options) => {
|
|
570
|
+
if (options.validate && !options.validate(snapshot)) {
|
|
571
|
+
throw new PersistedValidationError();
|
|
572
|
+
}
|
|
573
|
+
return snapshot;
|
|
574
|
+
};
|
|
575
|
+
var deserializePersistedValue = (raw, options, deserialize) => {
|
|
576
|
+
if (options.version === void 0) {
|
|
577
|
+
const value = deserialize(raw);
|
|
578
|
+
return { value: validateSnapshot(value, options), migrated: false };
|
|
579
|
+
}
|
|
580
|
+
const parsed = JSON.parse(raw);
|
|
581
|
+
const currentVersion = options.version;
|
|
582
|
+
const legacyVersion = options.legacyVersion ?? 0;
|
|
583
|
+
const fromVersion = isPersistedEnvelope(parsed) ? parsed.v : legacyVersion;
|
|
584
|
+
const snapshot = isPersistedEnvelope(parsed) ? parsed.data : deserialize(raw);
|
|
585
|
+
if (fromVersion > currentVersion) {
|
|
586
|
+
throw new FuturePersistedVersionError(fromVersion, currentVersion);
|
|
587
|
+
}
|
|
588
|
+
if (fromVersion === currentVersion) {
|
|
589
|
+
return { value: validateSnapshot(snapshot, options), migrated: false };
|
|
590
|
+
}
|
|
591
|
+
if (!options.migrate) {
|
|
592
|
+
return { value: validateSnapshot(snapshot, options), migrated: false };
|
|
593
|
+
}
|
|
594
|
+
const migrated = options.migrate(snapshot, fromVersion);
|
|
595
|
+
if (migrated && typeof migrated === "object" && "then" in migrated) {
|
|
596
|
+
throw new TypeError("Asynchronous migrations require an asynchronous persistence pipeline");
|
|
597
|
+
}
|
|
598
|
+
return { value: validateSnapshot(migrated, options), migrated: true };
|
|
599
|
+
};
|
|
600
|
+
var deserializePersistedValueAsync = async (raw, options, deserialize) => {
|
|
601
|
+
if (options.version === void 0) {
|
|
602
|
+
const value = deserialize(raw);
|
|
603
|
+
return { value: validateSnapshot(value, options), migrated: false };
|
|
604
|
+
}
|
|
605
|
+
const parsed = JSON.parse(raw);
|
|
606
|
+
const currentVersion = options.version;
|
|
607
|
+
const legacyVersion = options.legacyVersion ?? 0;
|
|
608
|
+
const fromVersion = isPersistedEnvelope(parsed) ? parsed.v : legacyVersion;
|
|
609
|
+
const snapshot = isPersistedEnvelope(parsed) ? parsed.data : deserialize(raw);
|
|
610
|
+
if (fromVersion > currentVersion) {
|
|
611
|
+
throw new FuturePersistedVersionError(fromVersion, currentVersion);
|
|
612
|
+
}
|
|
613
|
+
if (fromVersion === currentVersion) {
|
|
614
|
+
return { value: validateSnapshot(snapshot, options), migrated: false };
|
|
615
|
+
}
|
|
616
|
+
if (!options.migrate) {
|
|
617
|
+
return { value: validateSnapshot(snapshot, options), migrated: false };
|
|
618
|
+
}
|
|
619
|
+
const migrated = await options.migrate(snapshot, fromVersion);
|
|
620
|
+
return { value: validateSnapshot(migrated, options), migrated: true };
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
// src/createPersistedModel.ts
|
|
624
|
+
var isPromiseLike = (value) => typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
625
|
+
var toStorageOptions = (options) => ({
|
|
626
|
+
storage: options.storage,
|
|
627
|
+
serialize: options.serialize,
|
|
628
|
+
deserialize: options.deserialize,
|
|
629
|
+
sync: typeof options.sync === "boolean" ? options.sync : void 0,
|
|
630
|
+
cookie: options.cookie,
|
|
631
|
+
cookieContext: options.cookieContext,
|
|
632
|
+
indexedDB: options.indexedDB
|
|
633
|
+
});
|
|
634
|
+
var createPersistedModel = (options, factory) => {
|
|
635
|
+
const PersistedModelConstructor = createModel((...args) => {
|
|
636
|
+
const model = factory(...args);
|
|
637
|
+
const storageOptions = toStorageOptions(options);
|
|
638
|
+
const storage = resolveStorageType(options.storage);
|
|
639
|
+
const driver = resolveDriver(storage, storageOptions);
|
|
640
|
+
const serialize = options.serialize ?? defaultSerialize;
|
|
641
|
+
const deserialize = options.deserialize ?? defaultDeserialize;
|
|
642
|
+
const hydration = signal("idle");
|
|
643
|
+
const error = signal(null);
|
|
644
|
+
const initialSnapshot = options.select(model);
|
|
645
|
+
const scopedSnapshot = options.scope?.get(options.key);
|
|
646
|
+
const hydratedSnapshot = scopedSnapshot ?? consumeHydratedPersistedValue(options.key);
|
|
647
|
+
let isHydrating = true;
|
|
648
|
+
let isApplyingSnapshot = false;
|
|
649
|
+
let isDisposed = false;
|
|
650
|
+
let hasPendingHydrationChange = false;
|
|
651
|
+
let hasSeenSnapshot = false;
|
|
652
|
+
let persistenceBlocked = false;
|
|
653
|
+
let isApplyingRemoteSnapshot = false;
|
|
654
|
+
let revision = 0;
|
|
655
|
+
let lastAcceptedMessage = { revision: 0, source: "" };
|
|
656
|
+
const syncSource = createPersistedSyncSource();
|
|
657
|
+
const syncTransport = options.sync === "tabs" ? createBroadcastSyncTransport(`@kamod-ch/signals:${options.key}`) : typeof options.sync === "object" ? options.sync : null;
|
|
658
|
+
let stopSync = () => {
|
|
659
|
+
};
|
|
660
|
+
let stopTransport = () => {
|
|
661
|
+
};
|
|
662
|
+
let stopPersistEffect = () => {
|
|
663
|
+
};
|
|
664
|
+
let stopDisposeEffect = () => {
|
|
665
|
+
};
|
|
666
|
+
const eventBase = () => ({ key: options.key, storage });
|
|
667
|
+
const eventSnapshot = (snapshot) => options.includeEventSnapshots ? snapshot : void 0;
|
|
668
|
+
const persistSnapshot = async (snapshot) => {
|
|
669
|
+
if (isDisposed) {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
try {
|
|
673
|
+
if (persistenceBlocked) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "persist:start", snapshot: eventSnapshot(snapshot) });
|
|
677
|
+
options.scope?.set(options.key, snapshot);
|
|
678
|
+
revision += 1;
|
|
679
|
+
await driver.set(
|
|
680
|
+
options.key,
|
|
681
|
+
serializePersistedValue(snapshot, options, serialize),
|
|
682
|
+
storageOptions
|
|
683
|
+
);
|
|
684
|
+
if (!isApplyingRemoteSnapshot) {
|
|
685
|
+
syncTransport?.post({
|
|
686
|
+
key: options.key,
|
|
687
|
+
source: syncSource,
|
|
688
|
+
revision,
|
|
689
|
+
version: options.version,
|
|
690
|
+
payload: snapshot
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
error.value = null;
|
|
694
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "persist:success", snapshot: eventSnapshot(snapshot) });
|
|
695
|
+
} catch (persistError) {
|
|
696
|
+
error.value = persistError;
|
|
697
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "persist:error", error: persistError });
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
const applySnapshot = async (snapshot) => {
|
|
701
|
+
if (isDisposed) {
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
isApplyingSnapshot = true;
|
|
705
|
+
try {
|
|
706
|
+
await options.apply(model, snapshot);
|
|
707
|
+
error.value = null;
|
|
708
|
+
} catch (applyError) {
|
|
709
|
+
error.value = applyError;
|
|
710
|
+
} finally {
|
|
711
|
+
isApplyingSnapshot = false;
|
|
712
|
+
}
|
|
713
|
+
};
|
|
714
|
+
const applyRaw = async (raw) => {
|
|
715
|
+
if (raw === null) {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
try {
|
|
719
|
+
if (options.version !== void 0) {
|
|
720
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "migrate:start" });
|
|
721
|
+
}
|
|
722
|
+
const parsed = await deserializePersistedValueAsync(raw, options, deserialize);
|
|
723
|
+
persistenceBlocked = false;
|
|
724
|
+
await applySnapshot(parsed.value);
|
|
725
|
+
if (parsed.migrated) {
|
|
726
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "migrate:success", snapshot: eventSnapshot(parsed.value) });
|
|
727
|
+
await persistSnapshot(parsed.value);
|
|
728
|
+
}
|
|
729
|
+
} catch (deserializeError) {
|
|
730
|
+
if (options.migrationErrorStrategy === "throw") {
|
|
731
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "migrate:error", error: deserializeError });
|
|
732
|
+
throw deserializeError;
|
|
733
|
+
}
|
|
734
|
+
persistenceBlocked = deserializeError instanceof FuturePersistedVersionError || options.migrationErrorStrategy !== "reset";
|
|
735
|
+
error.value = deserializeError;
|
|
736
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "migrate:error", error: deserializeError });
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
const hydrate = async () => {
|
|
740
|
+
if (isDisposed) {
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
isHydrating = true;
|
|
744
|
+
hydration.value = "loading";
|
|
745
|
+
error.value = null;
|
|
746
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "hydrate:start" });
|
|
747
|
+
try {
|
|
748
|
+
if (hydratedSnapshot !== void 0) {
|
|
749
|
+
await applySnapshot(hydratedSnapshot);
|
|
750
|
+
options.scope?.set(options.key, hydratedSnapshot);
|
|
751
|
+
hydration.value = "ready";
|
|
752
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "hydrate:success", snapshot: eventSnapshot(hydratedSnapshot) });
|
|
753
|
+
} else {
|
|
754
|
+
const raw = await driver.get(options.key, storageOptions);
|
|
755
|
+
await applyRaw(raw);
|
|
756
|
+
options.scope?.set(options.key, options.select(model));
|
|
757
|
+
hydration.value = "ready";
|
|
758
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "hydrate:success", snapshot: eventSnapshot(options.select(model)) });
|
|
759
|
+
}
|
|
760
|
+
} catch (hydrateError) {
|
|
761
|
+
error.value = hydrateError;
|
|
762
|
+
hydration.value = "error";
|
|
763
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "hydrate:error", error: hydrateError });
|
|
764
|
+
} finally {
|
|
765
|
+
isHydrating = false;
|
|
766
|
+
}
|
|
767
|
+
if (hasPendingHydrationChange) {
|
|
768
|
+
hasPendingHydrationChange = false;
|
|
769
|
+
await persistSnapshot(options.select(model));
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
const applyRemoteMessage = async (message) => {
|
|
773
|
+
if (message.key !== options.key || message.source === syncSource) {
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "sync:receive", metadata: { source: message.source, revision: message.revision } });
|
|
777
|
+
if (comparePersistedSyncMessages(message, lastAcceptedMessage) <= 0) {
|
|
778
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "sync:reject", metadata: { reason: "stale", source: message.source, revision: message.revision } });
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
try {
|
|
782
|
+
const remotePayload = message.version === void 0 ? message.payload : { __kamod: "signals", v: message.version, data: message.payload };
|
|
783
|
+
const parsed = await deserializePersistedValueAsync(
|
|
784
|
+
JSON.stringify(remotePayload),
|
|
785
|
+
options,
|
|
786
|
+
(raw) => JSON.parse(raw)
|
|
787
|
+
);
|
|
788
|
+
lastAcceptedMessage = { revision: message.revision, source: message.source };
|
|
789
|
+
revision = Math.max(revision, message.revision);
|
|
790
|
+
isApplyingRemoteSnapshot = true;
|
|
791
|
+
await applySnapshot(parsed.value);
|
|
792
|
+
} catch (syncError) {
|
|
793
|
+
error.value = syncError;
|
|
794
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "sync:reject", error: syncError, metadata: { source: message.source, revision: message.revision } });
|
|
795
|
+
} finally {
|
|
796
|
+
isApplyingRemoteSnapshot = false;
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
const flush = async () => {
|
|
800
|
+
await persistSnapshot(options.select(model));
|
|
801
|
+
};
|
|
802
|
+
const reset = async () => {
|
|
803
|
+
persistenceBlocked = false;
|
|
804
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "reset" });
|
|
805
|
+
await applySnapshot(initialSnapshot);
|
|
806
|
+
await flush();
|
|
807
|
+
};
|
|
808
|
+
const dispose = () => {
|
|
809
|
+
if (isDisposed) {
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
isDisposed = true;
|
|
813
|
+
emitPersistedEvent(options.events, { ...eventBase(), type: "dispose" });
|
|
814
|
+
stopSync();
|
|
815
|
+
stopTransport();
|
|
816
|
+
syncTransport?.dispose();
|
|
817
|
+
stopPersistEffect();
|
|
818
|
+
stopDisposeEffect();
|
|
819
|
+
hydration.value = "idle";
|
|
820
|
+
};
|
|
821
|
+
stopPersistEffect = effect(() => {
|
|
822
|
+
const snapshot = options.select(model);
|
|
823
|
+
if (isDisposed || isApplyingSnapshot) {
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
if (!hasSeenSnapshot) {
|
|
827
|
+
hasSeenSnapshot = true;
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (isHydrating) {
|
|
831
|
+
hasPendingHydrationChange = true;
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
void persistSnapshot(snapshot);
|
|
835
|
+
});
|
|
836
|
+
if (syncTransport) {
|
|
837
|
+
stopTransport = syncTransport.subscribe((message) => {
|
|
838
|
+
void applyRemoteMessage(message);
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
if (options.sync !== false && options.sync !== "tabs" && typeof options.sync !== "object" && driver.subscribe) {
|
|
842
|
+
stopSync = driver.subscribe(
|
|
843
|
+
options.key,
|
|
844
|
+
() => {
|
|
845
|
+
if (isDisposed || isApplyingSnapshot) {
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
try {
|
|
849
|
+
const raw = driver.get(options.key, storageOptions);
|
|
850
|
+
if (isPromiseLike(raw)) {
|
|
851
|
+
raw.then((value) => void applyRaw(value)).catch((syncError) => {
|
|
852
|
+
error.value = syncError;
|
|
853
|
+
});
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
void applyRaw(raw);
|
|
857
|
+
} catch (syncError) {
|
|
858
|
+
error.value = syncError;
|
|
859
|
+
}
|
|
860
|
+
},
|
|
861
|
+
storageOptions
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
stopDisposeEffect = effect(() => () => {
|
|
865
|
+
dispose();
|
|
866
|
+
});
|
|
867
|
+
void hydrate();
|
|
868
|
+
return {
|
|
869
|
+
...model,
|
|
870
|
+
hydration,
|
|
871
|
+
error,
|
|
872
|
+
hydrate,
|
|
873
|
+
flush,
|
|
874
|
+
reset,
|
|
875
|
+
dispose
|
|
876
|
+
};
|
|
877
|
+
});
|
|
878
|
+
return PersistedModelConstructor;
|
|
879
|
+
};
|
|
880
|
+
var globalRegistry = /* @__PURE__ */ new Map();
|
|
881
|
+
var cookieContextRegistry = /* @__PURE__ */ new WeakMap();
|
|
882
|
+
var UNDEFINED_TOKEN = "__KAMOD_SIGNALS_UNDEFINED__";
|
|
883
|
+
var isPromiseLike2 = (value) => typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
884
|
+
var parseStoredValue = (raw, initialValue, options, deserialize) => {
|
|
885
|
+
if (raw === null) {
|
|
886
|
+
return { value: initialValue, migrated: false, blocked: false };
|
|
887
|
+
}
|
|
888
|
+
if (raw === UNDEFINED_TOKEN) {
|
|
889
|
+
return { value: void 0, migrated: false, blocked: false };
|
|
890
|
+
}
|
|
891
|
+
try {
|
|
892
|
+
const result = deserializePersistedValue(raw, options, deserialize);
|
|
893
|
+
return { value: result.value, migrated: result.migrated, blocked: false };
|
|
894
|
+
} catch (error) {
|
|
895
|
+
if (options.migrationErrorStrategy === "throw") {
|
|
896
|
+
throw error;
|
|
897
|
+
}
|
|
898
|
+
return { value: initialValue, migrated: false, blocked: error instanceof FuturePersistedVersionError || options.migrationErrorStrategy !== "reset" };
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
var readInitialValue = (key, initialValue, options, driver = resolveDriver(resolveStorageType(options.storage), options)) => {
|
|
902
|
+
const scopedSnapshot = options.scope?.get(key);
|
|
903
|
+
if (scopedSnapshot !== void 0) {
|
|
904
|
+
return scopedSnapshot;
|
|
905
|
+
}
|
|
906
|
+
const hydratedSnapshot = consumeHydratedPersistedValue(key);
|
|
907
|
+
if (hydratedSnapshot !== void 0) {
|
|
908
|
+
return hydratedSnapshot;
|
|
909
|
+
}
|
|
910
|
+
const deserialize = options.deserialize ?? defaultDeserialize;
|
|
911
|
+
const raw = driver.get(key, options);
|
|
912
|
+
if (isPromiseLike2(raw)) {
|
|
913
|
+
return initialValue;
|
|
914
|
+
}
|
|
915
|
+
return parseStoredValue(raw, initialValue, options, deserialize).value;
|
|
916
|
+
};
|
|
917
|
+
var normalizeCookieOptions = (cookie) => ({
|
|
918
|
+
expires: cookie?.expires instanceof Date ? cookie.expires.toUTCString() : cookie?.expires,
|
|
919
|
+
path: cookie?.path ?? "/",
|
|
920
|
+
domain: cookie?.domain,
|
|
921
|
+
secure: cookie?.secure,
|
|
922
|
+
sameSite: cookie?.sameSite
|
|
923
|
+
});
|
|
924
|
+
var createCompatibilitySnapshot = (options) => {
|
|
925
|
+
const storage = resolveStorageType(options.storage);
|
|
926
|
+
return {
|
|
927
|
+
storage,
|
|
928
|
+
serialize: options.serialize ?? defaultSerialize,
|
|
929
|
+
deserialize: options.deserialize ?? defaultDeserialize,
|
|
930
|
+
sync: options.sync ?? true,
|
|
931
|
+
removeOnUndefined: options.removeOnUndefined ?? true,
|
|
932
|
+
cookie: storage === "cookie" ? normalizeCookieOptions(options.cookie) : void 0,
|
|
933
|
+
indexedDB: storage === "indexeddb" ? {
|
|
934
|
+
database: options.indexedDB?.database ?? "@kamod-ch/signals",
|
|
935
|
+
store: options.indexedDB?.store ?? "signals",
|
|
936
|
+
version: options.indexedDB?.version ?? 1
|
|
937
|
+
} : void 0,
|
|
938
|
+
version: options.version
|
|
939
|
+
};
|
|
940
|
+
};
|
|
941
|
+
var snapshotsMatch = (left, right) => left.storage === right.storage && left.serialize === right.serialize && left.deserialize === right.deserialize && left.sync === right.sync && left.removeOnUndefined === right.removeOnUndefined && left.version === right.version && JSON.stringify(left.cookie) === JSON.stringify(right.cookie) && JSON.stringify(left.indexedDB) === JSON.stringify(right.indexedDB);
|
|
942
|
+
var createOptionConflictError = (id) => new Error(`persistedSignal(${id}) received conflicting options for an existing global signal`);
|
|
943
|
+
var getCompatibleEntry = (entry, snapshot, id) => {
|
|
944
|
+
if (!entry) {
|
|
945
|
+
return void 0;
|
|
946
|
+
}
|
|
947
|
+
if (!snapshotsMatch(entry.snapshot, snapshot)) {
|
|
948
|
+
throw createOptionConflictError(id);
|
|
949
|
+
}
|
|
950
|
+
return entry.controller;
|
|
951
|
+
};
|
|
952
|
+
var createController = (key, initialValue, options = {}) => {
|
|
953
|
+
const storage = resolveStorageType(options.storage);
|
|
954
|
+
const driver = resolveDriver(storage, options);
|
|
955
|
+
const serialize = options.serialize ?? defaultSerialize;
|
|
956
|
+
const deserialize = options.deserialize ?? defaultDeserialize;
|
|
957
|
+
const removeOnUndefined = options.removeOnUndefined ?? true;
|
|
958
|
+
const state = signal(readInitialValue(key, initialValue, options, driver));
|
|
959
|
+
let isApplyingExternalValue = false;
|
|
960
|
+
let isHydrating = Boolean(driver.async);
|
|
961
|
+
let observedValue = state.value;
|
|
962
|
+
let hasPendingHydrationChange = false;
|
|
963
|
+
let persistenceBlocked = false;
|
|
964
|
+
const persistValue = (value) => {
|
|
965
|
+
try {
|
|
966
|
+
if (persistenceBlocked) {
|
|
967
|
+
return void 0;
|
|
968
|
+
}
|
|
969
|
+
if (value === void 0 && removeOnUndefined) {
|
|
970
|
+
return driver.remove(key, options);
|
|
971
|
+
}
|
|
972
|
+
options.scope?.set(key, value);
|
|
973
|
+
return driver.set(
|
|
974
|
+
key,
|
|
975
|
+
value === void 0 ? UNDEFINED_TOKEN : serializePersistedValue(value, options, serialize),
|
|
976
|
+
options
|
|
977
|
+
);
|
|
978
|
+
} catch {
|
|
979
|
+
return void 0;
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
if (!driver.async) {
|
|
983
|
+
try {
|
|
984
|
+
const raw = driver.get(key, options);
|
|
985
|
+
if (!isPromiseLike2(raw)) {
|
|
986
|
+
const parsed = parseStoredValue(raw, initialValue, options, deserialize);
|
|
987
|
+
persistenceBlocked = parsed.blocked;
|
|
988
|
+
if (parsed.migrated) {
|
|
989
|
+
persistValue(parsed.value);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
} catch {
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
state.clear = () => {
|
|
996
|
+
persistenceBlocked = false;
|
|
997
|
+
isApplyingExternalValue = true;
|
|
998
|
+
driver.remove(key, options);
|
|
999
|
+
options.scope?.set(key, initialValue);
|
|
1000
|
+
state.value = initialValue;
|
|
1001
|
+
observedValue = state.value;
|
|
1002
|
+
isApplyingExternalValue = false;
|
|
1003
|
+
};
|
|
1004
|
+
state.reset = () => {
|
|
1005
|
+
persistenceBlocked = false;
|
|
1006
|
+
state.value = initialValue;
|
|
1007
|
+
};
|
|
1008
|
+
const stopEffect = effect(() => {
|
|
1009
|
+
const value = state.value;
|
|
1010
|
+
if (isApplyingExternalValue) {
|
|
1011
|
+
observedValue = value;
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
if (isHydrating) {
|
|
1015
|
+
if (!Object.is(value, observedValue)) {
|
|
1016
|
+
hasPendingHydrationChange = true;
|
|
1017
|
+
}
|
|
1018
|
+
observedValue = value;
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
observedValue = value;
|
|
1022
|
+
persistValue(value);
|
|
1023
|
+
});
|
|
1024
|
+
if (driver.async) {
|
|
1025
|
+
Promise.resolve(driver.get(key, options)).then(async (raw) => {
|
|
1026
|
+
if (!hasPendingHydrationChange) {
|
|
1027
|
+
const parsed = await deserializePersistedValueAsync(raw ?? "null", options, deserialize).catch((error) => {
|
|
1028
|
+
if (raw === null) {
|
|
1029
|
+
return { value: initialValue, migrated: false };
|
|
1030
|
+
}
|
|
1031
|
+
if (options.migrationErrorStrategy === "throw") {
|
|
1032
|
+
throw error;
|
|
1033
|
+
}
|
|
1034
|
+
persistenceBlocked = error instanceof FuturePersistedVersionError || options.migrationErrorStrategy !== "reset";
|
|
1035
|
+
return { value: initialValue, migrated: false };
|
|
1036
|
+
});
|
|
1037
|
+
const nextValue = raw === null ? initialValue : parsed.value;
|
|
1038
|
+
if (!Object.is(nextValue, state.value)) {
|
|
1039
|
+
isApplyingExternalValue = true;
|
|
1040
|
+
state.value = nextValue;
|
|
1041
|
+
observedValue = nextValue;
|
|
1042
|
+
isApplyingExternalValue = false;
|
|
1043
|
+
}
|
|
1044
|
+
if (raw !== null && parsed.migrated) {
|
|
1045
|
+
await persistValue(nextValue);
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
isHydrating = false;
|
|
1049
|
+
if (hasPendingHydrationChange) {
|
|
1050
|
+
persistValue(state.value);
|
|
1051
|
+
}
|
|
1052
|
+
}).catch(() => {
|
|
1053
|
+
isHydrating = false;
|
|
1054
|
+
if (hasPendingHydrationChange) {
|
|
1055
|
+
persistValue(state.value);
|
|
1056
|
+
}
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
const applyExternalRaw = (raw) => {
|
|
1060
|
+
const parsed = parseStoredValue(raw, initialValue, options, deserialize);
|
|
1061
|
+
persistenceBlocked = parsed.blocked;
|
|
1062
|
+
const nextValue = parsed.value;
|
|
1063
|
+
if (Object.is(nextValue, state.value)) {
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
isApplyingExternalValue = true;
|
|
1067
|
+
state.value = nextValue;
|
|
1068
|
+
observedValue = nextValue;
|
|
1069
|
+
isApplyingExternalValue = false;
|
|
1070
|
+
};
|
|
1071
|
+
const stopSync = options.sync === false || !driver.subscribe ? () => {
|
|
1072
|
+
} : driver.subscribe(key, () => {
|
|
1073
|
+
try {
|
|
1074
|
+
const raw = driver.get(key, options);
|
|
1075
|
+
if (isPromiseLike2(raw)) {
|
|
1076
|
+
raw.then((value) => {
|
|
1077
|
+
applyExternalRaw(value);
|
|
1078
|
+
}).catch(() => {
|
|
1079
|
+
});
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
applyExternalRaw(raw);
|
|
1083
|
+
} catch {
|
|
1084
|
+
}
|
|
1085
|
+
}, options);
|
|
1086
|
+
return {
|
|
1087
|
+
signal: state,
|
|
1088
|
+
dispose() {
|
|
1089
|
+
stopSync();
|
|
1090
|
+
stopEffect();
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
};
|
|
1094
|
+
var persistedSignal = (key, initialValue, options = {}) => {
|
|
1095
|
+
const storage = resolveStorageType(options.storage);
|
|
1096
|
+
const id = registryKey(storage, key);
|
|
1097
|
+
const snapshot = createCompatibilitySnapshot(options);
|
|
1098
|
+
const context = storage === "cookie" ? options.cookieContext : void 0;
|
|
1099
|
+
if (context) {
|
|
1100
|
+
let scopedRegistry = cookieContextRegistry.get(context);
|
|
1101
|
+
if (!scopedRegistry) {
|
|
1102
|
+
scopedRegistry = /* @__PURE__ */ new Map();
|
|
1103
|
+
cookieContextRegistry.set(context, scopedRegistry);
|
|
1104
|
+
}
|
|
1105
|
+
const existing2 = getCompatibleEntry(scopedRegistry.get(id), snapshot, id);
|
|
1106
|
+
if (existing2) {
|
|
1107
|
+
return existing2.signal;
|
|
1108
|
+
}
|
|
1109
|
+
const controller2 = createController(key, initialValue, options);
|
|
1110
|
+
scopedRegistry.set(id, { controller: controller2, snapshot });
|
|
1111
|
+
return controller2.signal;
|
|
1112
|
+
}
|
|
1113
|
+
const existing = getCompatibleEntry(globalRegistry.get(id), snapshot, id);
|
|
1114
|
+
if (existing) {
|
|
1115
|
+
return existing.signal;
|
|
1116
|
+
}
|
|
1117
|
+
const controller = createController(key, initialValue, options);
|
|
1118
|
+
globalRegistry.set(id, { controller, snapshot });
|
|
1119
|
+
return controller.signal;
|
|
1120
|
+
};
|
|
1121
|
+
var createPersistedSignal = createController;
|
|
1122
|
+
var cookieDependencyKey = (options) => {
|
|
1123
|
+
const cookie = options.cookie;
|
|
1124
|
+
if (!cookie) {
|
|
1125
|
+
return "";
|
|
1126
|
+
}
|
|
1127
|
+
return JSON.stringify([
|
|
1128
|
+
cookie.expires instanceof Date ? cookie.expires.toUTCString() : cookie.expires,
|
|
1129
|
+
cookie.path,
|
|
1130
|
+
cookie.domain,
|
|
1131
|
+
cookie.secure,
|
|
1132
|
+
cookie.sameSite
|
|
1133
|
+
]);
|
|
1134
|
+
};
|
|
1135
|
+
var indexedDbDependencyKey = (options) => JSON.stringify([
|
|
1136
|
+
options.indexedDB?.database ?? "@kamod-ch/signals",
|
|
1137
|
+
options.indexedDB?.store ?? "signals",
|
|
1138
|
+
options.indexedDB?.version ?? 1
|
|
1139
|
+
]);
|
|
1140
|
+
var usePersistedSignal = (key, initialValue, options = {}) => {
|
|
1141
|
+
const controller = useMemo(
|
|
1142
|
+
() => createPersistedSignal(key, initialValue, options),
|
|
1143
|
+
[
|
|
1144
|
+
key,
|
|
1145
|
+
initialValue,
|
|
1146
|
+
resolveStorageType(options.storage),
|
|
1147
|
+
options.sync,
|
|
1148
|
+
options.serialize,
|
|
1149
|
+
options.deserialize,
|
|
1150
|
+
options.removeOnUndefined,
|
|
1151
|
+
options.cookieContext,
|
|
1152
|
+
cookieDependencyKey(options),
|
|
1153
|
+
indexedDbDependencyKey(options)
|
|
1154
|
+
]
|
|
1155
|
+
);
|
|
1156
|
+
useEffect(() => () => controller.dispose(), [controller]);
|
|
1157
|
+
return controller.signal;
|
|
1158
|
+
};
|
|
1159
|
+
|
|
1160
|
+
export { FuturePersistedVersionError, PersistedValidationError, comparePersistedSyncMessages, createBroadcastSyncTransport, createCookieContext, createMemorySyncTransport, createPersistedEventTarget, createPersistedModel, createPersistedScope, dehydratePersisted, emitPersistedEvent, hydratePersisted, isPersistedEnvelope, persistedSignal, serializeCookie, serializePersistedStateForHtml, usePersistedSignal };
|