-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtypeson.js
1609 lines (1498 loc) · 55.5 KB
/
typeson.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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file Typeson - JSON with types.
* @license The MIT License (MIT)
* @copyright (c) 2016-2018 David Fahlander, Brett Zamir
*/
/**
* @typedef {number} Integer
*/
/**
* @typedef {object} StateObject
* @property {string} [type]
* @property {boolean} [replaced]
* @property {"object"|"array"} [iterateIn]
* @property {boolean} [iterateUnsetNumeric]
* @property {boolean} [addLength]
* @property {boolean} [ownKeys]
*/
/**
* @callback Tester
* @param {any} value
* @param {StateObject} stateobj
* @returns {boolean}
*/
/**
* @callback Replacer
* @param {any} value
* @param {StateObject} stateObj
* @returns {any} Should be JSON-stringifiable
*/
/**
* @callback AsyncReplacer
* @param {any} value
* @param {StateObject} stateObj
* @returns {TypesonPromise<any>} Should be JSON-stringifiable
*/
/**
* @callback Reviver
* @param {any} value May not be JSON if processed already by another type
* @param {StateObject} stateObj
* @returns {any}
*/
/**
* @callback AsyncReviver
* @param {any} value May not be JSON if processed already by another type
* @param {StateObject} stateObj
* @returns {TypesonPromise<any>|Promise<any>}
*/
/**
* @typedef {{
* testPlainObjects?: boolean,
* test?: Tester,
* replace?: Replacer,
* replaceAsync?: AsyncReplacer,
* revive?: Reviver,
* reviveAsync?: AsyncReviver
* }} Spec
*/
/**
* @typedef {{
* [key: string]:
* Spec|Function|[Tester, Replacer, Reviver?]|(new () => any)|null
* }} TypeSpecSet
*/
/**
* @typedef {(TypeSpecSet|Preset)[]} Preset
*/
/**
* @typedef {import(
* './utils/classMethods.js'
* ).ObjectTypeString} ObjectTypeString
*/
/**
* @typedef {{
* type: string,
* test: (val: any, stateObj: StateObject) => boolean,
* replace?: Replacer,
* replaceAsync?: AsyncReplacer
* }} ReplacerObject
*/
/**
* @typedef {{
* revive?: Reviver,
* reviveAsync?: AsyncReviver
* }} ReviverObject
*/
import {TypesonPromise} from './utils/TypesonPromise.js';
import {
isPlainObject, isObject, hasConstructorOf,
isThenable,
escapeKeyPathComponent,
getByKeyPath, setAtKeyPath, getJSONType
} from './utils/classMethods.js';
const {keys, hasOwn} = Object,
{isArray} = Array,
// eslint-disable-next-line @stylistic/max-len -- Long
/** @type {("type"|"replaced"|"iterateIn"|"iterateUnsetNumeric"|"addLength")[]} */
internalStateObjPropsToIgnore = [
'type', 'replaced', 'iterateIn', 'iterateUnsetNumeric', 'addLength'
];
/**
* @typedef {object} PlainObjectType
* @property {string} keypath
* @property {string} type
*/
/**
* Handle plain object revivers first so reference setting can use
* revived type (e.g., array instead of object); assumes revived
* has same structure or will otherwise break subsequent references.
* @param {PlainObjectType} a
* @param {PlainObjectType} b
* @returns {1|-1|0}
*/
function nestedPathsFirst (a, b) {
if (a.keypath === '') {
return -1;
}
let as = a.keypath.match(/\./gu) ?? 0;
let bs = b.keypath.match(/\./gu) ?? 0;
if (as) {
as = /** @type {RegExpMatchArray} */ (as).length;
}
if (bs) {
bs = /** @type {RegExpMatchArray} */ (bs).length;
}
return as > bs
? -1
: as < bs
? 1
: a.keypath < b.keypath
? -1
: a.keypath > b.keypath
? 1
// Keypath should never be the same
/* c8 ignore next 1 */
: 0;
}
/**
* @typedef {object} KeyPathEvent
* @property {string} [cyclicKeypath]
*/
/**
* @typedef {object} EndIterateInEvent
* @property {boolean} [endIterateIn]
* @property {boolean} [end]
*/
/**
* @typedef {{
* endIterateOwn?: boolean
* }} EndIterateOwnEvent
*/
/**
* @typedef {object} EndIterateUnsetNumericEvent
* @property {boolean} [endIterateUnsetNumeric]
* @property {boolean} [end]
*/
/**
* @typedef {object} TypeDetectedEvent
* @property {boolean} [typeDetected]
*/
/**
* @typedef {object} ReplacingEvent
* @property {boolean} [replacing]
*/
/**
* @typedef {[
* keyPath: string,
* value: object|Array<any>|TypesonPromise<any>,
* cyclic: boolean|"readonly"|undefined,
* stateObj: StateObject,
* clone: {[key: (string|Integer)]: any}|undefined,
* key: string|Integer|undefined,
* stateObjType: string|undefined
* ][]} PromisesData
*/
/**
* @typedef {KeyPathEvent & EndIterateInEvent & EndIterateOwnEvent &
* EndIterateUnsetNumericEvent &
* TypeDetectedEvent & ReplacingEvent & {} & {
* replaced?: any
* } & {
* clone?: {[key: string]: any}
* } & {
* keypath: string,
* value: any,
* cyclic: boolean|undefined|"readonly",
* stateObj: StateObject,
* promisesData: PromisesData,
* resolvingTypesonPromise: ?boolean|undefined,
* awaitingTypesonPromise: boolean
* } & {type: string}} ObserverData
*/
/**
* @typedef {(data: ObserverData) => void} EncapsulateObserver
*/
/**
* @callback Observer
* @param {KeyPathEvent|EndIterateInEvent|EndIterateOwnEvent|
* EndIterateUnsetNumericEvent|
* TypeDetectedEvent|ReplacingEvent} [event]
* @returns {void}
*/
/**
* @typedef {object} TypesonOptions
* @property {boolean} [stringification] Auto-set by `stringify`
* @property {boolean} [parse] Auto-set by `parse`
* @property {boolean} [sync] Can be overridden when auto-set by
* `encapsulate` and `revive`.
* @property {boolean} [returnTypeNames] Auto-set by `specialTypeNames`
* @property {boolean} [iterateNone] Auto-set by `rootTypeName`
* @property {boolean} [cyclic]
* @property {boolean} [throwOnBadSyncType] Auto-set by `stringifyAsync`,
* `stringifySync`, `parseSync`, `parseAsync`, `encapsulateSync`,
* `encapsulateAync`, `reviveSync`, `reviveAsync`
* @property {number|boolean} [fallback] `true` sets to 0. Default is
* positive infinity. Used within `register`
* @property {EncapsulateObserver} [encapsulateObserver]
*/
/**
* An instance of this class can be used to call `stringify()` and `parse()`.
* Typeson resolves cyclic references by default. Can also be extended to
* support custom types using the register() method.
*
* @class
* @param {{cyclic: boolean}} [options] - if cyclic (default true),
* cyclic references will be handled gracefully.
*/
class Typeson {
/**
* @param {TypesonOptions} [options]
*/
constructor (options) {
this.options = options;
// Replacers signature: replace (value). Returns falsy if not
// replacing. Otherwise ['Date', value.getTime()]
/** @type {ReplacerObject[]} */
this.plainObjectReplacers = [];
/** @type {ReplacerObject[]} */
this.nonplainObjectReplacers = [];
// Revivers: [{type => reviver}, {plain: boolean}].
// Sample: [{'Date': value => new Date(value)}, {plain: false}]
/**
* @type {{
* [key: string]: [
* ReviverObject|undefined,
* {plain: boolean|undefined}
* ]|undefined}}
*/
this.revivers = {};
/** Types registered via `register()`. */
/** @type {TypeSpecSet} */
this.types = {};
}
/**
* @typedef {null|boolean|number|string} Primitive
*/
/**
* @typedef {Primitive|Primitive[]|{[key: string]: JSON}} JSON
*/
/**
* @callback JSONReplacer
* @param {""|string} key
* @param {JSON} value
* @returns {any}
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter
*/
/**
* Serialize given object to Typeson.
* Initial arguments work identical to those of `JSON.stringify`.
* The `replacer` argument has nothing to do with our replacers.
* @param {any} obj
* @param {?(JSONReplacer|string[]|undefined)} [replacer]
* @param {number|string|null|undefined} [space]
* @param {TypesonOptions} [opts]
* @returns {string|Promise<string>} Promise resolves to a string
*/
stringify (obj, replacer, space, opts) {
opts = {...this.options, ...opts, stringification: true};
const encapsulated = this.encapsulate(obj, null, opts);
if (isArray(encapsulated)) {
return JSON.stringify(
encapsulated[0],
// Casting type due to error in JSON.stringify type
// not accepting `null`
/** @type {JSONReplacer|undefined} */ (replacer),
/** @type {string|number|undefined} */ (space)
);
}
return /** @type {Promise<string>} */ (encapsulated).then((res) => {
return JSON.stringify(
res,
// Casting type due to error in JSON.stringify type
/** @type {JSONReplacer|undefined} */ (replacer),
/** @type {string|number|undefined} */ (space)
);
});
}
/**
* Also sync but throws on non-sync result.
* @param {any} obj
* @param {?(JSONReplacer|string[]|undefined)} [replacer]
* @param {number|string} [space]
* @param {TypesonOptions} [opts]
* @returns {string}
*/
stringifySync (obj, replacer, space, opts) {
return /** @type {string} */ (this.stringify(obj, replacer, space, {
throwOnBadSyncType: true, ...opts, sync: true
}));
}
/**
*
* @param {any} obj
* @param {JSONReplacer|string[]|null|undefined} [replacer]
* @param {number|string|null|undefined} [space]
* @param {TypesonOptions} [opts]
* @returns {Promise<string>}
*/
stringifyAsync (obj, replacer, space, opts) {
return /** @type {Promise<string>} */ (
this.stringify(obj, replacer, space, {
throwOnBadSyncType: true, ...opts, sync: false
})
);
}
/**
* @callback JSONReviver
* @param {string} key
* @param {JSON} value
* @returns {JSON}
*/
/**
* Parse Typeson back into an obejct.
* Initial arguments works identical to those of `JSON.parse()`.
* @param {string} text
* @param {?JSONReviver} [reviver] This JSON reviver has nothing to do with
* our revivers.
* @param {TypesonOptions} [opts]
* @returns {any|Promise<any>}
*/
parse (text, reviver, opts) {
opts = {...this.options, ...opts, parse: true};
return this.revive(
JSON.parse(text, /** @type {JSONReviver|undefined} */ (reviver)),
opts
);
}
/**
* Also sync but throws on non-sync result.
* @param {string} text
* @param {JSONReviver} [reviver] This JSON reviver has nothing to do with
* our revivers.
* @param {TypesonOptions} [opts]
* @returns {any}
*/
parseSync (text, reviver, opts) {
return this.parse(
text,
reviver,
{throwOnBadSyncType: true, ...opts, sync: true}
);
}
/**
* @param {string} text
* @param {JSONReviver} [reviver] This JSON reviver has nothing to do with
* our revivers.
* @param {TypesonOptions} [opts]
* @returns {Promise<any>}
*/
parseAsync (text, reviver, opts) {
return this.parse(
text,
reviver,
{throwOnBadSyncType: true, ...opts, sync: false}
);
}
/**
*
* @param {any} obj
* @param {StateObject|null|undefined} [stateObj]
* @param {TypesonOptions} [opts]
* @returns {string[]|false}
*/
specialTypeNames (obj, stateObj, opts = {}) {
opts.returnTypeNames = true;
return /** @type {string[]|false} */ (
this.encapsulate(obj, stateObj, opts)
);
}
/**
*
* @param {any} obj
* @param {StateObject|null|undefined} [stateObj]
* @param {TypesonOptions} [opts]
* @returns {Promise<ObjectTypeString|string>|ObjectTypeString|string}
*/
rootTypeName (obj, stateObj, opts = {}) {
opts.iterateNone = true;
return (
/**
* @type {Promise<ObjectTypeString|string>|
* ObjectTypeString|string}
*/
(this.encapsulate(obj, stateObj, opts))
);
}
/**
* Encapsulate a complex object into a plain Object by replacing
* registered types with plain objects representing the types data.
*
* This method is used internally by `Typeson.stringify()`.
* @param {any} obj - Object to encapsulate.
* @param {StateObject|null|undefined} [stateObj]
* @param {TypesonOptions} [options]
* @returns {Promise<any>|
* {[key: (string|Integer)]: any}|any|
* ObjectTypeString|string|string[]|
* false
* } The ObjectTypeString, string and string[] should only be returned
* for `specialTypeNames` and `rootTypeName` calls, not direct use of
* this function.
*/
encapsulate (obj, stateObj, options) {
const opts = {sync: true, ...this.options, ...options};
const {sync} = opts;
/**
* @type {{
* [key: string]: '#'|string|string[]
* }}
*/
const types = {},
/** @type {object[]} */
refObjs = [], // For checking cyclic references
/** @type {string[]} */
refKeys = [], // For checking cyclic references
/** @type {PromisesData} */
promisesDataRoot = [];
// Clone the object deeply while at the same time replacing any
// special types or cyclic reference:
const cyclic = 'cyclic' in opts ? opts.cyclic : true;
const {encapsulateObserver} = opts;
/**
*
* @param {any} _ret
* @returns {{[key: (string|Integer)]: any}|string|string[]|
* ObjectTypeString|any|false}
*/
const finish = (_ret) => {
// Add `$types` to result only if we ever bumped into a
// special type (or special case where object has own `$types`)
const typeNames = Object.values(types);
if (opts.iterateNone) {
if (typeNames.length) {
return typeNames[0];
}
return getJSONType(_ret);
}
if (typeNames.length) {
if (opts.returnTypeNames) {
return [...new Set(typeNames)];
}
// Special if array (or a primitive) was serialized
// because JSON would ignore custom `$types` prop on it
if (!_ret || !isPlainObject(_ret) ||
// Also need to handle if this is an object with its
// own `$types` property (to avoid ambiguity)
hasOwn(_ret, '$types')
) {
_ret = {$: _ret, $types: {$: types}};
} else {
_ret.$types = types;
}
// No special types
} else if (isObject(_ret) && hasOwn(_ret, '$types')) {
_ret = {$: _ret, $types: true};
}
if (opts.returnTypeNames) {
return false;
}
return _ret;
};
/**
*
* @param {any} _ret
* @param {PromisesData} promisesData
* @returns {Promise<any>}
*/
const checkPromises = async (_ret, promisesData) => {
const promResults = await Promise.all(
promisesData.map((pd) => {
return /** @type {TypesonPromise<any>} */ (pd[1]).p;
})
);
await Promise.all(
promResults.map(async function (promResult) {
/** @type {PromisesData} */
const newPromisesData = [];
const [prData] = promisesData.splice(0, 1);
const [
keyPath, , _cyclic, _stateObj,
parentObj, key, detectedType
] = prData;
const encaps = _encapsulate(
keyPath, promResult, _cyclic, _stateObj,
newPromisesData, true, detectedType
);
const isTypesonPromise = hasConstructorOf(
encaps,
TypesonPromise
);
// Handle case where an embedded custom type itself
// returns a `TypesonPromise`
if (keyPath && isTypesonPromise) {
const encaps2 = await encaps.p;
// Undefined parent only for root which has no `keyPath`
// eslint-disable-next-line @stylistic/max-len -- Long
/** @type {{[key: (string|number)]: any}} */ (parentObj)[
/** @type {string|number} */ (key)
] = encaps2;
return checkPromises(_ret, newPromisesData);
}
if (keyPath) {
// Undefined parent only for root which has no `keyPath`
// eslint-disable-next-line @stylistic/max-len -- Long
/** @type {{[key: (string|number)]: any}} */ (parentObj)[
/** @type {string|number} */ (key)
] = encaps;
} else if (isTypesonPromise) {
_ret = encaps.p;
} else {
// If this is itself a `TypesonPromise` (because the
// original value supplied was a `Promise` or
// because the supplied custom type value resolved
// to one), returning it below will be fine since
// a `Promise` is expected anyways given current
// config (and if not a `Promise`, it will be ready
// as the resolve value)
_ret = encaps;
}
return checkPromises(_ret, newPromisesData);
})
);
return _ret;
};
/**
* @typedef {object} OwnKeysObject
* @property {boolean} ownKeys
*/
/**
* @callback BuiltinStateObjectPropertiesCallback
* @returns {void}
*/
/**
*
* @param {StateObject} _stateObj
* @param {OwnKeysObject} ownKeysObj
* @param {BuiltinStateObjectPropertiesCallback} cb
* @returns {void}
*/
const _adaptBuiltinStateObjectProperties = (
_stateObj, ownKeysObj, cb
) => {
Object.assign(_stateObj, ownKeysObj);
const vals = internalStateObjPropsToIgnore.map((prop) => {
const tmp = _stateObj[prop];
delete _stateObj[prop];
return tmp;
});
cb();
internalStateObjPropsToIgnore.forEach((prop, i) => {
// We're just copying from one StateObject to another,
// so force TS with a type each can take
_stateObj[prop] = /** @type {any} */ (vals[i]);
});
};
/**
*
* @param {string} keypath
* @param {any} value
* @param {boolean|undefined|"readonly"} _cyclic
* @param {StateObject} _stateObj
* @param {PromisesData} promisesData
* @param {?boolean} [resolvingTypesonPromise]
* @param {string} [detectedType]
* @returns {any}
*/
const _encapsulate = (
keypath, value, _cyclic, _stateObj, promisesData,
resolvingTypesonPromise, detectedType
) => {
let _ret;
/**
* @type {{}|{
* replaced: any
* }|{
* clone: {[key: string]: any}
* }}
*/
let observerData = {};
const $typeof = typeof value;
const runObserver = encapsulateObserver
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line @stylistic/operator-linebreak -- Needs JSDoc
?
// Bug with TS apparently as can't just use
// `@type {Observer}` here as doesn't see param is optional
/**
* @param {KeyPathEvent|EndIterateInEvent|EndIterateOwnEvent|
* EndIterateUnsetNumericEvent|
* TypeDetectedEvent|ReplacingEvent} [_obj]
* @returns {void}
*/
function (_obj) {
const type = detectedType ?? _stateObj.type ?? (
getJSONType(value)
);
encapsulateObserver(Object.assign(_obj ?? observerData, {
keypath,
value,
cyclic: _cyclic,
stateObj: _stateObj,
promisesData,
resolvingTypesonPromise,
awaitingTypesonPromise: hasConstructorOf(
value,
TypesonPromise
)
}, {type}));
}
: null;
if (['string', 'boolean', 'number', 'undefined'].includes(
$typeof
)) {
if (value === undefined ||
(
// Numbers that are not supported in JSON
Number.isNaN(value) ||
value === Number.NEGATIVE_INFINITY ||
value === Number.POSITIVE_INFINITY ||
// This can be 0 or -0
value === 0
)
) {
_ret = _stateObj.replaced
? value
: replace(
keypath, value, _stateObj, promisesData,
false, resolvingTypesonPromise, runObserver
);
if (_ret !== value) {
observerData = {replaced: _ret};
}
} else {
_ret = value;
}
if (runObserver) {
runObserver();
}
return _ret;
}
if (value === null) {
if (runObserver) {
runObserver();
}
return value;
}
if (_cyclic && !_stateObj.iterateIn &&
!_stateObj.iterateUnsetNumeric && value &&
typeof value === 'object'
) {
// Options set to detect cyclic references and be able
// to rewrite them.
const refIndex = refObjs.indexOf(value);
if (refIndex < 0) {
if (_cyclic === true) {
refObjs.push(value);
refKeys.push(keypath);
}
} else {
types[keypath] = '#';
if (runObserver) {
runObserver({
cyclicKeypath: refKeys[refIndex]
});
}
return '#' + refKeys[refIndex];
}
}
const isPlainObj = isPlainObject(value);
const isArr = isArray(value);
const replaced = (
// Running replace will cause infinite loop as will test
// positive again
((isPlainObj || isArr) &&
(!this.plainObjectReplacers.length ||
_stateObj.replaced)
) ||
_stateObj.iterateIn
)
// Optimization: if plain object and no plain-object
// replacers, don't try finding a replacer
? value
: replace(
keypath, value, _stateObj, promisesData,
isPlainObj || isArr,
null,
runObserver
);
/** @type {undefined|Array<any>|{[key: string]: any}} */
let clone;
if (replaced !== value) {
_ret = replaced;
observerData = {replaced};
} else {
// eslint-disable-next-line no-lonely-if -- Clearer
if (keypath === '' &&
hasConstructorOf(value, TypesonPromise)
) {
promisesData.push([
keypath, value, _cyclic, _stateObj,
undefined, undefined, _stateObj.type
]);
_ret = value;
} else if ((isArr && _stateObj.iterateIn !== 'object') ||
_stateObj.iterateIn === 'array'
) {
// eslint-disable-next-line unicorn/no-new-array -- Sparse
clone = new Array(value.length);
observerData = {clone};
} else if (
(
!['function', 'symbol'].includes(typeof value) &&
!('toJSON' in value) &&
!hasConstructorOf(value, TypesonPromise) &&
!hasConstructorOf(value, Promise) &&
!hasConstructorOf(value, ArrayBuffer)
) ||
isPlainObj ||
_stateObj.iterateIn === 'object'
) {
clone = {};
if (_stateObj.addLength) {
clone.length = value.length;
}
observerData = {clone};
} else {
_ret = value; // Only clone vanilla objects and arrays
}
}
if (runObserver) {
runObserver();
}
if (opts.iterateNone) {
return clone ?? _ret;
}
if (!clone) {
return _ret;
}
// Iterate object or array
if (_stateObj.iterateIn) {
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line guard-for-in -- Guard not wanted here
for (const key in value) {
const ownKeysObj = {ownKeys: hasOwn(value, key)};
_adaptBuiltinStateObjectProperties(
_stateObj,
ownKeysObj,
() => {
const kp = keypath + (keypath ? '.' : '') +
escapeKeyPathComponent(key);
const val = _encapsulate(
kp, value[key], Boolean(_cyclic), _stateObj,
promisesData, resolvingTypesonPromise
);
if (hasConstructorOf(val, TypesonPromise)) {
promisesData.push([
kp, val, Boolean(_cyclic), _stateObj,
clone, key, _stateObj.type
]);
} else if (val !== undefined) {
/** @type {{[key: (string|Integer)]: any}} */ (
clone
)[key] = val;
}
}
);
}
if (runObserver) {
runObserver({endIterateIn: true, end: true});
}
} else {
// Note: Non-indexes on arrays won't survive stringify so
// somewhat wasteful for arrays, but so too is iterating
// all numeric indexes on sparse arrays when not wanted
// or filtering own keys for positive integers
keys(value).forEach(function (key) {
const kp = keypath + (keypath ? '.' : '') +
escapeKeyPathComponent(key);
const ownKeysObj = {ownKeys: true};
_adaptBuiltinStateObjectProperties(
_stateObj,
ownKeysObj,
() => {
const val = _encapsulate(
kp, value[key], Boolean(_cyclic), _stateObj,
promisesData, resolvingTypesonPromise
);
if (hasConstructorOf(val, TypesonPromise)) {
promisesData.push([
kp, val, Boolean(_cyclic), _stateObj,
clone, key, _stateObj.type
]);
} else if (val !== undefined) {
/** @type {{[key: string]: any}} */ (
clone
)[key] = val;
}
}
);
});
if (runObserver) {
runObserver({endIterateOwn: true, end: true});
}
}
// Iterate array for non-own numeric properties (we can't
// replace the prior loop though as it iterates non-integer
// keys)
if (_stateObj.iterateUnsetNumeric) {
const vl = value.length;
for (let i = 0; i < vl; i++) {
if (!(i in value)) {
// No need to escape numeric
const kp = `${keypath}${keypath ? '.' : ''}${
String(i)
}`;
const ownKeysObj = {ownKeys: false};
_adaptBuiltinStateObjectProperties(
_stateObj,
ownKeysObj,
() => {
const val = _encapsulate(
kp, undefined, Boolean(_cyclic), _stateObj,
promisesData, resolvingTypesonPromise
);
if (hasConstructorOf(val, TypesonPromise)) {
promisesData.push([
kp, val, Boolean(_cyclic), _stateObj,
clone, i, _stateObj.type
]);
} else if (val !== undefined) {
/** @type {{[key: Integer]: any}} */
(clone)[i] = val;
}
}
);
}
}
if (runObserver) {
runObserver({endIterateUnsetNumeric: true, end: true});
}
}
return clone;
};
/**
*
* @param {string} keypath
* @param {any} value
* @param {StateObject} _stateObj
* @param {PromisesData} promisesData
* @param {boolean} plainObject
* @param {?boolean} [resolvingTypesonPromise]
* @param {Observer|null} [runObserver]
* @throws {Error}
* @returns {any}
*/
const replace = (
keypath, value, _stateObj, promisesData, plainObject,
resolvingTypesonPromise, runObserver
) => {
// Encapsulate registered types
const replacers = plainObject
? this.plainObjectReplacers
: this.nonplainObjectReplacers;
let i = replacers.length;
while (i--) {
const replacer = replacers[i];
if (replacer.test(value, _stateObj)) {
const {type} = replacer;
if (this.revivers[type]) {
// Record the type only if a corresponding reviver
// exists. This is to support specs where only
// replacement is done.
// For example, ensuring deep cloning of the object,
// or replacing a type to its equivalent without
// the need to revive it.
const existing = types[keypath];
// type can comprise an array of types (see test
// "should support intermediate types")
types[keypath] = existing
? [type].concat(existing)
: type;
}
Object.assign(_stateObj, {type, replaced: true});
if ((sync || !replacer.replaceAsync) &&
!replacer.replace
) {
if (runObserver) {
runObserver({typeDetected: true});
}
return _encapsulate(
keypath, value, cyclic && 'readonly',
_stateObj, promisesData,
resolvingTypesonPromise, type
);
}
if (runObserver) {
runObserver({replacing: true});
}
// Now, also traverse the result in case it contains its
// own types to replace
let replaced;
if (sync || !replacer.replaceAsync) {
// Shouldn't reach here due to above condition
/* c8 ignore next 3 */
if (typeof replacer.replace === 'undefined') {
throw new TypeError('Missing replacer');
}
replaced = replacer.replace(value, _stateObj);
} else {
replaced = replacer.replaceAsync(value, _stateObj);
}
return _encapsulate(
keypath,