Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): Handle Date and RegExp correctly in jsonStringify #5812

Merged
merged 2 commits into from
Mar 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions packages/workflow/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,16 @@ type JSONStringifyOptions = {
};

const replaceCircularReferences = <T>(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 => {
Expand Down
4 changes: 2 additions & 2 deletions packages/workflow/test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -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]"}',
);
});

Expand Down