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

Improve error message for invalid JSON values #224

Merged
merged 3 commits into from
Dec 10, 2024
Merged
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
12 changes: 12 additions & 0 deletions src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,18 @@ describe('json', () => {
'Expected a value of type `JSON`, but received: `undefined`',
);
});

it('returns a readable error message for a nested JsonStruct', () => {
const struct = object({
value: JsonStruct,
});

const [error] = validate({ value: undefined }, struct);
assert(error !== undefined);
expect(error.message).toBe(
'At path: value -- Expected a value of type `JSON`, but received: `undefined`',
);
});
});

describe('getSafeJson', () => {
Expand Down
27 changes: 15 additions & 12 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
union,
unknown,
Struct,
refine,
} from '@metamask/superstruct';
import type {
Context,
Expand Down Expand Up @@ -215,18 +216,20 @@ export const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>
* This struct sanitizes the value before validating it, so that it is safe to
* use with untrusted input.
*/
export const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {
assertStruct(value, UnsafeJsonStruct);
return JSON.parse(
JSON.stringify(value, (propKey, propValue) => {
// Strip __proto__ and constructor properties to prevent prototype pollution.
if (propKey === '__proto__' || propKey === 'constructor') {
return undefined;
}
return propValue;
}),
);
});
export const JsonStruct = coerce(
Mrtenz marked this conversation as resolved.
Show resolved Hide resolved
UnsafeJsonStruct,
refine(any(), 'JSON', (value) => is(value, UnsafeJsonStruct)),
(value) =>
JSON.parse(
JSON.stringify(value, (propKey, propValue) => {
// Strip __proto__ and constructor properties to prevent prototype pollution.
if (propKey === '__proto__' || propKey === 'constructor') {
return undefined;
}
return propValue;
}),
),
);

/**
* Check if the given value is a valid {@link Json} value, i.e., a value that is
Expand Down
Loading