Skip to content

Commit 5cb6df4

Browse files
committed
feat(util): return identical fromSerializableObject if already serialized
Update `fromSerializableObject` function to correctly identify and return native types (like Date, Error, Map, Set, and ArrayBuffer views) without modification.
1 parent e96ddb1 commit 5cb6df4

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

packages/util/src/serializableObject.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@ const hasInnerError = (error: unknown): error is { innerError: unknown } =>
4444
const innerErrorHasData = (innerError: unknown): innerError is { data: unknown } =>
4545
typeof innerError === 'object' && innerError !== null && 'data' in innerError;
4646

47+
const isNativeNonSerializableType = (obj: unknown): boolean => {
48+
if (typeof obj === 'undefined' || typeof obj === 'bigint') return true;
49+
if (typeof obj === 'object' && obj !== null) {
50+
if (obj instanceof Date) return true;
51+
if (obj instanceof Error) return true;
52+
if (obj instanceof Map) return true;
53+
if (obj instanceof Set) return true;
54+
if (ArrayBuffer.isView(obj)) return true;
55+
}
56+
return false;
57+
};
58+
4759
export const toSerializableObject = (obj: unknown, options: ToSerializableObjectOptions = {}): unknown => {
4860
if (PLAIN_TYPES.has(typeof obj)) return obj;
4961
const { transformationTypeKey = defaultTransformationTypeKey, serializeKey = defaultTransformKey } = options;
@@ -110,7 +122,9 @@ export const toSerializableObject = (obj: unknown, options: ToSerializableObject
110122
};
111123

112124
const fromSerializableObjectUnknown = (obj: unknown, options: FromSerializableObjectOptions = {}): unknown => {
113-
if (PLAIN_TYPES.has(typeof obj)) return obj;
125+
if (PLAIN_TYPES.has(typeof obj)) return obj; // no-op for plain types
126+
if (isNativeNonSerializableType(obj)) return obj; // no-op for native types
127+
114128
if (typeof obj === 'object') {
115129
if (obj === null) return null;
116130
if (Array.isArray(obj)) {

packages/util/test/serializableObject.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,5 +111,19 @@ describe('serializableObject', () => {
111111
const obj = [{ a: [{ b: 1, c: '2' }] }, 3];
112112
expect(fromSerializableObject(obj)).toEqual(obj);
113113
});
114+
115+
it('returns the identical object when input is already serialized', () => {
116+
const obj = {
117+
bigint: 123n,
118+
buffer: new Uint8Array(Buffer.from('data')),
119+
date: new Date(),
120+
error: new Error('error obj'),
121+
map: new Map([['key', 1n]]),
122+
nullVal: null,
123+
set: new Set(['item1', 1n]),
124+
undefinedVal: undefined
125+
};
126+
expect(fromSerializableObject(obj)).toEqual(obj);
127+
});
114128
});
115129
});

0 commit comments

Comments
 (0)