@plq/use-persisted-state 1.3.0 → 1.4.1
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/LICENSE +1 -1
- package/README.md +179 -50
- package/esm/index.d.mts +13 -0
- package/esm/index.mjs +10 -0
- package/esm/storages/browser-storage.d.mts +1 -0
- package/esm/storages/browser-storage.mjs +5 -0
- package/esm/storages/chrome-storage.d.mts +1 -0
- package/esm/storages/chrome-storage.mjs +5 -0
- package/esm/storages/local-storage.d.mts +1 -0
- package/esm/storages/local-storage.mjs +3 -0
- package/esm/storages/session-storage.d.mts +1 -0
- package/esm/storages/session-storage.mjs +3 -0
- package/lib/@types/storage.d.ts.map +1 -1
- package/lib/create-async-persisted-state.d.ts +2 -2
- package/lib/create-async-persisted-state.d.ts.map +1 -1
- package/lib/create-async-persisted-state.js +136 -17
- package/lib/create-async-persisted-state.js.map +1 -1
- package/lib/create-persisted-state.d.ts +2 -2
- package/lib/create-persisted-state.d.ts.map +1 -1
- package/lib/create-persisted-state.js +76 -15
- package/lib/create-persisted-state.js.map +1 -1
- package/lib/index.d.ts +6 -5
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +4 -2
- package/lib/index.js.map +1 -1
- package/lib/storages/browser-storage.d.ts +2 -2
- package/lib/storages/browser-storage.d.ts.map +1 -1
- package/lib/storages/browser-storage.js +6 -26
- package/lib/storages/browser-storage.js.map +1 -1
- package/lib/storages/chrome-storage.d.ts +2 -2
- package/lib/storages/chrome-storage.d.ts.map +1 -1
- package/lib/storages/chrome-storage.js +10 -27
- package/lib/storages/chrome-storage.js.map +1 -1
- package/lib/storages/local-storage.d.ts +1 -1
- package/lib/storages/local-storage.d.ts.map +1 -1
- package/lib/storages/local-storage.js +3 -1
- package/lib/storages/local-storage.js.map +1 -1
- package/lib/storages/session-storage.d.ts +1 -1
- package/lib/storages/session-storage.d.ts.map +1 -1
- package/lib/storages/session-storage.js +3 -1
- package/lib/storages/session-storage.js.map +1 -1
- package/lib/utils/change-notifier.d.ts +18 -0
- package/lib/utils/change-notifier.d.ts.map +1 -0
- package/lib/utils/change-notifier.js +38 -0
- package/lib/utils/change-notifier.js.map +1 -0
- package/lib/utils/create-web-storage.d.ts +10 -2
- package/lib/utils/create-web-storage.d.ts.map +1 -1
- package/lib/utils/create-web-storage.js +72 -75
- package/lib/utils/create-web-storage.js.map +1 -1
- package/lib/utils/extension-storage.d.ts +38 -0
- package/lib/utils/extension-storage.d.ts.map +1 -0
- package/lib/utils/extension-storage.js +66 -0
- package/lib/utils/extension-storage.js.map +1 -0
- package/lib/utils/get-new-item.d.ts +13 -1
- package/lib/utils/get-new-item.d.ts.map +1 -1
- package/lib/utils/get-new-item.js +27 -7
- package/lib/utils/get-new-item.js.map +1 -1
- package/lib/utils/get-new-value.d.ts +1 -1
- package/lib/utils/get-new-value.d.ts.map +1 -1
- package/lib/utils/get-persisted-value.d.ts +8 -1
- package/lib/utils/get-persisted-value.d.ts.map +1 -1
- package/lib/utils/get-persisted-value.js +19 -5
- package/lib/utils/get-persisted-value.js.map +1 -1
- package/lib/utils/is-async-storage.d.ts +7 -0
- package/lib/utils/is-async-storage.d.ts.map +1 -1
- package/lib/utils/is-async-storage.js +51 -20
- package/lib/utils/is-async-storage.js.map +1 -1
- package/lib/utils/storage-event-router.d.ts +17 -0
- package/lib/utils/storage-event-router.d.ts.map +1 -0
- package/lib/utils/storage-event-router.js +54 -0
- package/lib/utils/storage-event-router.js.map +1 -0
- package/lib/utils/use-storage-handler.d.ts +14 -3
- package/lib/utils/use-storage-handler.d.ts.map +1 -1
- package/lib/utils/use-storage-handler.js +109 -26
- package/lib/utils/use-storage-handler.js.map +1 -1
- package/package.json +97 -41
- package/src/@types/storage.ts +13 -13
- package/src/create-async-persisted-state.ts +125 -20
- package/src/create-persisted-state.ts +59 -23
- package/src/index.ts +12 -7
- package/src/storages/browser-storage.ts +8 -36
- package/src/storages/chrome-storage.ts +24 -46
- package/src/storages/local-storage.ts +3 -1
- package/src/storages/session-storage.ts +3 -1
- package/src/utils/change-notifier.ts +43 -0
- package/src/utils/create-web-storage.ts +74 -77
- package/src/utils/extension-storage.ts +79 -0
- package/src/utils/get-new-item.ts +32 -9
- package/src/utils/get-new-value.ts +1 -1
- package/src/utils/get-persisted-value.ts +22 -7
- package/src/utils/is-async-storage.ts +72 -27
- package/src/utils/storage-event-router.ts +67 -0
- package/src/utils/use-storage-handler.ts +144 -36
- package/storages/browser-storage.d.ts +1 -0
- package/storages/browser-storage.js +11 -0
- package/storages/chrome-storage.d.ts +1 -0
- package/storages/chrome-storage.js +11 -0
- package/storages/local-storage.d.ts +1 -0
- package/storages/local-storage.js +9 -0
- package/storages/session-storage.d.ts +1 -0
- package/storages/session-storage.js +9 -0
|
@@ -1,63 +1,76 @@
|
|
|
1
|
-
import { Storage, StorageChange, StorageChangeEvent
|
|
1
|
+
import type { Storage, StorageChange, StorageChangeEvent } from '../@types/storage'
|
|
2
|
+
import { createChangeNotifier } from './change-notifier'
|
|
3
|
+
import { addRoute, removeRoute, type StorageEventRoute } from './storage-event-router'
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
function fireStorageEvent(changes: { [key: string]: StorageChange }) {
|
|
6
|
-
listeners.forEach(listener => {
|
|
7
|
-
listener(changes)
|
|
8
|
-
})
|
|
5
|
+
function toKeyList(keys: string | string[]): string[] {
|
|
6
|
+
return Array.isArray(keys) ? keys : [keys]
|
|
9
7
|
}
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Adapts a Web Storage area to the library's `Storage` contract.
|
|
11
|
+
*
|
|
12
|
+
* Pass `undefined` where the global is missing, as it is on a server: the
|
|
13
|
+
* adapter then reads back nothing and **silently discards every write**, so a
|
|
14
|
+
* consumer keeps its initial value instead of the import throwing. Listeners
|
|
15
|
+
* are still accepted and reported, they simply never fire.
|
|
16
|
+
*/
|
|
17
|
+
export default (storage: globalThis.Storage | undefined): Storage => {
|
|
18
|
+
// Per-instance notifier: the localStorage and sessionStorage adapters must not
|
|
19
|
+
// share listeners, or a write to one area notifies subscribers of the other.
|
|
20
|
+
const notifier = createChangeNotifier()
|
|
21
|
+
|
|
22
|
+
// Only a missing global is inert. Anything else a caller passes has to fail
|
|
23
|
+
// on first use instead of swallowing their writes.
|
|
24
|
+
if (storage === undefined) {
|
|
25
|
+
return {
|
|
26
|
+
get: () => ({}),
|
|
27
|
+
set: () => {},
|
|
28
|
+
remove: () => {},
|
|
29
|
+
onChanged: notifier.onChanged,
|
|
18
30
|
}
|
|
19
|
-
|
|
20
|
-
fireStorageEvent(changes)
|
|
21
31
|
}
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
const onChanged: StorageChangeEvent = {
|
|
25
|
-
addListener(listener) {
|
|
26
|
-
listeners.add(listener)
|
|
27
|
-
},
|
|
28
|
-
removeListener(listener) {
|
|
29
|
-
listeners.delete(listener)
|
|
30
|
-
},
|
|
31
|
-
hasListener(listener) {
|
|
32
|
-
return listeners.has(listener)
|
|
33
|
-
},
|
|
34
|
-
}
|
|
35
32
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
33
|
+
const route: StorageEventRoute = { storage, fire: notifier.fire }
|
|
34
|
+
|
|
35
|
+
// The DOM subscription is shared and reference counted: an adapter joins it
|
|
36
|
+
// with its first listener and lets go with its last, so factory calls nobody
|
|
37
|
+
// listens to leave nothing attached to the global object.
|
|
38
|
+
const onChanged: StorageChangeEvent = {
|
|
39
|
+
addListener(listener) {
|
|
40
|
+
notifier.onChanged.addListener(listener)
|
|
41
|
+
|
|
42
|
+
addRoute(route)
|
|
43
|
+
},
|
|
44
|
+
removeListener(listener) {
|
|
45
|
+
notifier.onChanged.removeListener(listener)
|
|
46
|
+
|
|
47
|
+
if (!notifier.hasListeners()) removeRoute(route)
|
|
48
|
+
},
|
|
49
|
+
hasListener(listener) {
|
|
50
|
+
return notifier.onChanged.hasListener(listener)
|
|
51
|
+
},
|
|
52
|
+
}
|
|
39
53
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
54
|
+
return {
|
|
55
|
+
get: keys => {
|
|
56
|
+
const result: { [key: string]: string } = {}
|
|
43
57
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
} else {
|
|
47
|
-
const item = typeof storage !== 'undefined' ? storage.getItem(keys) : undefined
|
|
58
|
+
for (const key of toKeyList(keys)) {
|
|
59
|
+
const item = storage.getItem(key)
|
|
48
60
|
|
|
49
|
-
|
|
50
|
-
|
|
61
|
+
// `null` is the only answer that means absence: an empty string is a
|
|
62
|
+
// value the caller stored, and reporting it as a missing key loses it.
|
|
63
|
+
if (item !== null) result[key] = item
|
|
64
|
+
}
|
|
51
65
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
66
|
+
return result
|
|
67
|
+
},
|
|
68
|
+
set: items => {
|
|
69
|
+
const changes: { [key: string]: StorageChange } = {}
|
|
56
70
|
|
|
57
|
-
|
|
58
|
-
|
|
71
|
+
for (const [key, value] of Object.entries(items)) {
|
|
72
|
+
const oldValue = storage.getItem(key)
|
|
59
73
|
|
|
60
|
-
if (typeof storage !== 'undefined') {
|
|
61
74
|
storage.setItem(key, value)
|
|
62
75
|
|
|
63
76
|
changes[key] = {
|
|
@@ -65,41 +78,25 @@ export default (storage: globalThis.Storage): Storage => ({
|
|
|
65
78
|
newValue: value,
|
|
66
79
|
}
|
|
67
80
|
}
|
|
68
|
-
})
|
|
69
|
-
|
|
70
|
-
if (Object.keys(changes).length > 0) fireStorageEvent(changes)
|
|
71
|
-
},
|
|
72
|
-
remove: keys => {
|
|
73
|
-
const changes: { [key: string]: StorageChange } = {}
|
|
74
81
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
82
|
+
if (Object.keys(changes).length > 0) notifier.fire(changes)
|
|
83
|
+
},
|
|
84
|
+
remove: keys => {
|
|
85
|
+
const changes: { [key: string]: StorageChange } = {}
|
|
78
86
|
|
|
79
|
-
|
|
80
|
-
|
|
87
|
+
for (const key of toKeyList(keys)) {
|
|
88
|
+
const oldValue = storage.getItem(key)
|
|
81
89
|
|
|
82
|
-
|
|
83
|
-
oldValue,
|
|
84
|
-
newValue: null,
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
})
|
|
88
|
-
} else {
|
|
89
|
-
const oldValue = typeof storage !== 'undefined' ? storage.getItem(keys) : undefined
|
|
90
|
-
|
|
91
|
-
if (typeof storage !== 'undefined') {
|
|
92
|
-
storage.removeItem(keys)
|
|
90
|
+
storage.removeItem(key)
|
|
93
91
|
|
|
94
|
-
changes[
|
|
92
|
+
changes[key] = {
|
|
95
93
|
oldValue,
|
|
96
94
|
newValue: null,
|
|
97
95
|
}
|
|
98
96
|
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
if (Object.keys(changes).length > 0) fireStorageEvent(changes)
|
|
102
|
-
},
|
|
103
|
-
onChanged,
|
|
104
|
-
})
|
|
105
97
|
|
|
98
|
+
if (Object.keys(changes).length > 0) notifier.fire(changes)
|
|
99
|
+
},
|
|
100
|
+
onChanged,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { StorageChange, StorageChangeEvent } from '../@types/storage'
|
|
2
|
+
import { type ChangeNotifier, createChangeNotifier } from './change-notifier'
|
|
3
|
+
|
|
4
|
+
const TRACKED_AREAS = ['local', 'sync', 'managed'] as const
|
|
5
|
+
|
|
6
|
+
export type Area = (typeof TRACKED_AREAS)[number]
|
|
7
|
+
|
|
8
|
+
// Both browsers also report `session` changes, an area this library does not
|
|
9
|
+
// expose. Dispatching one would read an undefined notifier and throw.
|
|
10
|
+
function isTrackedArea(area: string): area is Area {
|
|
11
|
+
return (TRACKED_AREAS as readonly string[]).includes(area)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Extension storage holds arbitrary JSON, while this library only ever writes
|
|
16
|
+
* serialized strings. Anything else under a key belongs to other code and is
|
|
17
|
+
* reported as absent — which is what effectively happened before, once such a
|
|
18
|
+
* value reached `JSON.parse` and the hook fell back to its initial value.
|
|
19
|
+
*/
|
|
20
|
+
export function toStoredValue(value: unknown): string | null | undefined {
|
|
21
|
+
if (value === undefined) return
|
|
22
|
+
|
|
23
|
+
return typeof value === 'string' ? value : null
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function toStorageChanges(changes: { [key: string]: { oldValue?: unknown; newValue?: unknown } }): {
|
|
27
|
+
[key: string]: StorageChange
|
|
28
|
+
} {
|
|
29
|
+
const result: { [key: string]: StorageChange } = {}
|
|
30
|
+
|
|
31
|
+
for (const [key, change] of Object.entries(changes)) {
|
|
32
|
+
result[key] = {
|
|
33
|
+
oldValue: toStoredValue(change.oldValue),
|
|
34
|
+
newValue: toStoredValue(change.newValue),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return result
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function toStoredItems(items: { [key: string]: unknown }): { [key: string]: string } {
|
|
42
|
+
const result: { [key: string]: string } = {}
|
|
43
|
+
|
|
44
|
+
for (const [key, value] of Object.entries(items)) {
|
|
45
|
+
if (typeof value === 'string') result[key] = value
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return result
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ListenerRegistry {
|
|
52
|
+
fire(changes: { [key: string]: StorageChange }, area: string): void
|
|
53
|
+
createOnChanged(area: Area): StorageChangeEvent
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Demultiplexes an extension's single `onChanged` event, which names the area
|
|
58
|
+
* that changed, to one notifier per area. Each adapter owns its own registry,
|
|
59
|
+
* so a change in one browser's storage never reaches listeners registered on
|
|
60
|
+
* another's.
|
|
61
|
+
*/
|
|
62
|
+
export function createListenerRegistry(): ListenerRegistry {
|
|
63
|
+
const notifiers: { [area in Area]: ChangeNotifier } = {
|
|
64
|
+
local: createChangeNotifier(),
|
|
65
|
+
sync: createChangeNotifier(),
|
|
66
|
+
managed: createChangeNotifier(),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
fire(changes, area) {
|
|
71
|
+
if (!isTrackedArea(area)) return
|
|
72
|
+
|
|
73
|
+
notifiers[area].fire(changes)
|
|
74
|
+
},
|
|
75
|
+
createOnChanged(area) {
|
|
76
|
+
return notifiers[area].onChanged
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -1,16 +1,39 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { isObject } from '@plq/is'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Merges `newValue` under `key` into the serialized entry a factory shares between all of its
|
|
5
|
+
* hooks, and returns the entry to store.
|
|
6
|
+
*
|
|
7
|
+
* Reports and throws when the entry cannot be merged into, rather than answering with one built
|
|
8
|
+
* from nothing. What this returns is written over the whole entry, so an unreadable entry is the
|
|
9
|
+
* one case with nothing safe to return: every other hook's key would be replaced with nothing,
|
|
10
|
+
* and the bytes a repair still needs would go with them.
|
|
11
|
+
*
|
|
12
|
+
* @throws {SyntaxError} when the entry is not valid JSON.
|
|
13
|
+
* @throws {TypeError} when the entry is valid JSON but not an object of keys.
|
|
14
|
+
*/
|
|
15
|
+
export default function getNewItem<T>(key: string, persistedItem: string, newValue: T): string {
|
|
16
|
+
let persist: unknown
|
|
3
17
|
|
|
4
18
|
try {
|
|
5
19
|
persist = persistedItem ? JSON.parse(persistedItem) : {}
|
|
6
20
|
} catch (err) {
|
|
7
|
-
console.error(err)
|
|
8
|
-
|
|
21
|
+
console.error("use-persisted-state: Can't write value to storage", err)
|
|
22
|
+
|
|
23
|
+
throw err
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (!isObject(persist)) {
|
|
27
|
+
// A shared backend can leave any JSON under the key, and neither a primitive nor an array
|
|
28
|
+
// survives being merged into: `JSON.stringify` unwraps the first back to itself and keeps the
|
|
29
|
+
// second an array, so the value being set disappears with the property added to it. A stored
|
|
30
|
+
// `null` did not even get that far - it threw out of `Object.assign` and into the caller.
|
|
31
|
+
const err = new TypeError('the stored entry is not an object of keys')
|
|
32
|
+
|
|
33
|
+
console.error("use-persisted-state: Can't write value to storage", err)
|
|
34
|
+
|
|
35
|
+
throw err
|
|
9
36
|
}
|
|
10
37
|
|
|
11
|
-
return JSON.stringify(
|
|
12
|
-
Object.assign(persist, {
|
|
13
|
-
[key]: newValue,
|
|
14
|
-
}),
|
|
15
|
-
)
|
|
38
|
+
return JSON.stringify({ ...persist, [key]: newValue })
|
|
16
39
|
}
|
|
@@ -1,18 +1,33 @@
|
|
|
1
|
-
import { isFunction } from '@plq/is'
|
|
1
|
+
import { isFunction, isObject } from '@plq/is'
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Resolves the value a hook starts from: the persisted entry for `key` when the stored payload
|
|
5
|
+
* carries one, the initial value otherwise.
|
|
6
|
+
*
|
|
7
|
+
* Presence is decided by the key rather than by the value, so a persisted `null` comes back as
|
|
8
|
+
* the value the user set instead of being mistaken for an absence and replaced.
|
|
9
|
+
*/
|
|
10
|
+
export default function getPersistedValue<T>(key: string, initialValue: T | (() => T), persist?: string): T {
|
|
11
|
+
let initialPersist: unknown
|
|
5
12
|
|
|
6
13
|
try {
|
|
7
14
|
initialPersist = persist ? JSON.parse(persist) : {}
|
|
8
|
-
} catch {
|
|
15
|
+
} catch (err) {
|
|
16
|
+
// A shared backend can hold a foreign or truncated entry, so a parse failure is expected here
|
|
17
|
+
// and must not stop the component mounting. It is reported rather than swallowed because the
|
|
18
|
+
// fallback discards whatever was persisted, and because the change path logs the same failure.
|
|
19
|
+
console.error("use-persisted-state: Can't parse value from storage", err)
|
|
20
|
+
|
|
9
21
|
initialPersist = {}
|
|
10
22
|
}
|
|
11
23
|
|
|
12
|
-
let initialOrPersistedValue = isFunction(initialValue) ? initialValue()
|
|
24
|
+
let initialOrPersistedValue = isFunction(initialValue) ? initialValue() : initialValue
|
|
13
25
|
|
|
14
|
-
|
|
15
|
-
|
|
26
|
+
// `JSON.parse` yields any JSON value, so a foreign entry can be a primitive,
|
|
27
|
+
// and `in` throws on one. This runs in the `useState` initializer, where a
|
|
28
|
+
// throw stops the component mounting instead of falling back.
|
|
29
|
+
if (isObject(initialPersist) && key in initialPersist) {
|
|
30
|
+
initialOrPersistedValue = initialPersist[key] as T
|
|
16
31
|
}
|
|
17
32
|
|
|
18
33
|
return initialOrPersistedValue
|
|
@@ -1,30 +1,75 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type {AsyncStorage} from '../@types/storage'
|
|
1
|
+
import { isAsyncFunction, isFunction, isPromise } from '@plq/is'
|
|
2
|
+
import type { AsyncStorage } from '../@types/storage'
|
|
3
3
|
|
|
4
|
+
// An unvalidated candidate: its members are unknown until each one is checked.
|
|
5
|
+
type StorageCandidate = {
|
|
6
|
+
get?: unknown
|
|
7
|
+
set?: unknown
|
|
8
|
+
remove?: unknown
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// `AsyncStorage` is three methods, so every member has to be callable: a promise standing in for
|
|
12
|
+
// one satisfies nothing the hook then does with it. `@plq/is` classifies async functions as their
|
|
13
|
+
// own type, so `isFunction` rejects them and both checks are needed to admit a callable member.
|
|
14
|
+
const isCallableMember = (member: unknown): boolean => isFunction(member) || isAsyncFunction(member)
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Narrows a storage to {@link AsyncStorage}, deciding which hook the entry point builds.
|
|
18
|
+
*
|
|
19
|
+
* Inspection never writes: `set` and `remove` are only checked for shape, never invoked, so
|
|
20
|
+
* `get` alone decides. A candidate pairing an async `get` with a sync `set` satisfies neither
|
|
21
|
+
* storage interface, which is why proving the other two members is not worth a write.
|
|
22
|
+
*/
|
|
4
23
|
export default function isAsyncStorage(storage: unknown): storage is AsyncStorage {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
return
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
24
|
+
const candidate = storage as StorageCandidate | null | undefined
|
|
25
|
+
|
|
26
|
+
if (!candidate) {
|
|
27
|
+
return false
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const { get, set, remove } = candidate
|
|
31
|
+
|
|
32
|
+
if (!isCallableMember(set) || !isCallableMember(remove)) {
|
|
33
|
+
return false
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// An `async` declaration is the one form of asyncness visible without a call.
|
|
37
|
+
if (isAsyncFunction(get)) {
|
|
38
|
+
return true
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!isFunction(get)) {
|
|
42
|
+
return false
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// `AsyncStorage` admits a plain function returning a promise, and nothing short of a call tells
|
|
46
|
+
// that apart from a sync get. Any adapter written that way can only be recognised here, and a
|
|
47
|
+
// third-party one is free to be written that way, so this line stays necessary however the
|
|
48
|
+
// shipped adapters happen to declare themselves. A read is the one probe that leaves the
|
|
49
|
+
// inspected storage as it found it.
|
|
50
|
+
let probe: unknown
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
// Called as a method of the storage it belongs to: an adapter written as an
|
|
54
|
+
// object of methods reads its own state through `this`, and probing the
|
|
55
|
+
// extracted function would throw on a storage that is perfectly valid.
|
|
56
|
+
probe = get.call(candidate, '')
|
|
57
|
+
} catch {
|
|
58
|
+
// Not swallowed, deferred: consumers build the factory at module scope, where
|
|
59
|
+
// a throw takes the import down instead of reaching a component. A storage
|
|
60
|
+
// whose read fails is not provably async, and the sync path raises the same
|
|
61
|
+
// failure at the first read, where it can be handled.
|
|
62
|
+
return false
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (!isPromise(probe)) {
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Only the probe's shape answers the question, so its outcome is discarded by construction.
|
|
70
|
+
// The rejection still has to be claimed: unclaimed, it terminates the process on Node 15+,
|
|
71
|
+
// letting a storage that merely fails a read take the consuming application down with it.
|
|
72
|
+
probe.then(undefined, () => undefined)
|
|
73
|
+
|
|
74
|
+
return true
|
|
30
75
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { StorageChange } from '../@types/storage'
|
|
2
|
+
|
|
3
|
+
/** An adapter waiting for DOM storage events about the area it wraps. */
|
|
4
|
+
export interface StorageEventRoute {
|
|
5
|
+
storage: globalThis.Storage
|
|
6
|
+
fire(changes: { [key: string]: StorageChange }): void
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const routes = new Set<StorageEventRoute>()
|
|
10
|
+
|
|
11
|
+
let subscription: ((event: StorageEvent) => void) | null = null
|
|
12
|
+
|
|
13
|
+
function routeStorageEvent(event: StorageEvent): void {
|
|
14
|
+
if (!event.key) return
|
|
15
|
+
|
|
16
|
+
const changes = {
|
|
17
|
+
[event.key]: {
|
|
18
|
+
newValue: event.newValue,
|
|
19
|
+
oldValue: event.oldValue,
|
|
20
|
+
},
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
for (const route of routes) {
|
|
24
|
+
// A browser always names the area it changed, so real cross-tab events
|
|
25
|
+
// reach only the adapter of that area. An event a consumer synthesized —
|
|
26
|
+
// the sole way to test cross-tab sync under jsdom, and a common way to
|
|
27
|
+
// notify the writing tab in production — often cannot name one: the
|
|
28
|
+
// StorageEvent constructor rejects a mocked storage there. Those still go
|
|
29
|
+
// everywhere, exactly as they did before areas were told apart.
|
|
30
|
+
if (event.storageArea == null || event.storageArea === route.storage) {
|
|
31
|
+
route.fire(changes)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// A runtime can provide storage without the DOM event API, and can provide half
|
|
37
|
+
// of that API: subscribing where nothing can unsubscribe strands a listener and
|
|
38
|
+
// makes releasing it throw, so both halves are required before taking one.
|
|
39
|
+
function canSubscribe(): boolean {
|
|
40
|
+
return typeof globalThis.addEventListener === 'function' && typeof globalThis.removeEventListener === 'function'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Starts routing DOM storage events to `route`. Every adapter shares one
|
|
45
|
+
* subscription on the global object, so creating adapters nobody listens to
|
|
46
|
+
* costs nothing.
|
|
47
|
+
*/
|
|
48
|
+
export function addRoute(route: StorageEventRoute): void {
|
|
49
|
+
routes.add(route)
|
|
50
|
+
|
|
51
|
+
if (!subscription && canSubscribe()) {
|
|
52
|
+
subscription = routeStorageEvent
|
|
53
|
+
|
|
54
|
+
globalThis.addEventListener('storage', subscription)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Stops routing to `route`, releasing the shared subscription with the last one. */
|
|
59
|
+
export function removeRoute(route: StorageEventRoute): void {
|
|
60
|
+
routes.delete(route)
|
|
61
|
+
|
|
62
|
+
if (routes.size === 0 && subscription) {
|
|
63
|
+
globalThis.removeEventListener('storage', subscription)
|
|
64
|
+
|
|
65
|
+
subscription = null
|
|
66
|
+
}
|
|
67
|
+
}
|