Skip to content

Commit b11d1d9

Browse files
dahliabartlomieju
andauthored
fix: handle invalid date objects in jsonify stringify (#2851)
## Summary - Handles the case when `Date.toISOString()` throws for invalid dates by catching the error and serializing as `"Invalid Date"` - Round-trips correctly: `new Date("Invalid Date")` serializes to `["Date","Invalid Date"]` and deserializes back to an invalid `Date` object - Adds test case and snapshot for invalid `Date` Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
1 parent 61eb5f6 commit b11d1d9

3 files changed

Lines changed: 10 additions & 1 deletion

File tree

packages/fresh/src/jsonify/__snapshots__/round_trip_test.ts.snap

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ snapshot[`round trip - URL {\\n href: 'https://fresh.deno.dev/',\\n origin: 'h
4444

4545
snapshot[`round trip - 1990-05-31T00:00:00.000Z 1`] = `'[["Date","1990-05-31T00:00:00.000Z"]]'`;
4646

47+
snapshot[`round trip - Invalid Date 1`] = `'[["Date","Invalid Date"]]'`;
48+
4749
snapshot[`round trip - Map(2) { 1 => null, undefined => -2 } 1`] = `'[["Map",[1,-2,-1,2]],1,-2]'`;
4850

4951
snapshot[`round trip - Set(5) { 1, 2, null, -2, NaN } 1`] = `'[["Set",[1,2,-2,3,-3]],1,2,-2]'`;

packages/fresh/src/jsonify/round_trip_test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ const TESTS = [
3434
new Uint8Array([1, 2, 3]),
3535
new URL("https://fresh.deno.dev"),
3636
new Date("1990-05-31"),
37+
new Date("Invalid Date"),
3738
new Map([[1, null], [undefined, -2]]),
3839
new Set([1, 2, null, -2, NaN]),
3940
[1, , 3],

packages/fresh/src/jsonify/stringify.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,13 @@ function serializeInner(
108108
if (value instanceof URL) {
109109
str += `["URL","${value.href}"]`;
110110
} else if (value instanceof Date) {
111-
str += `["Date","${value.toISOString()}"]`;
111+
let iso: string;
112+
try {
113+
iso = value.toISOString();
114+
} catch {
115+
iso = "Invalid Date";
116+
}
117+
str += `["Date","${iso}"]`;
112118
} else if (value instanceof RegExp) {
113119
str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`;
114120
} else if (value instanceof Uint8Array) {

0 commit comments

Comments
 (0)