Skip to content
This repository was archived by the owner on Jan 12, 2026. It is now read-only.

Commit 588a76e

Browse files
committed
shapehash: Handle '{}' without crashing
toJson iterated over `item.fields` but this is empty when a JSON object is empty. The result was a crash while iterating on `undefined`. We now only iterate if the `.fields` is valid. Signed-off-by: Ray Bejjani <ray.bejjani@useoptic.com>
1 parent 54cd742 commit 588a76e

3 files changed

Lines changed: 20 additions & 5 deletions

File tree

workspaces/shape-hash/src/json-to-shape-hash.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,12 @@ export function toJsonExample(hash: string): any {
7575
function toJson(item: any) {
7676
switch (item.type) {
7777
case types.OBJECT:
78-
const newObj = {};
79-
item.fields.forEach(({ key, hash }: any) => {
80-
//@ts-ignore
81-
newObj[key] = toJson(hash);
82-
});
78+
const newObj: Record<string, any> = {};
79+
if (item.hasOwnProperty('fields')) {
80+
item.fields.forEach(({ key, hash }: any) => {
81+
newObj[key] = toJson(hash);
82+
});
83+
}
8384
return newObj;
8485
case types.ARRAY:
8586
return [...item.items.map(toJson)];

workspaces/shape-hash/src/test/__snapshots__/shape-hash.test.ts.snap

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,16 @@ Object {
399399

400400
exports[`can shape hash a json object 2`] = `"CAAS8AEKCGdsb3NzYXJ5EuMBCAASCwoFdGl0bGUSAggCEtEBCghHbG9zc0RpdhLEAQgAEgsKBXRpdGxlEgIIAhKyAQoJR2xvc3NMaXN0EqQBCAASnwEKCkdsb3NzRW50cnkSkAEIABIICgJJRBICCAUSDAoGU29ydEFzEgIIAhIPCglHbG9zc1Rlcm0SAggCEg0KB0Fjcm9ueW0SAggCEgwKBkFiYnJldhICCAISNgoIR2xvc3NEZWYSKggAEgoKBHBhcmESAggCEhoKDEdsb3NzU2VlQWxzbxIKCAEaAggCGgIIAhIOCghHbG9zc1NlZRICCAI="`;
401401

402+
exports[`correctly encode "{}" 1`] = `
403+
Object {
404+
"data": Array [
405+
8,
406+
0,
407+
],
408+
"type": "Buffer",
409+
}
410+
`;
411+
402412
exports[`shape hashes of string are secure 1`] = `
403413
Object {
404414
"data": Array [

workspaces/shape-hash/src/test/shape-hash.test.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,7 @@ test('can create a sanitized example from the hash', async () => {
4242
test('shape hashes of string are secure', async () => {
4343
expect(toBytes('123,456,789')).toMatchSnapshot();
4444
});
45+
46+
test('correctly encode "{}"', async () => {
47+
expect(toBytes({})).toMatchSnapshot();
48+
});

0 commit comments

Comments
 (0)