-
Notifications
You must be signed in to change notification settings - Fork 181
/
serialize.js
589 lines (495 loc) · 23.1 KB
/
serialize.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
/* global describe, it, beforeEach */
'use strict';
// temporarily monkeypatch `crypto.randomBytes` so we'll have a
// predictable UID for our tests
var crypto = require('crypto');
var oldRandom = crypto.randomBytes;
crypto.randomBytes = function(len, cb) {
var buf = Buffer.alloc(len);
buf.fill(0x00);
if (cb)
cb(null, buf);
return buf;
};
var serialize = require('../../'),
expect = require('chai').expect;
crypto.randomBytes = oldRandom;
describe('serialize( obj )', function () {
it('should be a function', function () {
expect(serialize).to.be.a('function');
});
describe('undefined', function () {
it('should serialize `undefined` to a string', function () {
expect(serialize()).to.be.a('string').equal('undefined');
expect(serialize(undefined)).to.be.a('string').equal('undefined');
});
it('should deserialize "undefined" to `undefined`', function () {
expect(eval(serialize())).to.equal(undefined);
expect(eval(serialize(undefined))).to.equal(undefined);
});
});
describe('null', function () {
it('should serialize `null` to a string', function () {
expect(serialize(null)).to.be.a('string').equal('null');
});
it('should deserialize "null" to `null`', function () {
expect(eval(serialize(null))).to.equal(null);
});
});
describe('JSON', function () {
var data;
beforeEach(function () {
data = {
str : 'string',
num : 0,
obj : {foo: 'foo'},
arr : [1, 2, 3],
bool: true,
nil : null
};
});
it('should serialize JSON to a JSON string', function () {
expect(serialize(data)).to.equal(JSON.stringify(data));
});
it('should deserialize a JSON string to a JSON object', function () {
expect(JSON.parse(serialize(data))).to.deep.equal(data);
});
it('should serialize weird whitespace characters correctly', function () {
var ws = String.fromCharCode(8232);
expect(eval(serialize(ws))).to.equal(ws);
});
it('should serialize undefined correctly', function () {
var obj;
var str = '{"undef":undefined,"nest":{"undef":undefined}}';
eval('obj = ' + str);
expect(serialize(obj)).to.equal(str);
});
});
describe('functions', function () {
it('should serialize annonymous functions', function () {
var fn = function () {};
expect(serialize(fn)).to.be.a('string').equal('function () {}');
});
it('should deserialize annonymous functions', function () {
var fn; eval('fn = ' + serialize(function () {}));
expect(fn).to.be.a('function');
});
it('should serialize named functions', function () {
function fn() {}
expect(serialize(fn)).to.be.a('string').equal('function fn() {}');
});
it('should deserialize named functions', function () {
var fn; eval('fn = ' + serialize(function fn() {}));
expect(fn).to.be.a('function');
expect(fn.name).to.equal('fn');
});
it('should serialize functions with arguments', function () {
function fn(arg1, arg2) {}
expect(serialize(fn)).to.equal('function fn(arg1, arg2) {}');
});
it('should deserialize functions with arguments', function () {
var fn; eval('fn = ' + serialize(function (arg1, arg2) {}));
expect(fn).to.be.a('function');
expect(fn.length).to.equal(2);
});
it('should serialize functions with bodies', function () {
function fn() { return true; }
expect(serialize(fn)).to.equal('function fn() { return true; }');
});
it('should deserialize functions with bodies', function () {
var fn; eval('fn = ' + serialize(function () { return true; }));
expect(fn).to.be.a('function');
expect(fn()).to.equal(true);
});
it('should throw a TypeError when serializing native built-ins', function () {
var err;
expect(Number.toString()).to.equal('function Number() { [native code] }');
try { serialize(Number); } catch (e) { err = e; }
expect(err).to.be.an.instanceOf(TypeError);
});
it('should serialize enhanced literal objects', function () {
var obj = {
foo() { return true; },
*bar() { return true; }
};
expect(serialize(obj)).to.equal('{"foo":function() { return true; },"bar":function*() { return true; }}');
});
it('should deserialize enhanced literal objects', function () {
var obj;
eval('obj = ' + serialize({ hello() { return true; } }));
expect(obj.hello()).to.equal(true);
});
it('should serialize functions that contain dates', function () {
function fn(arg1) {return new Date('2016-04-28T22:02:17.156Z')};
expect(serialize(fn)).to.be.a('string').equal('function fn(arg1) {return new Date(\'2016-04-28T22:02:17.156Z\')}');
});
it('should deserialize functions that contain dates', function () {
var fn; eval('fn = ' + serialize(function () { return new Date('2016-04-28T22:02:17.156Z') }));
expect(fn).to.be.a('function');
expect(fn().getTime()).to.equal(new Date('2016-04-28T22:02:17.156Z').getTime());
});
it('should serialize functions that return other functions', function () {
function fn() {return function(arg1) {return arg1 + 5}};
expect(serialize(fn)).to.be.a('string').equal('function fn() {return function(arg1) {return arg1 + 5}}');
});
it('should deserialize functions that return other functions', function () {
var fn; eval('fn = ' + serialize(function () { return function(arg1) {return arg1 + 5} }));
expect(fn).to.be.a('function');
expect(fn()(7)).to.equal(12);
});
});
describe('arrow-functions', function () {
it('should serialize arrow functions', function () {
var fn = () => {};
expect(serialize(fn)).to.be.a('string').equal('() => {}');
});
it('should deserialize arrow functions', function () {
var fn; eval('fn = ' + serialize(() => true));
expect(fn).to.be.a('function');
expect(fn()).to.equal(true);
});
it('should serialize arrow functions with one argument', function () {
var fn = arg1 => {}
expect(serialize(fn)).to.be.a('string').equal('arg1 => {}');
});
it('should deserialize arrow functions with one argument', function () {
var fn; eval('fn = ' + serialize(arg1 => {}));
expect(fn).to.be.a('function');
expect(fn.length).to.equal(1);
});
it('should serialize arrow functions with multiple arguments', function () {
var fn = (arg1, arg2) => {}
expect(serialize(fn)).to.equal('(arg1, arg2) => {}');
});
it('should deserialize arrow functions with multiple arguments', function () {
var fn; eval('fn = ' + serialize( (arg1, arg2) => {}));
expect(fn).to.be.a('function');
expect(fn.length).to.equal(2);
});
it('should serialize arrow functions with bodies', function () {
var fn = () => { return true; }
expect(serialize(fn)).to.equal('() => { return true; }');
});
it('should deserialize arrow functions with bodies', function () {
var fn; eval('fn = ' + serialize( () => { return true; }));
expect(fn).to.be.a('function');
expect(fn()).to.equal(true);
});
it('should serialize enhanced literal objects', function () {
var obj = {
foo: () => { return true; },
bar: arg1 => { return true; },
baz: (arg1, arg2) => { return true; }
};
expect(serialize(obj)).to.equal('{"foo":() => { return true; },"bar":arg1 => { return true; },"baz":(arg1, arg2) => { return true; }}');
});
it('should deserialize enhanced literal objects', function () {
var obj;
eval('obj = ' + serialize({ foo: () => { return true; },
foo: () => { return true; },
bar: arg1 => { return true; },
baz: (arg1, arg2) => { return true; }
}));
expect(obj.foo()).to.equal(true);
expect(obj.bar('arg1')).to.equal(true);
expect(obj.baz('arg1', 'arg1')).to.equal(true);
});
it('should serialize arrow functions with added properties', function () {
var fn = () => {};
fn.property1 = 'a string'
expect(serialize(fn)).to.be.a('string').equal('() => {}');
});
it('should deserialize arrow functions with added properties', function () {
var fn; eval('fn = ' + serialize( () => { this.property1 = 'a string'; return 5 }));
expect(fn).to.be.a('function');
expect(fn()).to.equal(5);
});
it('should serialize arrow functions that return other functions', function () {
var fn = arg1 => { return arg2 => arg1 + arg2 };
expect(serialize(fn)).to.be.a('string').equal('arg1 => { return arg2 => arg1 + arg2 }');
});
it('should deserialize arrow functions that return other functions', function () {
var fn; eval('fn = ' + serialize(arg1 => { return arg2 => arg1 + arg2 } ));
expect(fn).to.be.a('function');
expect(fn(2)(3)).to.equal(5);
});
});
describe('regexps', function () {
it('should serialize constructed regexps', function () {
var re = new RegExp('asdf');
expect(serialize(re)).to.be.a('string').equal('new RegExp("asdf", "")');
});
it('should deserialize constructed regexps', function () {
var re = eval(serialize(new RegExp('asdf')));
expect(re).to.be.a('RegExp');
expect(re.source).to.equal('asdf');
});
it('should serialize literal regexps', function () {
var re = /asdf/;
expect(serialize(re)).to.be.a('string').equal('new RegExp("asdf", "")');
});
it('should deserialize literal regexps', function () {
var re = eval(serialize(/asdf/));
expect(re).to.be.a('RegExp');
expect(re.source).to.equal('asdf');
});
it('should serialize regexps with flags', function () {
var re = /^asdf$/gi;
expect(serialize(re)).to.equal('new RegExp("^asdf$", "gi")');
});
it('should deserialize regexps with flags', function () {
var re = eval(serialize(/^asdf$/gi));
expect(re).to.be.a('RegExp');
expect(re.global).to.equal(true);
expect(re.ignoreCase).to.equal(true);
expect(re.multiline).to.equal(false);
});
it('should serialize regexps with escaped chars', function () {
expect(serialize(/\..*/)).to.equal('new RegExp("\\\\..*", "")');
expect(serialize(new RegExp('\\..*'))).to.equal('new RegExp("\\\\..*", "")');
});
it('should deserialize regexps with escaped chars', function () {
var re = eval(serialize(/\..*/));
expect(re).to.be.a('RegExp');
expect(re.source).to.equal('\\..*');
re = eval(serialize(new RegExp('\\..*')));
expect(re).to.be.a('RegExp');
expect(re.source).to.equal('\\..*');
});
it('should serialize dangerous regexps', function () {
var re = /[<\/script><script>alert('xss')\/\/]/
expect(serialize(re)).to.be.a('string').equal('new RegExp("[\\u003C\\\\\\u002Fscript\\u003E\\u003Cscript\\u003Ealert(\'xss\')\\\\\\u002F\\\\\\u002F]", "")');
});
});
describe('dates', function () {
it('should serialize dates', function () {
var d = new Date('2016-04-28T22:02:17.156Z');
expect(serialize(d)).to.be.a('string').equal('new Date("2016-04-28T22:02:17.156Z")');
expect(serialize({t: [d]})).to.be.a('string').equal('{"t":[new Date("2016-04-28T22:02:17.156Z")]}');
});
it('should deserialize a date', function () {
var d = eval(serialize(new Date('2016-04-28T22:02:17.156Z')));
expect(d).to.be.a('Date');
expect(d.toISOString()).to.equal('2016-04-28T22:02:17.156Z');
});
it('should deserialize a string that is not a valid date', function () {
var d = eval(serialize('2016-04-28T25:02:17.156Z'));
expect(d).to.be.a('string');
expect(d).to.equal('2016-04-28T25:02:17.156Z');
});
it('should serialize dates within objects', function () {
var d = {foo: new Date('2016-04-28T22:02:17.156Z')};
expect(serialize(d)).to.be.a('string').equal('{"foo":new Date("2016-04-28T22:02:17.156Z")}');
expect(serialize({t: [d]})).to.be.a('string').equal('{"t":[{"foo":new Date("2016-04-28T22:02:17.156Z")}]}');
});
});
describe('maps', function () {
it('should serialize maps', function () {
var regexKey = /.*/;
var m = new Map([
['a', 123],
[regexKey, 456],
[Infinity, 789]
]);
expect(serialize(m)).to.be.a('string').equal('new Map([["a",123],[new RegExp(".*", ""),456],[Infinity,789]])');
expect(serialize({t: [m]})).to.be.a('string').equal('{"t":[new Map([["a",123],[new RegExp(".*", ""),456],[Infinity,789]])]}');
});
it('should deserialize a map', function () {
var m = eval(serialize(new Map([
['a', 123],
[null, 456],
[Infinity, 789]
])));
expect(m).to.be.a('Map');
expect(m.get(null)).to.equal(456);
});
});
describe('sets', function () {
it('should serialize sets', function () {
var regex = /.*/;
var m = new Set([
'a',
123,
regex,
Infinity
]);
expect(serialize(m)).to.be.a('string').equal('new Set(["a",123,new RegExp(".*", ""),Infinity])');
expect(serialize({t: [m]})).to.be.a('string').equal('{"t":[new Set(["a",123,new RegExp(".*", ""),Infinity])]}');
});
it('should deserialize a set', function () {
var m = eval(serialize(new Set([
'a',
123,
null,
Infinity
])));
expect(m).to.be.a('Set');
expect(m.has(null)).to.equal(true);
});
});
describe('sparse arrays', function () {
it('should serialize sparse arrays', function () {
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
delete a[0];
a.length = 3;
a[5] = "wat"
expect(serialize(a)).to.be.a('string').equal('Array.prototype.slice.call({"1":2,"2":3,"5":"wat","length":6})');
expect(serialize({t: [a]})).to.be.a('string').equal('{"t":[Array.prototype.slice.call({"1":2,"2":3,"5":"wat","length":6})]}');
});
it('should deserialize a sparse array', function () {
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
delete a[0];
a.length = 3;
a[5] = "wat"
var b = eval(serialize(a));
expect(b).to.be.a('Array').deep.equal([ , 2, 3, , , 'wat' ]);
});
});
describe('Infinity', function () {
it('should serialize Infinity', function () {
expect(serialize(Infinity)).to.equal('Infinity');
expect(serialize({t: [Infinity]})).to.be.a('string').equal('{"t":[Infinity]}');
});
it('should deserialize Infinity', function () {
var d = eval(serialize(Infinity));
expect(d).to.equal(Infinity);
});
it('should serialize -Infinity', function () {
expect(serialize(-Infinity)).to.equal('-Infinity');
expect(serialize({t: [-Infinity]})).to.be.a('string').equal('{"t":[-Infinity]}');
});
it('should deserialize -Infinity', function () {
var d = eval(serialize(-Infinity));
expect(d).to.equal(-Infinity);
});
});
describe('BigInt', function () {
it('should serialize BigInt', function () {
var b = BigInt(9999);
expect(serialize(b)).to.equal('BigInt("9999")');
expect(serialize({t: [b]})).to.be.a('string').equal('{"t":[BigInt("9999")]}');
});
it('should deserialize BigInt', function () {
var d = eval(serialize(BigInt(9999)));
expect(d).to.be.a('BigInt');
expect(d.toString()).to.equal('9999');
});
it('should throw error for invalid bigint', function () {
expect(() => serialize(BigInt('abc'))).to.throw(Error);
});
});
describe('URL', function () {
it('should serialize URL', function () {
var u = new URL('https://x.com/')
expect(serialize(u)).to.equal('new URL("https://x.com/")');
expect(serialize({t: [u]})).to.be.a('string').equal('{"t":[new URL("https://x.com/")]}');
});
it('should deserialize URL', function () {
var d = eval(serialize(new URL('https://x.com/')));
expect(d).to.be.a('URL');
expect(d.toString()).to.equal('https://x.com/');
});
});
describe('Error', function () {
it('should serialize Error', function () {
var e = new Error('Error message.')
expect(serialize(e)).to.equal('new Error("Error message.")');
expect(serialize({t: [e]})).to.be.a('string').equal('{"t":[new Error("Error message.")]}');
});
it('should deserialize Error', function () {
var d = eval(serialize(new Error('Error message.')));
expect(d).to.be.a('Error');
expect(d.message).to.equal('Error message.');
});
});
describe('XSS', function () {
it('should encode unsafe HTML chars to Unicode', function () {
expect(serialize('</script>')).to.equal('"\\u003C\\u002Fscript\\u003E"');
expect(JSON.parse(serialize('</script>'))).to.equal('</script>');
expect(eval(serialize('</script>'))).to.equal('</script>');
});
});
describe('options', function () {
it('should accept options as the second argument', function () {
expect(serialize('foo', {})).to.equal('"foo"');
});
it('should accept a `space` option', function () {
expect(serialize([1], {space: 0})).to.equal('[1]');
expect(serialize([1], {space: ''})).to.equal('[1]');
expect(serialize([1], {space: undefined})).to.equal('[1]');
expect(serialize([1], {space: null})).to.equal('[1]');
expect(serialize([1], {space: false})).to.equal('[1]');
expect(serialize([1], {space: 1})).to.equal('[\n 1\n]');
expect(serialize([1], {space: ' '})).to.equal('[\n 1\n]');
expect(serialize([1], {space: 2})).to.equal('[\n 1\n]');
});
it('should accept a `isJSON` option', function () {
expect(serialize('foo', {isJSON: true})).to.equal('"foo"');
expect(serialize('foo', {isJSON: false})).to.equal('"foo"');
function fn() { return true; }
expect(serialize(fn)).to.equal('function fn() { return true; }');
expect(serialize(fn, {isJSON: false})).to.equal('function fn() { return true; }');
expect(serialize(fn, {isJSON: true})).to.equal('undefined');
expect(serialize([1], {isJSON: true, space: 2})).to.equal('[\n 1\n]');
});
it('should accept a `unsafe` option', function () {
expect(serialize('foo', {unsafe: true})).to.equal('"foo"');
expect(serialize('foo', {unsafe: false})).to.equal('"foo"');
function fn() { return true; }
expect(serialize(fn)).to.equal('function fn() { return true; }');
expect(serialize(fn, {unsafe: false})).to.equal('function fn() { return true; }');
expect(serialize(fn, {unsafe: undefined})).to.equal('function fn() { return true; }');
expect(serialize(fn, {unsafe: "true"})).to.equal('function fn() { return true; }');
expect(serialize(fn, {unsafe: true})).to.equal('function fn() { return true; }');
expect(serialize(["1"], {unsafe: false, space: 2})).to.equal('[\n "1"\n]');
expect(serialize(["1"], {unsafe: true, space: 2})).to.equal('[\n "1"\n]');
expect(serialize(["<"], {space: 2})).to.equal('[\n "\\u003C"\n]');
expect(serialize(["<"], {unsafe: true, space: 2})).to.equal('[\n "<"\n]');
});
it("should accept a `ignoreFunction` option", function() {
function fn() { return true; }
var obj = {
fn: fn,
fn_arrow: () => {
return true;
}
};
var obj2 = {
num: 123,
str: 'str',
fn: fn
}
// case 1. Pass function to serialize
expect(serialize(fn, { ignoreFunction: true })).to.equal('undefined');
// case 2. Pass function(arrow) in object to serialze
expect(serialize(obj, { ignoreFunction: true })).to.equal('{}');
// case 3. Other features should work
expect(serialize(obj2, { ignoreFunction: true })).to.equal(
'{"num":123,"str":"str"}'
);
});
});
describe('backwards-compatability', function () {
it('should accept `space` as the second argument', function () {
expect(serialize([1], 0)).to.equal('[1]');
expect(serialize([1], '')).to.equal('[1]');
expect(serialize([1], undefined)).to.equal('[1]');
expect(serialize([1], null)).to.equal('[1]');
expect(serialize([1], false)).to.equal('[1]');
expect(serialize([1], 1)).to.equal('[\n 1\n]');
expect(serialize([1], ' ')).to.equal('[\n 1\n]');
expect(serialize([1], 2)).to.equal('[\n 1\n]');
});
});
describe('placeholders', function() {
it('should not be replaced within string literals', function () {
// Since we made the UID deterministic this should always be the placeholder
var fakePlaceholder = '"@__R-0000000000000000-0__@';
var serialized = serialize({bar: /1/i, foo: fakePlaceholder}, {uid: 'foo'});
var obj = eval('(' + serialized + ')');
expect(obj).to.be.a('Object');
expect(obj.foo).to.be.a('String');
expect(obj.foo).to.equal(fakePlaceholder);
});
});
});