-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.library.ts
More file actions
335 lines (275 loc) · 10.9 KB
/
Copy pathserialize.library.ts
File metadata and controls
335 lines (275 loc) · 10.9 KB
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
import { curry } from '#library/function.library.js';
import { ownKeys, ownValues, ownEntries } from '#library/primitive.library.js';
import { asType } from '#library/type.library.js';
import { isType, isEmpty, isDefined, isUndefined, isNullish, isString, isObject, isArray, isFunction, isSymbolFor, isSymbol } from '#library/assertion.library.js';
import { sym } from '#library/symbol.library.js';
import type { Obj, Type } from '#library/type.library.js';
export const Registry = (globalThis as any)[sym.$SerializerRegistry] ??= new Map<string, Function>();
/** register a Class for serialization */
export const registerSerializable = (name: string, cls: Function) => {
const key = name.startsWith('$') ? name : `$${name}`;
if (Registry.has(key)) {
const existingCls = Registry.get(key);
if (existingCls === cls || existingCls?.toString() === cls.toString()) {
return; // Silently allow idempotent dual-registration
}
throw new Error(`[registerSerializable] Collision: '${key}' is already registered with ${existingCls?.name || 'anonymous constructor'}`);
}
Registry.set(key, cls);
}
// be aware that 'structuredClone' preserves \<undefined> values...
// and JSON.stringify() does not
/** make a deep-copy, using standard browser or JSON functions */
export function clone<T>(obj: T, opts?: { transfer: any[] }) {
try {
return globalThis.structuredClone(obj, opts);
} catch {
return cleanify(obj); // fallback to JSON functions
}
}
/** return a copy. remove unsupported values (e.g. \<undefined>, function) */
export function cleanify<T>(obj: T) {
try {
return JSON.parse(JSON.stringify(obj)) as T; // run any toString() methods
} catch (error) {
console.warn('Could not clean object: ', obj);
return { ...obj }
}
}
/** deep-copy an Object, and optionally replace \<undefined> fields with a Sentinel function call */
export function cloneify<T>(obj: T, sentinel?: Function): T {
try {
return objectify(stringify(obj), sentinel) as T;
} catch (error) {
console.warn('Could not cloneify object: ', obj);
console.warn('stack: ', (error as Error).stack);
return obj;
}
}
function replacer(key: string, obj: any): any { return isEmpty(key) ? obj : stringize(obj) }
function reviver(_key: string, val: any): any { return decode(val) }
// safe-characters [sp " ; < > [ ] ^ { | }]
const safeList = ['20', '22', '3B', '3C', '3E', '5B', '5D', '5E', '7B', '7C', '7D'];
/** encode control characters, then replace a safe-subset back to text-string */
function encode(val: string) {
let enc = encodeURI(val);
if (enc.includes('%')) { // if an encoded URI might be in string
safeList.forEach(code => {
const uri = '%' + code;
const reg = new RegExp(uri, 'g');
enc = enc.replace(reg, decodeURI(uri));
})
}
return enc;
}
/** decode control characters */
function decode(val: string) {
if (isString(val)) {
try {
return decodeURI(val); // might fail if badly encoded '%'
} catch (error) {
// console.warn(`decodeURI: ${(error as Error).message} -> ${val}`);
}
}
return val; // return original value
}
/** check type can be stringify'd */
function isStringable(val: unknown): boolean {
return !isType(val, 'Function', 'AsyncFunction', 'WeakMap', 'WeakSet', 'WeakRef');
}
/** string representation of a single key:value Object */
function oneKey(type: Type, value: string) {
return `{"$${type}":${value}}`;
}
/** Symbols in an Object-key will need special treatment */
function fromSymbol(key: PropertyKey) {
return stringize(isSymbol(key) // @@(name) for global, @(name) for local symbols
? `${isSymbolFor(key) ? '@' : ''}@(${key.description ?? ''})`
: key)
}
const symKey = /^@(@)?\(([^\)]*)\)$/; // pattern to match a stringify'd Symbol
/** reconstruct a Symbol from a string-representation of a key */
function toSymbol(value: PropertyKey) {
const [pat, keyFor, desc] = value.toString().match(symKey) || [null, undefined, undefined];
switch (true) {
case isSymbol(value): // already a Symbol
case isNullish(pat): // incorrectly encoded Symbol
case isDefined(keyFor) && isUndefined(desc): // incorrectly encoded global Symbol
return value;
case isDefined(keyFor): // global Symbol
return Symbol.for(desc!);
case isUndefined(keyFor): // local Symbol
default:
return Symbol(desc);
}
}
/**
* For items which are not currently serializable via standard JSON.stringify (Undefined, BigInt, Set, Map, Symbol, etc.)
* this creates a stringified, single key:value Object to represent the value; for example '{ "$BigInt": 123 }'
*
* Drawbacks:
* no support Function / WeakMap / WeakSet / WeakRef
* limited support for user-defined Classes (must be specifically registered with @Serialize() decorator)
*/
/**
* serialize Objects for string-safe stashing in WebStorage, Cache, etc
* uses JSON.stringify where available, else returns stringified single key:value Object '{[$type]: value}'
*/
export function stringify<T>(obj: T) {
return stringize(obj, false);
}
/**
* internal function to process stringify-requests (and hide second parameter)
* where first argument is the object to stringify, and
* the second argument is a boolean to indicate if function is being called recursively
*/
function stringize<T>(obj: T, recurse = true): string { // hide the second parameter: for internal use only
const arg = asType(obj);
const one = curry(oneKey)(arg.type); // curry the oneKey() function
switch (arg.type) {
case 'String':
if (!recurse) { // if a top-level string (e.g. 'true' or '1234')
recurse = arg.value === 'true' // ensure true|false|null|1234 are quoted by JSON.stringify
|| arg.value === 'false' // so they will be correctly identified during objectify()
|| arg.value === 'null'
|| parseFloat(arg.value).toString() === arg.value
}
return recurse
? JSON.stringify(encode(arg.value)) // encode string for safe-storage
: encode(arg.value); // dont JSON.stringify a top-level string
case 'Boolean':
case 'Null':
case 'Number':
return JSON.stringify(arg.value); // JSON.stringify will correctly handle these
case 'Void':
case 'Undefined':
return one(JSON.stringify('void')); // preserve 'undefined' values
case 'BigInt':
return one(arg.value.toString()); // even though BigInt has a toString method, it is not supported in JSON.stringify
case 'Object':
const obj = ownEntries(arg.value)
.filter(([, val]) => isStringable(val))
.map(([key, val]) => `${fromSymbol(key)}: ${stringize(val)}`)
.join(',')
return `{${obj}}`;
case 'Array':
const arr = arg.value
.filter(val => isStringable(val))
.map(val => stringize(val))
.join(',')
return `[${arr}]`;
case 'Map':
const map = Array.from(arg.value.entries())
.filter(([, val]) => isStringable(val))
.map(([key, val]) => `[${stringize(key)}, ${stringize(val)}]`)
.join(',')
return one(`[${map}]`);
case 'Set':
const set = Array.from(arg.value.values())
.filter(val => isStringable(val))
.map(val => stringize(val))
.join(',')
return one(`[${set}]`);
case 'Symbol':
return one(fromSymbol(arg.value));
case 'RegExp':
return one(stringize({ source: arg.value.source, flags: arg.value.flags }));
case 'Class':
default:
const value = arg.value as any;
switch (true) {
case !isStringable(value): // Object is not stringify-able
return undefined as unknown as string;
case isFunction(value.toJSON): // Object has its own toJSON method
return one(stringize(value.toJSON(), /** replacer */));
case isFunction(value.toString): // Object has its own toString method
const str = value.toString();
return one(str.includes('"') // TODO: improve detection of JSON vs non-JSON strings
? str
: JSON.stringify(str));
case isFunction(value.valueOf): // Object has its own valueOf method
return one(JSON.stringify(value.valueOf()));
default: // else standard stringify
return one(JSON.stringify(value, replacer));
}
}
}
/** rebuild an Object from its stringified representation */
export function objectify<T>(str: any, sentinel?: Function): T {
if (!isString(str))
return str; // skip parsing
let parse: any;
try {
parse = JSON.parse(str, reviver); // catch if cannot parse
} catch (error) {
if (str.startsWith('"') && str.endsWith('"')) {
console.warn(`objectify.parse: -> ${str}, ${(error as Error).message}`);
return str as unknown as T; // bail-out
}
else return objectify(`"${str}"`, sentinel); // have another try, quoted
}
switch (true) {
case str.startsWith('{') && str.endsWith('}'): // looks like Object
case str.startsWith('[') && str.endsWith(']'): // looks like Array
return traverse(parse, sentinel); // recurse into object
default:
return parse;
}
}
/** recurse into Object / Array, looking for special single key:value Objects */
function traverse(obj: Obj, sentinel?: Function): any {
if (isObject(obj)) {
return typeify(ownEntries(obj)
.reduce((acc, [key, val]) => Object.assign(acc, { [toSymbol(key)]: typeify(traverse(val, sentinel)) }), {}),
sentinel
)
}
if (isArray(obj)) {
return ownValues(obj)
.map(val => typeify(traverse(val, sentinel)))
}
return obj;
}
/** rebuild an Object from its single key:value representation */
function typeify(json: any, sentinel?: Function) {
if (!isObject(json) || ownKeys(json).length !== 1)
return json; // only JSON Objects, with a single key:value pair
const [$type, value] = ownEntries(json)[0] as unknown as [`$${Type}`, any];
if (!String($type).startsWith('$'))
return json; // not a serialized single key:value Object
const type = $type.substring(1) as Type; // remove '$' prefix
switch (type) {
case 'String':
case 'Boolean':
case 'Object':
case 'Array':
return value; // these types are already handled by traverse()
case 'Number':
return Number(value);
case 'BigInt':
return BigInt(value);
case 'Null':
return null;
case 'Undefined':
case 'Empty':
case 'Void':
return sentinel?.(); // run Sentinel function to handle undefined values
case 'Date':
return new Date(value);
case 'RegExp':
return new RegExp(value.source, value.flags);
case 'Symbol':
return toSymbol(value);
case 'Map':
return new Map(value);
case 'Set':
return new Set(value);
default:
const cls = Registry.get($type); // lookup registered Class
if (!cls) {
console.warn(`objectify: dont know how to deserialize '${type}'`);
return json; // return original JSON object
}
return Reflect.construct(cls, [value]) // create new Class instance
}
}