diff --git a/package.json b/package.json index a658735d2c..01a1bad1b6 100644 --- a/package.json +++ b/package.json @@ -81,7 +81,7 @@ "cid-tool": "~0.4.0", "cids": "~0.7.1", "class-is": "^1.1.0", - "dag-cbor-links": "^1.3.0", + "dag-cbor-links": "^1.3.2", "datastore-core": "~0.7.0", "datastore-pubsub": "^0.2.1", "debug": "^4.1.0", diff --git a/src/cli/commands/dag/put.js b/src/cli/commands/dag/put.js index 45ebd0345c..5c469d8c6c 100644 --- a/src/cli/commands/dag/put.js +++ b/src/cli/commands/dag/put.js @@ -4,6 +4,7 @@ const mh = require('multihashes') const multibase = require('multibase') const dagCBOR = require('ipld-dag-cbor') const dagPB = require('ipld-dag-pb') +const CID = require('cids') const { cidToString } = require('../../../utils/cid') const inputDecoders = { @@ -109,6 +110,12 @@ module.exports = { source = inputDecoders[inputEncoding](source) + // Support legacy { "/" : "" } format so dag put is actually useful + // on the command line: https://github.com/ipld/js-ipld-dag-cbor/issues/84 + if (inputEncoding === 'json' && format === 'dag-cbor') { + source = objectSlashToCID(source) + } + const cid = await ipfs.dag.put(source, { format, hashAlg, @@ -122,3 +129,26 @@ module.exports = { })()) } } + +function objectSlashToCID (obj) { + if (Array.isArray(obj)) { + return obj.map(objectSlashToCID) + } + + if (obj && typeof obj === 'object') { + const keys = Object.keys(obj) + if (keys.length === 1 && '/' in obj) { + if (typeof obj['/'] !== 'string') { + throw new Error('link should have been a string') + } + return new CID(obj['/']) // throws if not a CID - consistent with go-ipfs + } + + return keys.reduce((obj, key) => { + obj[key] = objectSlashToCID(obj[key]) + return obj + }, obj) + } + + return obj +} diff --git a/test/cli/dag.js b/test/cli/dag.js index cab2460864..dcd8521573 100644 --- a/test/cli/dag.js +++ b/test/cli/dag.js @@ -135,5 +135,30 @@ describe('dag', () => runOnAndOff.off((thing) => { const out = await ipfs('pin ls') expect(out).to.include(cid) }) + + it('puts a cbor node with a legacy { "/": "" } links', async function () { + this.timeout(20 * 1000) + + const input = `dag api rulz ${Date.now()}` + + const linkedCid = (await ipfs('dag put', { + input: Buffer.from(`"${input}"`) + })).trim() + + const cid = (await ipfs('dag put', { + input: Buffer.from(JSON.stringify({ + link: { '/': linkedCid }, + arrayLink: [{ '/': linkedCid }], + data: { test: Date.now() }, + noData: null + })) + })).trim() + + const out0 = (await ipfs(`dag get ${cid}/link`)).trim() + expect(out0).to.equal(input) + + const out1 = (await ipfs(`dag get ${cid}/arrayLink/0`)).trim() + expect(out1).to.equal(input) + }) }) }))