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

perf: Faster JSON validation #218

Merged
merged 6 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('index', () => {
"KnownCaipNamespace",
"PendingJsonRpcResponseStruct",
"StrictHexStruct",
"UnsafeFastJsonStruct",
"UnsafeJsonStruct",
"VersionRangeStruct",
"VersionStruct",
Expand Down
18 changes: 17 additions & 1 deletion src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ describe('json', () => {
const [error] = validate(undefined, JsonStruct);
assert(error !== undefined);
expect(error.message).toBe(
'Expected the value to satisfy a union of `literal | boolean | finite number | string | array | record`, but received: undefined',
'Expected a value of type `JSON`, but received: `undefined`',
);
});
});
Expand Down Expand Up @@ -418,6 +418,22 @@ describe('json', () => {
assertIsJsonRpcRequest(JSON_RPC_REQUEST_FIXTURES.invalid[0]),
).toThrow('Invalid JSON-RPC request: oops');
});

it('is fast for large inputs', () => {
const request = {
jsonrpc: '2.0',
id: 'foo',
method: 'wallet_invokeSnap',
params: {
snapId: 'npm:@metamask/manage-state-example-snap',
request: {
method: 'setState',
params: { items: new Array(9999999).fill(2) },
},
},
};
expect(() => assertIsJsonRpcRequest(request)).not.toThrow();
});
});

describe('isJsonRpcSuccess', () => {
Expand Down
60 changes: 58 additions & 2 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,62 @@ const finiteNumber = () =>
return is(value, number()) && Number.isFinite(value);
});

/**
* Validate an unknown input to be valid JSON.
*
* Useful for constructing JSON structs.
*
* @param json - An unknown value.
* @returns True if the value is valid JSON, otherwise false.
*/
function validateJson(json: unknown): boolean {
if (json === null || typeof json === 'boolean' || typeof json === 'string') {
return true;
}

if (typeof json === 'number' && Number.isFinite(json)) {
return true;
}

if (typeof json === 'object') {
let every = true;
if (Array.isArray(json)) {
// eslint-disable-next-line @typescript-eslint/prefer-for-of
FrederikBolding marked this conversation as resolved.
Show resolved Hide resolved
for (let i = 0; i < json.length; i++) {
if (!validateJson(json[i])) {
every = false;
break;
}
}
return every;
}

const entries = Object.entries(json);
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < entries.length; i++) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {
every = false;
break;
}
}
return every;
}

return false;
}

/**
* A struct to check if the given value is a valid JSON-serializable value.
*
* A faster alternative to {@link UnsafeJsonStruct}.
*
* Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.
*/
export const UnsafeFastJsonStruct: Struct<Json> = define('JSON', (json) =>
validateJson(json),
);

/**
* A struct to check if the given value is a valid JSON-serializable value.
*
Expand All @@ -188,8 +244,8 @@ export const UnsafeJsonStruct: Struct<Json> = union([
* 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);
export const JsonStruct = coerce(UnsafeFastJsonStruct, any(), (value) => {
assertStruct(value, UnsafeFastJsonStruct);
return JSON.parse(
JSON.stringify(value, (propKey, propValue) => {
// Strip __proto__ and constructor properties to prevent prototype pollution.
Expand Down
1 change: 1 addition & 0 deletions src/node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('node', () => {
"KnownCaipNamespace",
"PendingJsonRpcResponseStruct",
"StrictHexStruct",
"UnsafeFastJsonStruct",
"UnsafeJsonStruct",
"VersionRangeStruct",
"VersionStruct",
Expand Down
Loading