From 194e00215b2d3c2ba49acae0b3066535ac741ebe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E0=A4=95=E0=A4=BE=E0=A4=B0=E0=A4=A4=E0=A5=8B=E0=A4=AB?= =?UTF-8?q?=E0=A5=8D=E0=A4=AB=E0=A5=87=E0=A4=B2=E0=A4=B8=E0=A5=8D=E0=A4=95?= =?UTF-8?q?=E0=A5=8D=E0=A4=B0=E0=A4=BF=E0=A4=AA=E0=A5=8D=E0=A4=9F=E2=84=A2?= Date: Wed, 29 Mar 2023 14:29:26 +0200 Subject: [PATCH] fix(core): Handle Date and RegExp correctly in jsonStringify --- packages/workflow/src/utils.ts | 19 +++++++++---------- packages/workflow/test/utils.test.ts | 4 ++-- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/packages/workflow/src/utils.ts b/packages/workflow/src/utils.ts index b1ada63be1f68..71d4a50028a35 100644 --- a/packages/workflow/src/utils.ts +++ b/packages/workflow/src/utils.ts @@ -67,17 +67,16 @@ type JSONStringifyOptions = { }; const replaceCircularReferences = (value: T, knownObjects = new WeakSet()): T => { - if (value && typeof value === 'object') { - if (knownObjects.has(value)) return '[Circular Reference]' as T; - knownObjects.add(value); - const copy = (Array.isArray(value) ? [] : {}) as T; - for (const key in value) { - copy[key] = replaceCircularReferences(value[key], knownObjects); - } - knownObjects.delete(value); - return copy; + if (typeof value !== 'object' || value === null || value instanceof RegExp) return value; + if ('toJSON' in value && typeof value.toJSON === 'function') return value.toJSON() as T; + if (knownObjects.has(value)) return '[Circular Reference]' as T; + knownObjects.add(value); + const copy = (Array.isArray(value) ? [] : {}) as T; + for (const key in value) { + copy[key] = replaceCircularReferences(value[key], knownObjects); } - return value; + knownObjects.delete(value); + return copy; }; export const jsonStringify = (obj: unknown, options: JSONStringifyOptions = {}): string => { diff --git a/packages/workflow/test/utils.test.ts b/packages/workflow/test/utils.test.ts index fb944ec62ab61..268f270e02624 100644 --- a/packages/workflow/test/utils.test.ts +++ b/packages/workflow/test/utils.test.ts @@ -18,7 +18,7 @@ describe('jsonParse', () => { }); describe('jsonStringify', () => { - const source: any = { a: 1, b: 2 }; + const source: any = { a: 1, b: 2, d: new Date(1680089084200), r: new RegExp('^test$', 'ig') }; source.c = source; it('should throw errors on circular references by default', () => { @@ -27,7 +27,7 @@ describe('jsonStringify', () => { it('should break circular references when requested', () => { expect(jsonStringify(source, { replaceCircularRefs: true })).toEqual( - '{"a":1,"b":2,"c":"[Circular Reference]"}', + '{"a":1,"b":2,"d":"2023-03-29T11:24:44.200Z","r":{},"c":"[Circular Reference]"}', ); });