-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.ts
506 lines (430 loc) · 14.6 KB
/
index.ts
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable import/no-extraneous-dependencies */
import isRegExp from 'is-regex';
import isFunction from 'is-function';
import isSymbol from 'is-symbol';
import isObjectAny from 'isobject';
import { get } from 'lodash-es';
import memoize from 'memoizerific';
import { extractEventHiddenProperties } from './dom-event';
// eslint-disable-next-line @typescript-eslint/ban-types, no-use-before-define
const isObject = isObjectAny as <T = object>(val: any) => val is T;
const removeCodeComments = (code: string) => {
let inQuoteChar = null;
let inBlockComment = false;
let inLineComment = false;
let inRegexLiteral = false;
let newCode = '';
if (code.indexOf('//') >= 0 || code.indexOf('/*') >= 0) {
for (let i = 0; i < code.length; i += 1) {
if (!inQuoteChar && !inBlockComment && !inLineComment && !inRegexLiteral) {
if (code[i] === '"' || code[i] === "'" || code[i] === '`') {
inQuoteChar = code[i];
} else if (code[i] === '/' && code[i + 1] === '*') {
inBlockComment = true;
} else if (code[i] === '/' && code[i + 1] === '/') {
inLineComment = true;
} else if (code[i] === '/' && code[i + 1] !== '/') {
inRegexLiteral = true;
}
} else {
if (
inQuoteChar &&
((code[i] === inQuoteChar && code[i - 1] !== '\\') ||
(code[i] === '\n' && inQuoteChar !== '`'))
) {
inQuoteChar = null;
}
if (inRegexLiteral && ((code[i] === '/' && code[i - 1] !== '\\') || code[i] === '\n')) {
inRegexLiteral = false;
}
if (inBlockComment && code[i - 1] === '/' && code[i - 2] === '*') {
inBlockComment = false;
}
if (inLineComment && code[i] === '\n') {
inLineComment = false;
}
}
if (!inBlockComment && !inLineComment) {
newCode += code[i];
}
}
} else {
newCode = code;
}
return newCode;
};
const cleanCode = memoize(10000)((code: string) =>
removeCodeComments(code)
.replace(/\n\s*/g, '') // remove indents & newlines
.trim()
);
const convertShorthandMethods = function convertShorthandMethods(key: string, stringified: string) {
const fnHead = stringified.slice(0, stringified.indexOf('{'));
const fnBody = stringified.slice(stringified.indexOf('{'));
if (fnHead.includes('=>')) {
// This is an arrow function
return stringified;
}
if (fnHead.includes('function')) {
// This is an anonymous function
return stringified;
}
let modifiedHead = fnHead;
modifiedHead = modifiedHead.replace(key, 'function');
return modifiedHead + fnBody;
};
const dateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
export interface Options {
allowRegExp: boolean;
allowFunction: boolean;
allowSymbol: boolean;
allowDate: boolean;
allowUndefined: boolean;
allowClass: boolean;
allowError: boolean;
maxDepth: number;
space: number | undefined;
lazyEval: boolean;
}
// eslint-disable-next-line no-useless-escape
export const isJSON = (input: string) => input.match(/^[\[\{\"\}].*[\]\}\"]$/);
function convertUnconventionalData(data: unknown) {
if (!isObject(data)) {
return data;
}
let result: any = data;
let wasMutated = false;
// `Event` has a weird structure, for details see `extractEventHiddenProperties` doc
// Plus we need to check if running in a browser to ensure `Event` exist and
// is really the dom Event class.
if (typeof Event !== 'undefined' && data instanceof Event) {
result = extractEventHiddenProperties(result);
wasMutated = true;
}
result = Object.keys(result).reduce((acc, key) => {
try {
// Try accessing a property to test if we are allowed to do so
// We have a if statement, and not a optional chaining, because webpack4 doesn't support it, and react-native uses it
if (result[key]) {
// eslint-disable-next-line no-unused-expressions, @typescript-eslint/no-unused-expressions
result[key].toJSON;
}
acc[key] = result[key];
} catch (err) {
wasMutated = true;
}
return acc;
}, {} as any);
return wasMutated ? result : data;
}
export const replacer = function replacer(options: Options): any {
let objects: Map<any, string>;
let map: Map<any, any>;
let stack: any[];
let keys: string[];
return function replace(this: any, key: string, value: any) {
try {
// very first iteration
if (key === '') {
keys = [];
objects = new Map([[value, '[]']]);
map = new Map();
stack = [];
return value;
}
// From the JSON.stringify's doc:
// "The object in which the key was found is provided as the replacer's this parameter." thus one can control the depth
const origin = map.get(this) || this;
while (stack.length && origin !== stack[0]) {
stack.shift();
keys.pop();
}
if (typeof value === 'boolean') {
return value;
}
if (value === undefined) {
if (!options.allowUndefined) {
return undefined;
}
return '_undefined_';
}
if (value === null) {
return null;
}
if (typeof value === 'number') {
if (value === -Infinity) {
return '_-Infinity_';
}
if (value === Infinity) {
return '_Infinity_';
}
if (Number.isNaN(value)) {
return '_NaN_';
}
return value;
}
if (typeof value === 'bigint') {
return `_bigint_${value.toString()}`;
}
if (typeof value === 'string') {
if (dateFormat.test(value)) {
if (!options.allowDate) {
return undefined;
}
return `_date_${value}`;
}
return value;
}
if (isRegExp(value)) {
if (!options.allowRegExp) {
return undefined;
}
return `_regexp_${value.flags}|${value.source}`;
}
if (isFunction(value)) {
if (!options.allowFunction) {
return undefined;
}
const { name } = value;
const stringified = value.toString();
if (
!stringified.match(
/(\[native code\]|WEBPACK_IMPORTED_MODULE|__webpack_exports__|__webpack_require__)/
)
) {
return `_function_${name}|${cleanCode(convertShorthandMethods(key, stringified))}`;
}
return `_function_${name}|${(() => {}).toString()}`;
}
if (isSymbol(value)) {
if (!options.allowSymbol) {
return undefined;
}
const globalRegistryKey = Symbol.keyFor(value);
if (globalRegistryKey !== undefined) {
return `_gsymbol_${globalRegistryKey}`;
}
return `_symbol_${value.toString().slice(7, -1)}`;
}
if (stack.length >= options.maxDepth) {
if (Array.isArray(value)) {
return `[Array(${value.length})]`;
}
return '[Object]';
}
if (value === this) {
return `_duplicate_${JSON.stringify(keys)}`;
}
if (value instanceof Error && options.allowError) {
return {
__isConvertedError__: true,
errorProperties: {
// @ts-expect-error cause is not defined in the current tsconfig target(es2020)
...(value.cause ? { cause: value.cause } : {}),
...value,
name: value.name,
message: value.message,
stack: value.stack,
'_constructor-name_': value.constructor.name,
},
};
}
// when it's a class and we don't want to support classes, skip
if (
value.constructor &&
value.constructor.name &&
value.constructor.name !== 'Object' &&
!Array.isArray(value) &&
!options.allowClass
) {
return undefined;
}
const found = objects.get(value);
if (!found) {
const converted = Array.isArray(value) ? value : convertUnconventionalData(value);
if (
value.constructor &&
value.constructor.name &&
value.constructor.name !== 'Object' &&
!Array.isArray(value) &&
options.allowClass
) {
try {
Object.assign(converted, { '_constructor-name_': value.constructor.name });
} catch (e) {
// immutable objects can't be written to and throw
// we could make a deep copy but if the user values the correct instance name,
// the user should make the deep copy themselves.
}
}
keys.push(key);
stack.unshift(converted);
objects.set(value, JSON.stringify(keys));
if (value !== converted) {
map.set(value, converted);
}
return converted;
}
// actually, here's the only place where the keys keeping is useful
return `_duplicate_${found}`;
} catch (e) {
return undefined;
}
};
};
interface ValueContainer {
'_constructor-name_'?: string;
[keys: string]: any;
}
export const reviver = function reviver(options: Options): any {
const refs: { target: string; container: { [keys: string]: any }; replacement: string }[] = [];
let root: any;
return function revive(this: any, key: string, value: ValueContainer | string) {
// last iteration = root
if (key === '') {
root = value;
// restore cyclic refs
refs.forEach(({ target, container, replacement }) => {
const replacementArr = isJSON(replacement)
? JSON.parse(replacement)
: replacement.split('.');
if (replacementArr.length === 0) {
// eslint-disable-next-line no-param-reassign
container[target] = root;
} else {
// eslint-disable-next-line no-param-reassign
container[target] = get(root, replacementArr);
}
});
}
if (key === '_constructor-name_') {
return value;
}
// eslint-disable-next-line no-underscore-dangle
if (isObject<ValueContainer>(value) && value.__isConvertedError__) {
// reconstruct the error with its original properties
const { message, ...properties } = value.errorProperties;
const error = new Error(message);
Object.assign(error, properties);
return error;
}
// deal with instance names
if (isObject<ValueContainer>(value) && value['_constructor-name_'] && options.allowFunction) {
const name = value['_constructor-name_'];
if (name !== 'Object') {
// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
const Fn = new Function(`return function ${name.replace(/[^a-zA-Z0-9$_]+/g, '')}(){}`)();
Object.setPrototypeOf(value, new Fn());
}
// eslint-disable-next-line no-param-reassign
delete value['_constructor-name_'];
return value;
}
if (typeof value === 'string' && value.startsWith('_function_') && options.allowFunction) {
const [, name, source] = value.match(/_function_([^|]*)\|(.*)/) || [];
// eslint-disable-next-line no-useless-escape
const sourceSanitized = source.replace(/[(\(\))|\\| |\]|`]*$/, '');
if (!options.lazyEval) {
// eslint-disable-next-line no-eval
return eval(`(${sourceSanitized})`);
}
// lazy eval of the function
const result = (...args: any[]) => {
// eslint-disable-next-line no-eval
const f = eval(`(${sourceSanitized})`);
return f(...args);
};
Object.defineProperty(result, 'toString', {
value: () => sourceSanitized,
});
Object.defineProperty(result, 'name', {
value: name,
});
return result;
}
if (typeof value === 'string' && value.startsWith('_regexp_') && options.allowRegExp) {
// this split isn't working correctly
const [, flags, source] = value.match(/_regexp_([^|]*)\|(.*)/) || [];
return new RegExp(source, flags);
}
if (typeof value === 'string' && value.startsWith('_date_') && options.allowDate) {
return new Date(value.replace('_date_', ''));
}
if (typeof value === 'string' && value.startsWith('_duplicate_')) {
refs.push({ target: key, container: this, replacement: value.replace(/^_duplicate_/, '') });
return null;
}
if (typeof value === 'string' && value.startsWith('_symbol_') && options.allowSymbol) {
return Symbol(value.replace('_symbol_', ''));
}
if (typeof value === 'string' && value.startsWith('_gsymbol_') && options.allowSymbol) {
return Symbol.for(value.replace('_gsymbol_', ''));
}
if (typeof value === 'string' && value === '_-Infinity_') {
return -Infinity;
}
if (typeof value === 'string' && value === '_Infinity_') {
return Infinity;
}
if (typeof value === 'string' && value === '_NaN_') {
return NaN;
}
if (typeof value === 'string' && value.startsWith('_bigint_') && typeof BigInt === 'function') {
return BigInt(value.replace('_bigint_', ''));
}
return value;
};
};
const defaultOptions: Options = {
maxDepth: 10,
space: undefined,
allowFunction: true,
allowRegExp: true,
allowDate: true,
allowClass: true,
allowError: true,
allowUndefined: true,
allowSymbol: true,
lazyEval: true,
};
export const stringify = (data: unknown, options: Partial<Options> = {}) => {
const mergedOptions: Options = { ...defaultOptions, ...options };
return JSON.stringify(convertUnconventionalData(data), replacer(mergedOptions), options.space);
};
const mutator = () => {
const mutated: Map<any, boolean> = new Map();
return function mutateUndefined(value: any) {
// JSON.parse will not output keys with value of undefined
// we map over a deeply nester object, if we find any value with `_undefined_`, we mutate it to be undefined
if (isObject<{ [keys: string]: any }>(value)) {
Object.entries(value).forEach(([k, v]) => {
if (v === '_undefined_') {
// eslint-disable-next-line no-param-reassign
value[k] = undefined;
} else if (!mutated.get(v)) {
mutated.set(v, true);
mutateUndefined(v);
}
});
}
if (Array.isArray(value)) {
value.forEach((v, index) => {
if (v === '_undefined_') {
mutated.set(v, true);
// eslint-disable-next-line no-param-reassign
value[index] = undefined;
} else if (!mutated.get(v)) {
mutated.set(v, true);
mutateUndefined(v);
}
});
}
};
};
export const parse = (data: string, options: Partial<Options> = {}) => {
const mergedOptions: Options = { ...defaultOptions, ...options };
const result = JSON.parse(data, reviver(mergedOptions));
mutator()(result);
return result;
};