Skip to content

Commit

Permalink
fix: handle Buffer serialization (#277)
Browse files Browse the repository at this point in the history
Buffer has a toJSON implementation which is called before our replacer
function when serialising. It's JSON form is an object like `{ type:
'Buffer, data: number[] }`.

This means it doesn't get identfied as $bytes, and does not get
deserialised in the reviver. I think we'd rather have `Uint8Array`
everywhere so this PR fixes it so that it gets revived as that.

License: MIT
Signed-off-by: Oli Evans <oli@protocol.ai>
  • Loading branch information
olizilla authored Dec 9, 2022
1 parent 77bd413 commit 6dc77ca
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/access-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
"@types/assert": "^1.5.6",
"@types/inquirer": "^9.0.3",
"@types/mocha": "^10.0.1",
"@types/node": "^18.11.9",
"@types/node": "^18.11.10",
"@types/ws": "^8.5.3",
"@ucanto/server": "^4.0.2",
"assert": "^2.0.0",
Expand Down
2 changes: 2 additions & 0 deletions packages/access-client/src/utils/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export const replacer = (k, v) => {
return { $map: [...v.entries()] }
} else if (v instanceof Uint8Array) {
return { $bytes: [...v.values()] }
} else if (v?.type === 'Buffer' && Array.isArray(v.data)) {
return { $bytes: v.data }
}
return v
}
Expand Down
10 changes: 10 additions & 0 deletions packages/access-client/test/drivers/conf.node.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import assert from 'assert'
import { Buffer } from 'node:buffer'
import { ConfDriver } from '../../src/drivers/conf.js'

describe('Conf driver', () => {
Expand All @@ -11,4 +12,13 @@ describe('Conf driver', () => {
assert.strictEqual(data.foo, undefined)
assert.strictEqual(data.bar, 1)
})

it('should store a Buffer', async () => {
const driver = new ConfDriver({ profile: 'w3protocol-access-client-test' })
await driver.reset()
await driver.save({ buf: Buffer.from('⁂', 'utf8') })
const actual = await driver.load()
assert(actual)
assert.deepEqual(actual.buf, new TextEncoder().encode('⁂'))
})
})
2 changes: 1 addition & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 6dc77ca

Please sign in to comment.