Skip to content

Commit

Permalink
fix: Improve field validation errors (#2937)
Browse files Browse the repository at this point in the history
Improves validation errors for `Field` by rewriting the struct using
`selectiveUnion`.

Fixes #2927

---------

Co-authored-by: Maarten Zuidhoorn <[email protected]>
  • Loading branch information
FrederikBolding and Mrtenz authored Dec 10, 2024
1 parent 90b2e39 commit c7a6906
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/snaps.git"
},
"source": {
"shasum": "lyy+HECzOFQzuzjyD1nas6GPc4kMt340ChbqQZl7uEo=",
"shasum": "DYLBW3jdovQYu6jwACo/3xlujGXb0YxJ19UEpUKX1qE=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/examples/packages/browserify/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/snaps.git"
},
"source": {
"shasum": "k7NYoT8jI2E4u785PN5PoruwtjF18KNOSagNY9fS44U=",
"shasum": "dFTqb94KtIZ44IaoMYhGunl9c9Of9j67TNYobl+CwYg=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ describe('snap_createInterface', () => {
error: {
code: -32602,
message:
'Invalid params: At path: ui.props.children.props.children -- Expected the value to satisfy a union of `tuple | tuple | tuple | object | object | object | object | object | object`, but received: [object Object].',
'Invalid params: At path: ui.props.children.props.children -- Expected type to be one of: "Input", "Dropdown", "RadioGroup", "FileInput", "Checkbox", "Selector", but received: "Copyable".',
stack: expect.any(String),
},
id: 1,
Expand Down
20 changes: 14 additions & 6 deletions packages/snaps-sdk/src/jsx/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,12 +481,20 @@ export const FieldChildUnionStruct = nullUnion([
/**
* A subset of JSX elements that are allowed as children of the Field component.
*/
const FieldChildStruct = nullUnion([
tuple(BOX_INPUT_LEFT),
tuple(BOX_INPUT_RIGHT),
tuple(BOX_INPUT_BOTH),
...FIELD_CHILDREN_ARRAY,
]) as unknown as Struct<
const FieldChildStruct = selectiveUnion((value) => {
const isArray = Array.isArray(value);
if (isArray && value.length === 3) {
return tuple(BOX_INPUT_BOTH);
}

if (isArray && value.length === 2) {
return value[0]?.type === 'Box'
? tuple(BOX_INPUT_LEFT)
: tuple(BOX_INPUT_RIGHT);
}

return typedUnion(FIELD_CHILDREN_ARRAY);
}) as unknown as Struct<
| [InputElement, GenericSnapChildren]
| [GenericSnapChildren, InputElement]
| [GenericSnapChildren, InputElement, GenericSnapChildren]
Expand Down

0 comments on commit c7a6906

Please sign in to comment.