js-mafmt/src/index.js

153 lines
2.7 KiB
JavaScript
Raw Normal View History

2016-03-23 15:07:25 +01:00
'use strict'
const multiaddr = require('multiaddr')
/*
* Valid combinations
*/
const DNS = base('dns')
const IP = or(base('ip4'), base('ip6'))
const TCP = and(IP, base('tcp'))
const UDP = and(IP, base('udp'))
const UTP = and(UDP, base('utp'))
const WebSockets = or(
and(TCP, base('ws')),
and(DNS, base('ws'))
)
const HTTP = or(
and(TCP, base('http')),
and(DNS),
and(DNS, base('http'))
)
const WebRTCStar = and(base('libp2p-webrtc-star'), WebSockets, base('ipfs'))
const WebRTCDirect = and(base('libp2p-webrtc-direct'), HTTP)
const Reliable = or(WebSockets, TCP, UTP)
const IPFS = or(
and(Reliable, base('ipfs')),
and(WebRTCStar)
)
exports.DNS = DNS
2016-01-19 17:23:52 +01:00
exports.IP = IP
exports.TCP = TCP
exports.UDP = UDP
exports.UTP = UTP
exports.HTTP = HTTP
2016-03-12 12:36:19 +00:00
exports.WebSockets = WebSockets
2016-05-21 19:57:26 +01:00
exports.WebRTCStar = WebRTCStar
exports.WebRTCDirect = WebRTCDirect
2016-01-19 17:23:52 +01:00
exports.Reliable = Reliable
exports.IPFS = IPFS
/*
* Validation funcs
*/
2016-01-19 17:23:52 +01:00
function and () {
const args = Array.from(arguments)
2016-01-19 17:23:52 +01:00
function matches (a) {
if (typeof a === 'string') {
a = multiaddr(a)
}
let out = partialMatch(a.protoNames())
2016-01-19 17:23:52 +01:00
if (out === null) {
return false
}
return out.length === 0
}
function partialMatch (a) {
if (a.length < args.length) {
return null
}
args.some(function (arg) {
a = arg.partialMatch(a)
if (a === null) {
return true
}
})
return a
}
return {
input: args,
matches: matches,
partialMatch: partialMatch
}
}
function or () {
const args = Array.from(arguments)
2016-01-19 17:23:52 +01:00
function matches (a) {
if (typeof a === 'string') {
a = multiaddr(a)
}
const out = partialMatch(a.protoNames())
2016-01-19 17:23:52 +01:00
if (out === null) {
return false
}
return out.length === 0
}
function partialMatch (a) {
let out = null
2016-01-19 17:23:52 +01:00
args.some(function (arg) {
const res = arg.partialMatch(a)
2016-01-19 17:23:52 +01:00
if (res) {
out = res
return true
}
})
return out
}
const result = {
2016-01-19 17:23:52 +01:00
toString: function () { return '{ ' + args.join(' ') + ' }' },
input: args,
matches: matches,
partialMatch: partialMatch
}
return result
2016-01-19 17:23:52 +01:00
}
function base (n) {
const name = n
2016-01-19 17:23:52 +01:00
function matches (a) {
if (typeof a === 'string') {
a = multiaddr(a)
}
const pnames = a.protoNames()
2016-01-19 17:23:52 +01:00
if (pnames.length === 1 && pnames[0] === name) {
return true
}
return false
}
function partialMatch (protos) {
if (protos.length === 0) {
return null
}
if (protos[0] === name) {
return protos.slice(1)
}
return null
}
return {
toString: function () { return name },
matches: matches,
partialMatch: partialMatch
}
}