mirror of
https://github.com/fluencelabs/js-multiaddr-to-uri
synced 2024-12-05 03:30:25 +00:00
3021c00543
The upgrade to multiaddr 7 brings with it a change that means multiaddrs with libp2p peer ID keys like `/ipfs/QmXXX` will be transformed to `/p 2p/QmXXX` when converted from a string, to a multiaddr instance and back to a string. This is because `p2p` and `ipfs` are name aliases for the same codec. `p2p` has now become the default and older `ipfs` names do not round trip(they are converted to `p2p` - as stated above). This change allows us to use the new multiaddr 7 lib but retain backward compatibility by ensuring the protocol specified in a string multiaddr is the protocol used in the resulting URI.
61 lines
2.0 KiB
JavaScript
61 lines
2.0 KiB
JavaScript
const Multiaddr = require('multiaddr')
|
|
|
|
const reduceValue = (_, v) => v
|
|
const tcpUri = (str, port, parts, opts) => {
|
|
// return tcp when explicitly requested
|
|
if (opts && opts.assumeHttp === false) return `tcp://${str}:${port}`
|
|
// check if tcp is the last protocol in multiaddr
|
|
let protocol = 'tcp'
|
|
let explicitPort = `:${port}`
|
|
const last = parts[parts.length - 1]
|
|
if (last.protocol === 'tcp') {
|
|
// assume http and produce clean urls
|
|
protocol = port === '443' ? 'https' : 'http'
|
|
explicitPort = port === '443' || port === '80' ? '' : explicitPort
|
|
}
|
|
return `${protocol}://${str}${explicitPort}`
|
|
}
|
|
|
|
const Reducers = {
|
|
ip4: reduceValue,
|
|
ip6: (str, content, i, parts) => (
|
|
parts.length === 1 && parts[0].protocol === 'ip6'
|
|
? content
|
|
: `[${content}]`
|
|
),
|
|
tcp: (str, content, i, parts, opts) => (
|
|
parts.some(p => ['http', 'https', 'ws', 'wss'].includes(p.protocol))
|
|
? `${str}:${content}`
|
|
: tcpUri(str, content, parts, opts)
|
|
),
|
|
udp: (str, content) => `udp://${str}:${content}`,
|
|
dnsaddr: reduceValue,
|
|
dns4: reduceValue,
|
|
dns6: reduceValue,
|
|
ipfs: (str, content) => `${str}/ipfs/${content}`,
|
|
p2p: (str, content) => `${str}/p2p/${content}`,
|
|
http: str => `http://${str}`,
|
|
https: str => `https://${str}`,
|
|
ws: str => `ws://${str}`,
|
|
wss: str => `wss://${str}`,
|
|
'p2p-websocket-star': str => `${str}/p2p-websocket-star`,
|
|
'p2p-webrtc-star': str => `${str}/p2p-webrtc-star`,
|
|
'p2p-webrtc-direct': str => `${str}/p2p-webrtc-direct`
|
|
}
|
|
|
|
module.exports = (multiaddr, opts) => {
|
|
const ma = Multiaddr(multiaddr)
|
|
const parts = multiaddr.toString().split('/').slice(1)
|
|
return ma
|
|
.tuples()
|
|
.map(tuple => ({
|
|
protocol: parts.shift(),
|
|
content: tuple[1] ? parts.shift() : null
|
|
}))
|
|
.reduce((str, part, i, parts) => {
|
|
const reduce = Reducers[part.protocol]
|
|
if (!reduce) throw new Error(`Unsupported protocol ${part.protocol}`)
|
|
return reduce(str, part.content, i, parts, opts)
|
|
}, '')
|
|
}
|