flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.13k stars 91 forks source link

Fix production problems with `Map` and `Set` #26

Closed Skn0tt closed 4 years ago

Skn0tt commented 4 years ago

Apparently, our code behaves differently in production code than in our tests.

Some snippets that don't work as intended:

SuperJSON.parse(
    SuperJSON.stringify({
        a: new Map([[1, 2]])
    })
)
// yields { a: Map(2) { 'undefined' => undefined, 1 => undefined } }
SuperJSON.stringify({
    a: new Set([])
})
// throws TypeError: Circular Reference
Skn0tt commented 4 years ago

Turns out: TSC compiles [...map.entries()] to [].concat(map.entries()), which is less than equivalent:

> [...map.entries()]
[ [ 1, 2 ] ]
> [].concat(map.entries())
[ [Map Entries] { [ 1, 2 ] } ]
Skn0tt commented 4 years ago

This behaviour is enabled with the downLevelIteration: true compiler flag. Will turn off and adapt our code. PR incoming.