forked from pfrazee/parse-dat-url
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
33 lines (29 loc) · 1.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const isNode = typeof window === 'undefined'
const parse = isNode ? require('url').parse : browserParse
const SCHEME_REGEX = /[a-z]+:\/\//i
// 1 2 3 4
const VERSION_REGEX = /^(dat:\/\/)?([^/]+)(\+[^/]+)(.*)$/i
module.exports = function parseDatURL (str, parseQS) {
// prepend the scheme if it's missing
if (!SCHEME_REGEX.test(str)) {
str = 'dat://' + str
}
var parsed, version = null, match = VERSION_REGEX.exec(str)
if (match) {
// run typical parse with version segment removed
parsed = parse((match[1] || '') + (match[2] || '') + (match[4] || ''), parseQS)
version = match[3].slice(1)
} else {
parsed = parse(str, parseQS)
}
if (isNode) parsed.href = str // overwrite href to include actual original
else parsed.path = parsed.pathname // to match node
if (!parsed.query && parsed.searchParams) {
parsed.query = Object.fromEntries(parsed.searchParams) // to match node
}
parsed.version = version // add version segment
return parsed
}
function browserParse (str) {
return new URL(str)
}