From b11d1d98f2fb61a14ef4fc95d1b7eff45b393d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hong=20Minhee=20=28=E6=B4=AA=20=E6=B0=91=E6=86=99=29?= Date: Thu, 26 Mar 2026 17:31:27 +0900 Subject: [PATCH] fix: handle invalid date objects in jsonify stringify (#2851) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 --- .../src/jsonify/__snapshots__/round_trip_test.ts.snap | 2 ++ packages/fresh/src/jsonify/round_trip_test.ts | 1 + packages/fresh/src/jsonify/stringify.ts | 8 +++++++- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/fresh/src/jsonify/__snapshots__/round_trip_test.ts.snap b/packages/fresh/src/jsonify/__snapshots__/round_trip_test.ts.snap index f7f4f371..ae21ba2a 100644 --- a/packages/fresh/src/jsonify/__snapshots__/round_trip_test.ts.snap +++ b/packages/fresh/src/jsonify/__snapshots__/round_trip_test.ts.snap @@ -44,6 +44,8 @@ snapshot[`round trip - URL {\\n href: 'https://fresh.deno.dev/',\\n origin: 'h snapshot[`round trip - 1990-05-31T00:00:00.000Z 1`] = `'[["Date","1990-05-31T00:00:00.000Z"]]'`; +snapshot[`round trip - Invalid Date 1`] = `'[["Date","Invalid Date"]]'`; + snapshot[`round trip - Map(2) { 1 => null, undefined => -2 } 1`] = `'[["Map",[1,-2,-1,2]],1,-2]'`; snapshot[`round trip - Set(5) { 1, 2, null, -2, NaN } 1`] = `'[["Set",[1,2,-2,3,-3]],1,2,-2]'`; diff --git a/packages/fresh/src/jsonify/round_trip_test.ts b/packages/fresh/src/jsonify/round_trip_test.ts index 83e11108..c44e5f9b 100644 --- a/packages/fresh/src/jsonify/round_trip_test.ts +++ b/packages/fresh/src/jsonify/round_trip_test.ts @@ -34,6 +34,7 @@ const TESTS = [ new Uint8Array([1, 2, 3]), new URL("https://fresh.deno.dev"), new Date("1990-05-31"), + new Date("Invalid Date"), new Map([[1, null], [undefined, -2]]), new Set([1, 2, null, -2, NaN]), [1, , 3], diff --git a/packages/fresh/src/jsonify/stringify.ts b/packages/fresh/src/jsonify/stringify.ts index 1179b5a3..00231115 100644 --- a/packages/fresh/src/jsonify/stringify.ts +++ b/packages/fresh/src/jsonify/stringify.ts @@ -108,7 +108,13 @@ function serializeInner( if (value instanceof URL) { str += `["URL","${value.href}"]`; } else if (value instanceof Date) { - str += `["Date","${value.toISOString()}"]`; + let iso: string; + try { + iso = value.toISOString(); + } catch { + iso = "Invalid Date"; + } + str += `["Date","${iso}"]`; } else if (value instanceof RegExp) { str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`; } else if (value instanceof Uint8Array) {