-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.ts
352 lines (311 loc) · 11.4 KB
/
main.ts
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import {HostType, IConnectionDefaults, IEncodingOptions, IHost, IParsedHost} from './types';
import {decode, encode, hasText, fullHostName, parseHost, validateUrl} from './static';
import {setupCustomInspect} from './inspect';
const errInvalidDefaults = `Invalid "defaults" parameter: `;
export class ConnectionString {
/**
* Connection protocol, if specified,
* or else the property does not exist.
*/
protocol?: string;
/**
* User name, if specified,
* or else the property does not exist.
*/
user?: string;
/**
* User password, if specified,
* or else the property does not exist.
*/
password?: string;
/**
* List of parsed hosts, if at least one is specified,
* or else the property does not exist.
*/
hosts?: IParsedHost[];
/**
* Url path segments, if at least one is specified,
* or else the property does not exist.
*/
path?: string[];
/**
* Url parameters, if at least one is specified,
* or else the property does not exist.
*/
params?: { [name: string]: any };
/**
* Safe read-accessor to the first host's full name (hostname + port).
*/
get host(): string | undefined {
return this.hosts?.[0].toString();
}
/**
* Safe read-accessor to the first host's name (without port).
*/
get hostname(): string | undefined {
return this.hosts?.[0].name;
}
/**
* Safe read-accessor to the first host's port.
*/
get port(): number | undefined {
return this.hosts?.[0].port;
}
/**
* Safe read-accessor to the first host's type.
*/
get type(): HostType | undefined {
return this.hosts?.[0].type;
}
/**
* Constructor.
*
* @param cs - connection string (can be empty).
*
* @param defaults - optional defaults, which can also be set
* explicitly, via method setDefaults.
*/
constructor(cs?: string | null, defaults?: IConnectionDefaults) {
if (!(this instanceof ConnectionString)) {
throw new TypeError(`Class constructor ConnectionString cannot be invoked without 'new'`);
}
cs = cs ?? '';
if (typeof cs as any !== 'string') {
throw new TypeError(`Invalid connection string: ${JSON.stringify(cs)}`);
}
if (typeof (defaults ?? {}) !== 'object') {
throw new TypeError(errInvalidDefaults + JSON.stringify(defaults));
}
cs = cs.trim();
validateUrl(cs); // will throw, if failed
// Extracting the protocol:
let m = cs.match(/^(.*)?:\/\//);
if (m) {
const p = m[1]; // protocol name
if (p) {
const m2 = p.match(/^([a-z]+[a-z0-9+-.:]*)/i);
if (p && (!m2 || m2[1] !== p)) {
throw new Error(`Invalid protocol name: ${p}`);
}
this.protocol = p;
}
cs = cs.substring(m[0].length);
}
// Extracting user + password:
m = cs.match(/^([\w-_.+!*'()$%]*):?([\w-_.+!*'()$%~]*)@/);
if (m) {
if (m[1]) {
this.user = decode(m[1]);
}
if (m[2]) {
this.password = decode(m[2]);
}
cs = cs.substring(m[0].length);
}
// Extracting hosts details:
// (if it starts with `/`, it is the first path segment, i.e. no hosts specified)
if (cs[0] !== '/') {
const endOfHosts = cs.search(/[\/?]/);
const hosts = (endOfHosts === -1 ? cs : cs.substring(0, endOfHosts)).split(',');
hosts.forEach(h => {
const host = parseHost(h);
if (host) {
if (!this.hosts) {
this.hosts = [];
}
this.hosts.push(host);
}
});
if (endOfHosts >= 0) {
cs = cs.substring(endOfHosts);
}
}
// Extracting the path:
m = cs.match(/\/([\w-_.+!*'()$%]+)/g);
if (m) {
this.path = m.map(s => decode(s.substring(1)));
}
// Extracting parameters:
const idx = cs.indexOf('?');
if (idx !== -1) {
cs = cs.substring(idx + 1);
m = cs.match(/([\w-_.+!*'()$%]+)=([\w-_.+!*'()$%,]+)/g);
if (m) {
const params: { [name: string]: string | string[] } = {};
m.forEach(s => {
const a = s.split('=');
const prop = decode(a[0]);
const val = a[1].split(',').map(decode);
if (prop in params) {
if (Array.isArray(params[prop])) {
(params[prop] as string[]).push(...val);
} else {
params[prop] = [params[prop] as string, ...val];
}
} else {
params[prop] = val.length > 1 ? val : val[0];
}
});
this.params = params;
}
}
if (defaults) {
this.setDefaults(defaults);
}
}
/**
* Parses a host name into an object, which then can be passed into `setDefaults`.
*
* It returns `null` only when no valid host recognized.
*/
static parseHost(host: string): IParsedHost | null {
return parseHost(host, true);
}
/**
* Converts this object into a valid connection string.
*/
toString(options?: IEncodingOptions): string {
let s = this.protocol ? `${this.protocol}://` : ``;
const opts = <IEncodingOptions>options || {};
if (this.user || this.password) {
if (this.user) {
s += encode(this.user, opts);
}
if (this.password) {
s += ':';
const h = opts.passwordHash;
if (h) {
const code = (typeof h === 'string' && h[0]) || '#';
s += code.repeat(this.password.length);
} else {
s += encode(this.password, opts);
}
}
s += '@';
}
if (Array.isArray(this.hosts)) {
s += this.hosts.map(h => fullHostName(h, options)).join();
}
if (Array.isArray(this.path)) {
this.path.forEach(seg => {
s += `/${encode(seg, opts)}`;
});
}
if (this.params && typeof this.params === 'object') {
const params = [];
for (const a in this.params) {
let value = this.params[a];
value = Array.isArray(value) ? value : [value];
value = value.map((v: any) => {
return encode(typeof v === 'string' ? v : JSON.stringify(v), opts);
}).join();
if (opts.plusForSpace) {
value = value.replace(/%20/g, '+');
}
params.push(`${encode(a, opts)}=${value}`);
}
if (params.length) {
s += `?${params.join('&')}`;
}
}
return s;
}
/**
* Applies default parameters, and returns itself.
*/
setDefaults(defaults: IConnectionDefaults): this {
if (!defaults || typeof defaults !== 'object') {
throw new TypeError(errInvalidDefaults + JSON.stringify(defaults));
}
if (!('protocol' in this) && hasText(defaults.protocol)) {
this.protocol = defaults.protocol && defaults.protocol.trim();
}
// Missing default `hosts` are merged with the existing ones:
if (Array.isArray(defaults.hosts)) {
const hosts = Array.isArray(this.hosts) ? this.hosts : [];
const dhHosts = defaults.hosts.filter(d => d && typeof d === 'object') as IHost[];
dhHosts.forEach(dh => {
const dhName = hasText(dh.name) ? dh.name!.trim() : undefined;
const h: IHost = {name: dhName, port: dh.port, type: dh.type};
let found = false;
for (let i = 0; i < hosts.length; i++) {
const thisHost = fullHostName(hosts[i]), defHost = fullHostName(h);
if (thisHost.toLowerCase() === defHost.toLowerCase()) {
found = true;
break;
}
}
if (!found) {
const obj: IParsedHost = {};
if (h.name) {
if (h.type && h.type in HostType) {
obj.name = h.name;
obj.type = h.type;
} else {
const t = parseHost(h.name, true);
if (t) {
obj.name = t.name;
obj.type = t.type;
}
}
}
const p = h.port;
if (typeof p === 'number' && p > 0 && p < 65536) {
obj.port = p;
}
if (obj.name || obj.port) {
Object.defineProperty(obj, 'toString', {
value: (options: IEncodingOptions) => fullHostName(obj, options)
});
hosts.push(obj);
}
}
});
if (hosts.length) {
this.hosts = hosts;
}
}
if (!('user' in this) && hasText(defaults.user)) {
this.user = defaults.user!.trim();
}
if (!('password' in this) && hasText(defaults.password)) {
this.password = defaults.password!.trim();
}
// Since the order of `path` segments is usually important, we set default
// `path` segments as they are, but only when they are missing completely:
if (!('path' in this) && Array.isArray(defaults.path)) {
const s = defaults.path.filter(hasText);
if (s.length) {
this.path = s;
}
}
// Missing default `params` are merged with the existing ones:
if (defaults.params && typeof defaults.params === 'object') {
const keys = Object.keys(defaults.params);
if (keys.length) {
if (this.params && typeof this.params === 'object') {
for (const a in defaults.params) {
if (!(a in this.params)) {
this.params[a] = defaults.params[a];
}
}
} else {
this.params = {};
for (const b in defaults.params) {
this.params[b] = defaults.params[b];
}
}
}
}
return this;
}
}
(function () {
// hiding prototype methods, to keep the type signature clean:
['setDefaults', 'toString'].forEach(prop => {
const desc = <PropertyDescriptor>Object.getOwnPropertyDescriptor(ConnectionString.prototype, prop);
desc.enumerable = false;
Object.defineProperty(ConnectionString.prototype, prop, desc);
});
setupCustomInspect(ConnectionString);
})();