multiformats
Version:
Interface for multihash, multicodec, multibase and CID
127 lines (121 loc) • 3.31 kB
JavaScript
var OLDCID = require('cids');
var bytes = require('./bytes.js');
var buffer = require('buffer');
var cid = require('./cid.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var OLDCID__default = /*#__PURE__*/_interopDefaultLegacy(OLDCID);
const legacy = (codec, {hashes}) => {
const toLegacy = obj => {
if (OLDCID__default['default'].isCID(obj)) {
return obj;
}
const newCID = cid.asCID(obj);
if (newCID) {
const {
version,
code,
multihash: {bytes}
} = newCID;
const {buffer: buffer$1, byteOffset, byteLength} = bytes;
const multihash = buffer.Buffer.from(buffer$1, byteOffset, byteLength);
return new OLDCID__default['default'](version, code, multihash);
}
if (bytes.isBinary(obj)) {
return buffer.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$1 = cid.asCID(obj);
if (cid$1)
return cid$1;
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.Buffer.from(codec.encode(fromLegacy(o)));
const deserialize = b => toLegacy(codec.decode(bytes.coerce(b)));
const cid$1 = 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__default['default'](cidVersion, codec.name, buffer.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__default['default'].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.Buffer.isBuffer(val) && !OLDCID__default['default'].isCID(val)) {
yield* _tree(val, [
...path,
key
]);
}
}
}
};
const tree = buff => {
return _tree(codec.decode(buff));
};
const defaultHashAlg = 'sha2-256';
const util = {
serialize,
deserialize,
cid: cid$1
};
const resolver = {
resolve,
tree
};
return {
defaultHashAlg,
codec: codec.code,
util,
resolver
};
};
module.exports = legacy;
;