UNPKG

multiformats

Version:

Interface for multihash, multicodec, multibase and CID

118 lines 2.94 kB
import OldCID from 'cids'; import * as bytes from './bytes.js'; import { Buffer } from 'buffer'; import CID from './cid.js'; const legacy = (codec, {hashes}) => { const toLegacy = obj => { if (OldCID.isCID(obj)) { return obj; } const newCID = CID.asCID(obj); if (newCID) { const { version, code, multihash: {bytes} } = newCID; const {buffer, byteOffset, byteLength} = bytes; const multihash = Buffer.from(buffer, byteOffset, byteLength); return new OldCID(version, code, multihash); } if (bytes.isBinary(obj)) { return Buffer.from(obj); } if (obj && typeof obj === 'object') { for (const [key, value] of Object.entries(obj)) { obj[key] = toLegacy(value); } } return obj; }; const fromLegacy = obj => { const cid = CID.asCID(obj); if (cid) return cid; if (bytes.isBinary(obj)) return bytes.coerce(obj); if (obj && typeof obj === 'object') { for (const [key, value] of Object.entries(obj)) { obj[key] = fromLegacy(value); } } return obj; }; const serialize = o => Buffer.from(codec.encode(fromLegacy(o))); const deserialize = b => toLegacy(codec.decode(bytes.coerce(b))); const cid = async (buff, opts) => { const defaults = { cidVersion: 1, hashAlg: 'sha2-256' }; const {cidVersion, hashAlg} = { ...defaults, ...opts }; const hasher = hashes[hashAlg]; if (hasher == null) { throw new Error(`Hasher for ${ hashAlg } was not provided in the configuration`); } const hash = await hasher.digest(buff); return new OldCID(cidVersion, codec.name, Buffer.from(hash.bytes)); }; const resolve = (buff, path) => { let value = codec.decode(buff); const entries = path.split('/').filter(x => x); while (entries.length) { value = value[entries.shift()]; if (typeof value === 'undefined') throw new Error('Not found'); if (OldCID.isCID(value)) { return { value, remainderPath: entries.join('/') }; } } return { value, remainderPath: '' }; }; const _tree = function* (value, path = []) { if (typeof value === 'object') { for (const [key, val] of Object.entries(value)) { yield [ '', ...path, key ].join('/'); if (typeof val === 'object' && !Buffer.isBuffer(val) && !OldCID.isCID(val)) { yield* _tree(val, [ ...path, key ]); } } } }; const tree = buff => { return _tree(codec.decode(buff)); }; const defaultHashAlg = 'sha2-256'; const util = { serialize, deserialize, cid }; const resolver = { resolve, tree }; return { defaultHashAlg, codec: codec.code, util, resolver }; }; export default legacy;