]>
Commit | Line | Data |
---|---|---|
1 | // Thanks: https://github.com/capaj/localstorage-polyfill | |
2 | ||
3 | const valuesMap = new Map() | |
4 | ||
5 | function proxify (instance: MemoryStorage) { | |
6 | return new Proxy(instance, { | |
7 | set: function (obj, prop: string | symbol, value) { | |
8 | if (Object.prototype.hasOwnProperty.call(MemoryStorage, prop)) { | |
9 | // FIXME: symbol typing issue https://github.com/microsoft/TypeScript/issues/1863 | |
10 | instance[prop as any] = value | |
11 | } else { | |
12 | instance.setItem(prop, value) | |
13 | } | |
14 | return true | |
15 | }, | |
16 | get: function (target, name: string | symbol | number) { | |
17 | if (Object.prototype.hasOwnProperty.call(MemoryStorage, name)) { | |
18 | // FIXME: symbol typing issue https://github.com/microsoft/TypeScript/issues/1863 | |
19 | return instance[name as any] | |
20 | } | |
21 | if (valuesMap.has(name)) { | |
22 | return instance.getItem(name) | |
23 | } | |
24 | } | |
25 | }) | |
26 | } | |
27 | ||
28 | class MemoryStorage implements Storage { | |
29 | [key: string]: any | |
30 | ||
31 | getItem (key: any) { | |
32 | const stringKey = String(key) | |
33 | if (valuesMap.has(key)) { | |
34 | return String(valuesMap.get(stringKey)) | |
35 | } | |
36 | ||
37 | return null | |
38 | } | |
39 | ||
40 | setItem (key: any, val: any) { | |
41 | valuesMap.set(String(key), String(val)) | |
42 | } | |
43 | ||
44 | removeItem (key: any) { | |
45 | valuesMap.delete(key) | |
46 | } | |
47 | ||
48 | clear () { | |
49 | valuesMap.clear() | |
50 | } | |
51 | ||
52 | key (i: any) { | |
53 | if (arguments.length === 0) { | |
54 | throw new TypeError('Failed to execute "key" on "Storage": 1 argument required, but only 0 present.') | |
55 | } | |
56 | ||
57 | const arr = Array.from(valuesMap.keys()) | |
58 | return arr[i] | |
59 | } | |
60 | ||
61 | get length () { | |
62 | return valuesMap.size | |
63 | } | |
64 | } | |
65 | ||
66 | let peertubeLocalStorage: Storage | |
67 | let peertubeSessionStorage: Storage | |
68 | ||
69 | function reinitStorage () { | |
70 | const instanceLocalStorage = new MemoryStorage() | |
71 | const instanceSessionStorage = new MemoryStorage() | |
72 | ||
73 | peertubeLocalStorage = proxify(instanceLocalStorage) | |
74 | peertubeSessionStorage = proxify(instanceSessionStorage) | |
75 | } | |
76 | ||
77 | try { | |
78 | peertubeLocalStorage = localStorage | |
79 | peertubeSessionStorage = sessionStorage | |
80 | } catch (err) { | |
81 | // support Firefox and other browsers using an exception rather than null | |
82 | reinitStorage() | |
83 | } | |
84 | ||
85 | // support Brave and other browsers using null rather than an exception | |
86 | if (peertubeLocalStorage === null || peertubeSessionStorage === null) { | |
87 | reinitStorage() | |
88 | } | |
89 | ||
90 | export { | |
91 | peertubeLocalStorage, | |
92 | peertubeSessionStorage | |
93 | } |