Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,17 @@ describe('structuredClone', () => {
expectDataCloneError(() => structuredClone(Promise.resolve(4)));
});

it('does not coerce non-serializable values', () => {
const values: Array<$FlowFixMe> = [() => {}, new WeakMap()];
for (const value of values) {
value[Symbol.toPrimitive] = () => {
throw new Error('Unexpected coercion');
};

expectDataCloneError(() => structuredClone(value));
}
});

it('clones simple objects', () => {
const value = {foo: 'bar'};
const clone = structuredClone(value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ const ObjectPrototype = Object.prototype;
// any given point we only have one memory object alive anyway.
const memory: Map<unknown, unknown> = new Map();

function createDataCloneError(): DOMException {
return new DOMException(
"Failed to execute 'structuredClone' on 'Window': value could not be cloned.",
'DataCloneError',
);
}

function structuredCloneInternal<T>(value: T): T {
// Handles `null` and `undefined`.
if (value == null) {
Expand All @@ -52,11 +59,7 @@ function structuredCloneInternal<T>(value: T): T {

// Handles unsupported types (symbols and functions).
if (typeof value !== 'object') {
// value is symbol or function
throw new DOMException(
`Failed to execute 'structuredClone' on 'Window': ${String(value)} could not be cloned.`,
'DataCloneError',
);
throw createDataCloneError();
}

// Handles circular references.
Expand Down Expand Up @@ -168,10 +171,7 @@ function structuredCloneInternal<T>(value: T): T {

// Known non-serializable objects.
if (isNonSerializableObject(value) || isPlatformObject(value)) {
throw new DOMException(
`Failed to execute 'structuredClone' on 'Window': ${String(value)} could not be cloned.`,
'DataCloneError',
);
throw createDataCloneError();
}

// Arbitrary object slow path
Expand Down
Loading