|
| 1 | +// imported from https://github.com/galkn/parseuri |
| 2 | +/** |
| 3 | + * Parses an URI |
| 4 | + * |
| 5 | + * @author Steven Levithan <stevenlevithan.com> (MIT license) |
| 6 | + * @api private |
| 7 | + */ |
| 8 | +const re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; |
| 9 | + |
| 10 | +const parts = [ |
| 11 | + 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' |
| 12 | +]; |
| 13 | + |
| 14 | +export function parse(str) { |
| 15 | + const src = str, |
| 16 | + b = str.indexOf('['), |
| 17 | + e = str.indexOf(']'); |
| 18 | + |
| 19 | + if (b != -1 && e != -1) { |
| 20 | + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); |
| 21 | + } |
| 22 | + |
| 23 | + let m = re.exec(str || ''), |
| 24 | + uri = {} as any, |
| 25 | + i = 14; |
| 26 | + |
| 27 | + while (i--) { |
| 28 | + uri[parts[i]] = m[i] || ''; |
| 29 | + } |
| 30 | + |
| 31 | + if (b != -1 && e != -1) { |
| 32 | + uri.source = src; |
| 33 | + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); |
| 34 | + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); |
| 35 | + uri.ipv6uri = true; |
| 36 | + } |
| 37 | + |
| 38 | + uri.pathNames = pathNames(uri, uri['path']); |
| 39 | + uri.queryKey = queryKey(uri, uri['query']); |
| 40 | + |
| 41 | + return uri; |
| 42 | +} |
| 43 | + |
| 44 | +function pathNames(obj, path) { |
| 45 | + const regx = /\/{2,9}/g, |
| 46 | + names = path.replace(regx, "/").split("/"); |
| 47 | + |
| 48 | + if (path.substr(0, 1) == '/' || path.length === 0) { |
| 49 | + names.splice(0, 1); |
| 50 | + } |
| 51 | + if (path.substr(path.length - 1, 1) == '/') { |
| 52 | + names.splice(names.length - 1, 1); |
| 53 | + } |
| 54 | + |
| 55 | + return names; |
| 56 | +} |
| 57 | + |
| 58 | +function queryKey(uri, query) { |
| 59 | + const data = {}; |
| 60 | + |
| 61 | + query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { |
| 62 | + if ($1) { |
| 63 | + data[$1] = $2; |
| 64 | + } |
| 65 | + }); |
| 66 | + |
| 67 | + return data; |
| 68 | +} |
0 commit comments