Rich-Harris/devalue

don't throw an error on invalid dates when using `stringify`

ivanhofer opened this issue · 1 comments

When it comes to invalid date objects e.g. when using new Date() with an invalid date string, the stringify function throws an error.

See the example here:
https://svelte.dev/repl/db77cddd51d84149b7ddb9ce29a87ec0?version=3.49.0

But the same input does not throw an error when using the uneval function.
I guess it makes sense to have a consistent behavior there.

A solution to this problem could look like this:

// https://github.com/Rich-Harris/devalue/blob/master/src/stringify.js#L68
case 'Date':
	const isValidDate = !isNaN(thing.getDate())
	str = `["Date","${isValidDate ? thing.toISOString() : ''}"]`;
	break;

This gets rid of the error and when using parse you'll get back an invalid date.

What do you think?
I can submit PR if you want.

Just ran into this with Superforms as well. You get an invalid date object sent to the server, but cannot return it back to the client since then it will throw an error as above.