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

WIP: or combinator improvement #143

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
"./traversal": {
"import": "./src/traversal.js"
},
"./bases/base": {
"import": "./src/bases/base.js"
},
"./bases/identity": {
"import": "./src/bases/identity.js"
},
Expand Down Expand Up @@ -103,6 +106,8 @@
"@ipld/dag-pb": "^2.1.14",
"@stablelib/sha256": "^1.0.1",
"@stablelib/sha512": "^1.0.1",
"@types/chai": "^4.3.0",
"@types/mocha": "^9.0.0",
"@types/node": "^16.11.12",
"@typescript-eslint/eslint-plugin": "^5.6.0",
"@typescript-eslint/parser": "^5.6.0",
Expand All @@ -114,7 +119,7 @@
"mocha": "^9.1.3",
"polendina": "^2.0.0",
"standard": "^16.0.4",
"typescript": "^4.5.2"
"typescript": "^4.5.4"
},
"standard": {
"ignore": [
Expand Down
49 changes: 33 additions & 16 deletions src/bases/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,6 @@ class Encoder {
* @typedef {import('./interface').MultibaseDecoder<Prefix>} MultibaseDecoder
*/

/**
* @template {string} Prefix
* @typedef {import('./interface').UnibaseDecoder<Prefix>} UnibaseDecoder
*/

/**
* @template {string} Prefix
*/
Expand All @@ -72,7 +67,7 @@ class Encoder {
* @template {string} Base
* @template {string} Prefix
* @implements {MultibaseDecoder<Prefix>}
* @implements {UnibaseDecoder<Prefix>}
* @implements {CombobaseDecoder<Prefix>}
* @implements {BaseDecoder}
*/
class Decoder {
Expand All @@ -87,6 +82,22 @@ class Decoder {
this.baseDecode = baseDecode
}

/**
* @returns {CombobaseDecoder<Prefix>}
*/
get composed () {
return this
}

/**
* @type {{[K in Prefix]: MultibaseDecoder<Prefix>}}
*/
get decoders () {
return /** @type {{[K in Prefix]: MultibaseDecoder<Prefix>}} */({
[this.prefix]: /** @type {MultibaseDecoder<Prefix>} */(this)
})
}

/**
* @param {string} text
*/
Expand All @@ -107,7 +118,7 @@ class Decoder {

/**
* @template {string} OtherPrefix
* @param {UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
* @param {CombobaseDecoder<OtherPrefix>} decoder
* @returns {ComposedDecoder<Prefix|OtherPrefix>}
*/
or (decoder) {
Expand All @@ -122,7 +133,7 @@ class Decoder {

/**
* @template {string} Prefix
* @typedef {Record<Prefix, UnibaseDecoder<Prefix>>} Decoders
* @typedef {Record<Prefix, MultibaseDecoder<Prefix>>} Decoders
*/

/**
Expand All @@ -132,15 +143,15 @@ class Decoder {
*/
class ComposedDecoder {
/**
* @param {Record<Prefix, UnibaseDecoder<Prefix>>} decoders
* @param {{[K in Prefix]: MultibaseDecoder<K>}} decoders
*/
constructor (decoders) {
this.decoders = decoders
}

/**
* @template {string} OtherPrefix
* @param {UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
* @param {CombobaseDecoder<OtherPrefix>} decoder
* @returns {ComposedDecoder<Prefix|OtherPrefix>}
*/
or (decoder) {
Expand All @@ -165,13 +176,13 @@ class ComposedDecoder {
/**
* @template {string} L
* @template {string} R
* @param {UnibaseDecoder<L>|CombobaseDecoder<L>} left
* @param {UnibaseDecoder<R>|CombobaseDecoder<R>} right
* @param {CombobaseDecoder<L>} left
* @param {CombobaseDecoder<R>} right
* @returns {ComposedDecoder<L|R>}
*/
export const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
...(left.decoders || { [/** @type UnibaseDecoder<L> */(left).prefix]: left }),
...(right.decoders || { [/** @type UnibaseDecoder<R> */(right).prefix]: right })
...left.decoders,
...right.decoders
}))

/**
Expand Down Expand Up @@ -206,6 +217,10 @@ export class Codec {
this.decoder = new Decoder(name, prefix, baseDecode)
}

get decoders () {
return this.decoder.decoders
}

/**
* @param {Uint8Array} input
*/
Expand Down Expand Up @@ -353,9 +368,11 @@ const encode = (data, alphabet, bitsPerChar) => {
/**
* RFC4648 Factory
*
* @template {string} Base
* @template {string} Prefix
* @param {Object} options
* @param {string} options.name
* @param {string} options.prefix
* @param {Base} options.name
* @param {Prefix} options.prefix
* @param {string} options.alphabet
* @param {number} options.bitsPerChar
*/
Expand Down
13 changes: 3 additions & 10 deletions src/bases/interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-use-before-define */
// Base encoders / decoders just base encode / decode between binary and
// textual representation. They are unaware of multibase.

Expand Down Expand Up @@ -83,17 +84,9 @@ export interface MultibaseCodec<Prefix extends string> {
name: string
prefix: Prefix
encoder: MultibaseEncoder<Prefix>
decoder: MultibaseDecoder<Prefix>
}


export interface UnibaseDecoder<Prefix extends string> extends MultibaseDecoder<Prefix> {
// Reserve this property so it can be used to derive type.
readonly decoders?: null

readonly prefix: Prefix
decoder: CombobaseDecoder<Prefix>
}

export interface CombobaseDecoder<Prefix extends string> extends MultibaseDecoder<Prefix> {
readonly decoders: Record<Prefix, UnibaseDecoder<Prefix>>
readonly decoders: {[K in Prefix]?: MultibaseDecoder<K>}
}
24 changes: 21 additions & 3 deletions test/fixtures/test-throw.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,27 @@

export default function testThrow (fn, message) {
/**
* @param {Function} fn
* @param {string} message
*/
export const testThrowSync = (fn, message) => {
try {
fn()
} catch (e) {
if (e.message !== message) throw e
if (/** @type {Error} */(e).message !== message) throw e
return
}
/* c8 ignore next */
throw new Error('Test failed to throw')
}

/**
* @param {Function} fn
* @param {string} message
*/
export const testThrowAsync = async (fn, message) => {
try {
await fn()
} catch (e) {
if (/** @type {Error} */(e).message !== message) throw e
return
}
/* c8 ignore next */
Expand Down
80 changes: 49 additions & 31 deletions test/test-block.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { sha256 as hasher } from 'multiformats/hashes/sha2'
import * as main from 'multiformats/block'
import { CID, bytes } from 'multiformats'
import { assert } from 'chai'
import { testThrowAsync, testThrowSync } from './fixtures/test-throw.js'

const fixture = { hello: 'world' }
const link = CID.parse('bafyreidykglsfhoixmivffc5uwhcgshx4j465xwqntbmu43nb2dzqwfvae')
Expand All @@ -27,7 +28,15 @@ describe('block', () => {
})

describe('reader', () => {
const value = { link, nope: 'skip', arr: [link], obj: { arr: [{ obj: {} }] }, bytes: Uint8Array.from('1234') }
const value = {
link,
nope: 'skip',
arr: [link],
obj: { arr: [{ obj: {} }] },
// @ts-expect-error - 'string' is not assignable to parameter of type 'ArrayLike<number>'
bytes: Uint8Array.from('1234')
}
// @ts-expect-error - 'boolean' is not assignable to type 'CID'
const block = main.createUnsafe({ value, codec, hasher, cid: true, bytes: true })

it('links', () => {
Expand All @@ -50,11 +59,20 @@ describe('block', () => {
assert.deepStrictEqual(ret.remaining, 'test')
assert.deepStrictEqual(ret.value.toString(), link.toString())
ret = block.get('nope')
// @ts-expect-error - 'string' is not expected
assert.deepStrictEqual(ret, { value: 'skip' })
})

it('null links/tree', () => {
const block = main.createUnsafe({ value: null, codec, hasher, bytes: true, cid: true })
const block = main.createUnsafe({
value: null,
codec,
hasher,
// @ts-expect-error - 'boolean' is not assignable to type 'ByteView<unknown>'
bytes: true,
// @ts-expect-error - 'boolean' is not assignable to type 'CID'
cid: true
})
// eslint-disable-next-line
for (const x of block.tree()) {
throw new Error(`tree should have nothing, got "${x}"`)
Expand All @@ -68,58 +86,58 @@ describe('block', () => {

it('kitchen sink', () => {
const sink = { one: { two: { arr: [true, false, null], three: 3, buff, link } } }
const block = main.createUnsafe({ value: sink, codec, bytes: true, cid: true })
const block = main.createUnsafe({
value: sink,
codec,
// @ts-expect-error - 'boolean' is not assignable to type 'ByteView<unknown>'
bytes: true,
// @ts-expect-error - 'boolean' is not assignable to type 'CID'
cid: true
})
assert.deepStrictEqual(sink, block.value)
})

describe('errors', () => {
it('constructor missing args', () => {
let threw = true
try {
threw = new main.Block({})
threw = false
} catch (e) {
if (e.message !== 'Missing required argument') throw e
}
assert.deepStrictEqual(threw, true)
testThrowSync(
// @ts-expect-error - missing properties
() => new main.Block({}),
'Missing required argument'
)
})

const errTest = async (method, arg, message) => {
let threw = true
try {
await method(arg)
threw = false
} catch (e) {
if (e.message !== message) throw e
}
assert.deepStrictEqual(threw, true)
}

it('encode', async () => {
await errTest(main.encode, {}, 'Missing required argument "value"')
await errTest(main.encode, { value: true }, 'Missing required argument: codec or hasher')
// @ts-expect-error
await testThrowAsync(() => main.encode({}), 'Missing required argument "value"')
// @ts-expect-error
await testThrowAsync(() => main.encode({ value: true }), 'Missing required argument: codec or hasher')
})

it('decode', async () => {
await errTest(main.decode, {}, 'Missing required argument "bytes"')
await errTest(main.decode, { bytes: true }, 'Missing required argument: codec or hasher')
// @ts-expect-error
await testThrowAsync(() => main.decode({}), 'Missing required argument "bytes"')
// @ts-expect-error
await testThrowAsync(() => main.decode({ bytes: true }), 'Missing required argument: codec or hasher')
})

it('createUnsafe', async () => {
await errTest(main.createUnsafe, {}, 'Missing required argument, must either provide "value" or "codec"')
// @ts-expect-error
await testThrowAsync(() => main.createUnsafe({}), 'Missing required argument, must either provide "value" or "codec"')
})

it('create', async () => {
await errTest(main.create, {}, 'Missing required argument "bytes"')
await errTest(main.create, { bytes: true }, 'Missing required argument "hasher"')
// @ts-expect-error
await testThrowAsync(() => main.create({}), 'Missing required argument "bytes"')
// @ts-expect-error
await testThrowAsync(() => main.create({ bytes: true }), 'Missing required argument "hasher"')
const block = await main.encode({ value: fixture, codec, hasher })
const block2 = await main.encode({ value: { ...fixture, test: 'blah' }, codec, hasher })
await errTest(main.create, { bytes: block.bytes, cid: block2.cid, codec, hasher }, 'CID hash does not match bytes')
await testThrowAsync(() => main.create({ bytes: block.bytes, cid: block2.cid, codec, hasher }), 'CID hash does not match bytes')
})

it('get', async () => {
const block = await main.encode({ value: fixture, codec, hasher })
await errTest(path => block.get(path), '/asd/fs/dfasd/f', 'Object has no property at ["asd"]')
await testThrowAsync(() => block.get('/asd/fs/dfasd/f'), 'Object has no property at ["asd"]')
})
})
})
4 changes: 2 additions & 2 deletions test/test-bytes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { assert } from 'chai'

describe('bytes', () => {
it('isBinary', () => {
assert.deepStrictEqual(bytes.isBinary(new ArrayBuffer()), true)
assert.deepStrictEqual(bytes.isBinary(new DataView(new ArrayBuffer())), true)
assert.deepStrictEqual(bytes.isBinary(new ArrayBuffer(0)), true)
assert.deepStrictEqual(bytes.isBinary(new DataView(new ArrayBuffer(0))), true)
})

it('coerce', () => {
Expand Down
Loading