Skip to content

Commit

Permalink
feat!: coerce undefined to null on decode
Browse files Browse the repository at this point in the history
For legacy data since this has been allowed by dag-cbor for a long time.
New data should _not_ take advantage of this, `undefined` should not appear
in IPLD data structures as it is not part of the IPLD data model.

Fixes: #44
Ref: ipld/go-ipld-prime#308
  • Loading branch information
rvagg committed Dec 13, 2021
1 parent e7939c7 commit 6bd4107
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 deletions.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function cidDecoder (bytes) {

const decodeOptions = {
allowIndefinite: false,
allowUndefined: false,
coerceUndefinedToNull: true,
allowNaN: false,
allowInfinity: false,
allowBigInt: true, // this will lead to BigInt for ints outside of
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"import": "./index.js"
},
"dependencies": {
"cborg": "^1.5.4",
"cborg": "^1.6.0",
"multiformats": "^9.5.4"
},
"devDependencies": {
Expand Down
17 changes: 11 additions & 6 deletions test/test-basics.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,6 @@ describe('dag-cbor', () => {
assert.throws(() => encode(objWithUndefined), /\Wundefined\W.*not supported/)
})

test('error on decoding undefined', () => {
// encoded forms from the encode() test above
assert.throws(() => decode(bytes.fromHex('f7')), /\Wundefined\W.*not supported/)
assert.throws(() => decode(bytes.fromHex('a2616161616162f7')), /\Wundefined\W.*not supported/)
})

test('error on encoding IEEE 754 specials', () => {
for (const special of [NaN, Infinity, -Infinity]) {
assert.throws(() => encode(special), new RegExp(`\\W${String(special)}\\W.*not supported`))
Expand Down Expand Up @@ -172,4 +166,15 @@ describe('dag-cbor', () => {
const encoded = bytes.fromHex('a1646c696e6bd82a582501017012207252523e6591fb8fe553d67ff55a86f84044b46a3e4176e10c58fa529a4aabd5')
assert.throws(() => decode(encoded), /Invalid CID for CBOR tag 42; expected leading 0x00/)
})

test('sloppy decode: coerce undefined', () => {
// See https://github.com/ipld/js-dag-cbor/issues/44 for context on this
let encoded = bytes.fromHex('f7')
let decoded = decode(encoded)
same(null, decoded)

encoded = bytes.fromHex('a26362617af763666f6f63626172')
decoded = decode(encoded)
same({ foo: 'bar', baz: null }, decoded)
})
})

0 comments on commit 6bd4107

Please sign in to comment.