UNPKG

3.27 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright 2020 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18Object.defineProperty(exports, "__esModule", { value: true });
19exports.uriToString = exports.splitHostPort = exports.parseUri = void 0;
20/*
21 * The groups correspond to URI parts as follows:
22 * 1. scheme
23 * 2. authority
24 * 3. path
25 */
26const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;
27function parseUri(uriString) {
28 const parsedUri = URI_REGEX.exec(uriString);
29 if (parsedUri === null) {
30 return null;
31 }
32 return {
33 scheme: parsedUri[1],
34 authority: parsedUri[2],
35 path: parsedUri[3],
36 };
37}
38exports.parseUri = parseUri;
39const NUMBER_REGEX = /^\d+$/;
40function splitHostPort(path) {
41 if (path.startsWith('[')) {
42 const hostEnd = path.indexOf(']');
43 if (hostEnd === -1) {
44 return null;
45 }
46 const host = path.substring(1, hostEnd);
47 /* Only an IPv6 address should be in bracketed notation, and an IPv6
48 * address should have at least one colon */
49 if (host.indexOf(':') === -1) {
50 return null;
51 }
52 if (path.length > hostEnd + 1) {
53 if (path[hostEnd + 1] === ':') {
54 const portString = path.substring(hostEnd + 2);
55 if (NUMBER_REGEX.test(portString)) {
56 return {
57 host: host,
58 port: +portString,
59 };
60 }
61 else {
62 return null;
63 }
64 }
65 else {
66 return null;
67 }
68 }
69 else {
70 return {
71 host,
72 };
73 }
74 }
75 else {
76 const splitPath = path.split(':');
77 /* Exactly one colon means that this is host:port. Zero colons means that
78 * there is no port. And multiple colons means that this is a bare IPv6
79 * address with no port */
80 if (splitPath.length === 2) {
81 if (NUMBER_REGEX.test(splitPath[1])) {
82 return {
83 host: splitPath[0],
84 port: +splitPath[1],
85 };
86 }
87 else {
88 return null;
89 }
90 }
91 else {
92 return {
93 host: path,
94 };
95 }
96 }
97}
98exports.splitHostPort = splitHostPort;
99function uriToString(uri) {
100 let result = '';
101 if (uri.scheme !== undefined) {
102 result += uri.scheme + ':';
103 }
104 if (uri.authority !== undefined) {
105 result += '//' + uri.authority + '/';
106 }
107 result += uri.path;
108 return result;
109}
110exports.uriToString = uriToString;
111//# sourceMappingURL=uri-parser.js.map
\No newline at end of file