2018-03-20 14:39:26 +00:00
|
|
|
const Multiaddr = require('multiaddr')
|
2019-08-21 10:09:35 +00:00
|
|
|
|
2018-03-20 14:39:26 +00:00
|
|
|
const reduceValue = (_, v) => v
|
2019-08-21 10:09:35 +00:00
|
|
|
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
|
2020-01-01 22:29:49 +00:00
|
|
|
protocol = port === '443' ? 'https' : 'http'
|
|
|
|
explicitPort = port === '443' || port === '80' ? '' : explicitPort
|
2019-08-21 10:09:35 +00:00
|
|
|
}
|
|
|
|
return `${protocol}://${str}${explicitPort}`
|
|
|
|
}
|
2018-03-20 14:39:26 +00:00
|
|
|
|
2018-03-21 10:09:39 +00:00
|
|
|
const Reducers = {
|
2018-03-20 14:39:26 +00:00
|
|
|
ip4: reduceValue,
|
2019-01-13 10:12:30 +00:00
|
|
|
ip6: (str, content, i, parts) => (
|
2019-01-13 10:22:17 +00:00
|
|
|
parts.length === 1 && parts[0].protocol === 'ip6'
|
|
|
|
? content
|
|
|
|
: `[${content}]`
|
2019-01-13 10:12:30 +00:00
|
|
|
),
|
2019-08-21 10:09:35 +00:00
|
|
|
tcp: (str, content, i, parts, opts) => (
|
2018-03-20 14:39:26 +00:00
|
|
|
parts.some(p => ['http', 'https', 'ws', 'wss'].includes(p.protocol))
|
|
|
|
? `${str}:${content}`
|
2019-08-21 10:09:35 +00:00
|
|
|
: tcpUri(str, content, parts, opts)
|
2018-03-20 14:39:26 +00:00
|
|
|
),
|
|
|
|
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`
|
|
|
|
}
|
|
|
|
|
2020-01-01 22:29:49 +00:00
|
|
|
module.exports = (multiaddr, opts) => {
|
|
|
|
const ma = Multiaddr(multiaddr)
|
|
|
|
const parts = multiaddr.toString().split('/').slice(1)
|
|
|
|
return ma
|
|
|
|
.tuples()
|
2018-03-20 14:39:26 +00:00
|
|
|
.map(tuple => ({
|
2020-01-01 22:29:49 +00:00
|
|
|
protocol: parts.shift(),
|
|
|
|
content: tuple[1] ? parts.shift() : null
|
2018-03-20 14:39:26 +00:00
|
|
|
}))
|
|
|
|
.reduce((str, part, i, parts) => {
|
2018-03-21 10:09:39 +00:00
|
|
|
const reduce = Reducers[part.protocol]
|
2018-03-20 14:39:26 +00:00
|
|
|
if (!reduce) throw new Error(`Unsupported protocol ${part.protocol}`)
|
2019-08-21 10:09:35 +00:00
|
|
|
return reduce(str, part.content, i, parts, opts)
|
2018-03-20 14:39:26 +00:00
|
|
|
}, '')
|
2020-01-01 22:29:49 +00:00
|
|
|
}
|