-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
396 lines (354 loc) · 12.2 KB
/
storage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// ==UserScript==
// @name OxiStorage
// @description Provides an API around `GM_getValue`, `GM_setValue`, and `GM_deleteValue` to manage userscript storage.
// @version 1.0.2
// @namespace owowed.moe
// @author owowed <[email protected]>
// @match *://*/*
// @require https://github.com/owowed/userscript-common/raw/main/common.js
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @license LGPL-3.0
// ==/UserScript==
class OxiStorageError extends OxiError {
constructor (message, { data, cause, ...rest }) {
super(message, { cause, ...rest });
this.data = data;
}
}
class OxiStorageSerializationError extends OxiStorageError {}
class OxiStorageDeserializationError extends OxiStorageError {}
/**
* @typedef {string | number | null | undefined | Record<string, UserscriptStorageValue>} UserscriptStorageValue
*/
/**
* @typedef {any} AssignationData
*/
class OxiStorage {
valueGetter = GM_getValue;
valueSetter = GM_setValue;
valueDeleter = GM_deleteValue ?? ((propPath) => {
this.valueSetter(propPath, undefined);
});
#activeProxies = [];
#proxyMetadata = Symbol("oxi storage proxy key");
constructor (
{ valueGetter,
valueSetter,
valueDeleter } = {}) {
this.valueGetter ??= valueGetter;
this.valueSetter ??= valueSetter;
this.valueDeleter ??= valueDeleter;
if (this.valueGetter("oxi_storage_metadata") == undefined) {
this.valueSetter("oxi_storage_metadata", {
version: [1, 0, 0],
creationDate: Date.now()
});
}
if (this.valueGetter(".") == undefined) {
this.valueSetter(".", {
root: true,
type: "object",
keys: [],
});
}
}
/**
* Check if `obj` is primitive.
* @param {any} obj
* @returns {boolean}
*/
static isPrimitive(obj) {
return !OxiStorage.isObject(obj) || obj === null;
}
/**
* Check if `obj` is an object, whether or not is a class object or dictionary object.
* @param {any} obj
* @returns {boolean}
*/
static isObject(obj) {
return typeof obj === "object" && !Array.isArray(obj) && obj !== null;
}
/**
* Check if `obj` is a dictionary object, an object that is usually created in object literal expression.
* @param {any} obj
* @returns {boolean}
*/
static isDictionaryObject(obj) {
return OxiStorage.isObject(obj) && obj.constructor == Object;
}
/**
* Check if `obj` is a class object, an object that is usually created/constructed by class.
* @param {any} obj
* @returns {boolean}
*/
static isClassObject(obj) {
return OxiStorage.isObject(obj) && obj.constructor != Object;
}
/**
* Check if `obj` is `OxiStorage` data object, an object that is stored in userscript storage, usually indicating that the property is an array or an object.
* @param {any} obj
* @returns {boolean}
*/
static isDataObject(obj) {
return obj?.type && true;
}
/**
* Split string path into array of string.
* @param {string} path
* @returns {string[]}
*/
static splitPath(path) {
path = OxiStorage.resolvePath(path);
return path.split(".");
}
/**
* Resolve string path to correct string path.
* @param {string | string[]} path
* @returns {string}
*/
static resolvePath(path) {
if (Array.isArray(path)) {
path = path.join(".");
}
if (path.includes("\\.")) {
throw new OxiStorage("escaping path character is not supported at the moment", {
data: { path }
});
}
if (path[0] != ".") {
return `.${path}`;
}
path = path.replace(/^\.+(.+)?/, ".$1");
return path;
}
/**
* @param {"update" | "delete"} mode
* @param {AssignationData} param1
*/
#modifyParentObjectData(mode, { parent, valueKey, subroot, parentKey } = {}) {
if (mode != "update" && mode != "delete") {
throw new TypeError(`modify parent object data: invalid mode "${mode}"`);
}
if (!OxiStorage.isDataObject(parent)) {
throw new OxiStorageSerializationError("value is not data object", {
data: {
subroot,
parent,
parentKey,
valueKey,
}
});
}
let assignationData;
switch (parent.type) {
case "object": {
assignationData = {
...parent,
keys: mode == "update"
? Array.from(new Set(parent.keys.concat(valueKey)))
: parent.keys.filter(i => i != valueKey),
};
} break;
case "array": {
assignationData = {
...parent,
length: mode == "update"
? parent.length + 1
: parent.length - 1,
};
} break;
}
this.valueSetter(OxiStorage.resolvePath([subroot, parentKey]), assignationData);
}
/**
* @param {string} path
* @returns {AssignationData}
*/
#getAssignationData(path) {
const parsedPath = OxiStorage.splitPath(path);
const [parentKey, valueKey] = parsedPath.slice(-2);
const subroot = parsedPath.slice(0, -2).join(".");
const parent = this.valueGetter(OxiStorage.resolvePath([subroot, parentKey]));
const value = this.valueGetter(`${path}`);
if (!OxiStorage.isDataObject(parent)) {
return { parent: undefined, parentKey, value, valueKey };
}
return { parent, parentKey, value, valueKey, subroot };
}
/**
* Get value from the userscript storage.
* @template {UserscriptStorageValue} T
* @param {string | string[]} path - any valid path can be resolved by `OxiStorage#resolvePath()`.
* @returns {T} - usually JSON primitives, but may also return `undefined` if the property does not exist.
*/
getValue(path) {
path = OxiStorage.resolvePath(path);
const { parent, parentKey, value } = this.#getAssignationData(path);
if (parent == undefined) {
throw new OxiStorageDeserializationError("parent is undefined", {
data: {
parent,
parentKey,
path,
value
}
});
}
if (OxiStorage.isDataObject(value)) {
return this.createProxy(path, value);
}
else {
return value;
}
}
/**
* Set value in the userscript storage.
* @param {string | string[]} path - any valid path can be resolved by `OxiStorage#resolvePath()`.
* @param {UserscriptStorageValue} value - JSON primitives.
* @returns {void}
*/
setValue(path, value) {
path = OxiStorage.resolvePath(path);
const { parent, parentKey, valueKey, subroot } = this.#getAssignationData(path);
if (parent == undefined) {
throw new OxiStorageDeserializationError("parent is undefined", {
data: {
parent,
parentKey,
path,
value
}
});
}
if (OxiStorage.isClassObject(value)) {
throw new OxiStorageSerializationError("unsupported class object", {
data: {
type: typeof value,
value
}
});
}
this.deleteValue(path);
if (OxiStorage.isDictionaryObject(value)) {
this.valueSetter(path, {
type: "object",
keys: Object.keys(value),
});
for (const [okey, ovalue] of Object.entries(value)) {
this.setValue([path, okey], ovalue);
}
}
else if (Array.isArray(value)) {
this.valueSetter(path, {
type: "array",
length: value.length,
});
for (let index = 0; index < value.length; index++) {
this.setValue([path, index], value[index]);
}
}
else {
if (OxiStorage.isPrimitive(value)) {
this.valueSetter(path, value);
}
else {
this.setValue(path, value);
}
}
this.#modifyParentObjectData("update", { parent, valueKey, subroot, parentKey });
}
/**
* Delete value from the userscript storage.
* @param {string | string[]} path - any valid path can be resolved by `OxiStorage#resolvePath()`.
* @returns {void}
*/
deleteValue(path) {
path = OxiStorage.resolvePath(path);
const { parent, parentKey, valueKey, value, subroot } = this.#getAssignationData(path);
if (parent == undefined) {
throw new OxiStorageDeserializationError("parent is undefined", {
data: {
parent,
parentKey,
path,
value
}
});
}
if (OxiStorage.isDataObject(value)) {
for (const key of value.keys) {
this.valueDeleter(`${path}.${key}`);
}
}
this.valueDeleter(path);
this.#modifyParentObjectData("delete", { parent, valueKey, subroot, parentKey });
}
/**
* Create a proxy from path. You can access userscript storage using object notation by creating a proxy.
* @template {Record<string, UserscriptStorageValue>} T
* @param {string | string[]} path - any valid path can be resolved by `OxiStorage#resolvePath()`.
* @param {{ type: "array" | "object" }} objectDescriptor
* @returns {T}
*/
createProxy(path, { type }) {
const proxy = new Proxy({
isActive: true
}, {
get: (target, prop, receiver) => {
if (prop == this.#proxyMetadata) {
return target;
}
if (!target.isActive) {
return undefined;
}
if (prop == Symbol.toPrimitive) {
return { type };
}
if (!(typeof prop == "string" || typeof prop == "number")) {
throw new OxiStorageDeserializationError("unexpected non-primitive property", {
data: {
type: typeof prop,
prop,
}
});
}
return this.getValue([path, prop]);
},
set: (target, prop, value, receiver) => {
if (prop == this.#proxyMetadata) {
throw new OxiStorageSerializationError("unexpected assignment: proxy metadata", {
data: {
prop,
}
});
}
if (!target.isActive) {
return false;
}
if (!OxiStorage.isPrimitive(value)) {
throw new OxiStorageSerializationError("type of value is not primitive type", {
data: {
type: typeof value,
value
}
});
}
this.setValue([path, prop], value);
return true;
}
});
this.#activeProxies.push(proxy);
return proxy;
}
/**
* Disable and remove created proxy from this class.
* @param {Record<string, UserscriptStorageValue>} proxy
* @returns {void}
*/
removeProxy(proxy) {
proxy[this.#proxyMetadata].isActive = false;
this.#activeProxies = this.#activeProxies.filter(p => p != proxy);
}
}