Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80529 views
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
var punycode = require('punycode');
23
24
exports.parse = urlParse;
25
exports.resolve = urlResolve;
26
exports.resolveObject = urlResolveObject;
27
exports.format = urlFormat;
28
29
exports.Url = Url;
30
31
function Url() {
32
this.protocol = null;
33
this.slashes = null;
34
this.auth = null;
35
this.host = null;
36
this.port = null;
37
this.hostname = null;
38
this.hash = null;
39
this.search = null;
40
this.query = null;
41
this.pathname = null;
42
this.path = null;
43
this.href = null;
44
}
45
46
// Reference: RFC 3986, RFC 1808, RFC 2396
47
48
// define these here so at least they only have to be
49
// compiled once on the first module load.
50
var protocolPattern = /^([a-z0-9.+-]+:)/i,
51
portPattern = /:[0-9]*$/,
52
53
// RFC 2396: characters reserved for delimiting URLs.
54
// We actually just auto-escape these.
55
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
56
57
// RFC 2396: characters not allowed for various reasons.
58
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
59
60
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
61
autoEscape = ['\''].concat(unwise),
62
// Characters that are never ever allowed in a hostname.
63
// Note that any invalid chars are also handled, but these
64
// are the ones that are *expected* to be seen, so we fast-path
65
// them.
66
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
67
hostEndingChars = ['/', '?', '#'],
68
hostnameMaxLen = 255,
69
hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
70
hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
71
// protocols that can allow "unsafe" and "unwise" chars.
72
unsafeProtocol = {
73
'javascript': true,
74
'javascript:': true
75
},
76
// protocols that never have a hostname.
77
hostlessProtocol = {
78
'javascript': true,
79
'javascript:': true
80
},
81
// protocols that always contain a // bit.
82
slashedProtocol = {
83
'http': true,
84
'https': true,
85
'ftp': true,
86
'gopher': true,
87
'file': true,
88
'http:': true,
89
'https:': true,
90
'ftp:': true,
91
'gopher:': true,
92
'file:': true
93
},
94
querystring = require('querystring');
95
96
function urlParse(url, parseQueryString, slashesDenoteHost) {
97
if (url && isObject(url) && url instanceof Url) return url;
98
99
var u = new Url;
100
u.parse(url, parseQueryString, slashesDenoteHost);
101
return u;
102
}
103
104
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
105
if (!isString(url)) {
106
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
107
}
108
109
var rest = url;
110
111
// trim before proceeding.
112
// This is to support parse stuff like " http://foo.com \n"
113
rest = rest.trim();
114
115
var proto = protocolPattern.exec(rest);
116
if (proto) {
117
proto = proto[0];
118
var lowerProto = proto.toLowerCase();
119
this.protocol = lowerProto;
120
rest = rest.substr(proto.length);
121
}
122
123
// figure out if it's got a host
124
// user@server is *always* interpreted as a hostname, and url
125
// resolution will treat //foo/bar as host=foo,path=bar because that's
126
// how the browser resolves relative URLs.
127
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
128
var slashes = rest.substr(0, 2) === '//';
129
if (slashes && !(proto && hostlessProtocol[proto])) {
130
rest = rest.substr(2);
131
this.slashes = true;
132
}
133
}
134
135
if (!hostlessProtocol[proto] &&
136
(slashes || (proto && !slashedProtocol[proto]))) {
137
138
// there's a hostname.
139
// the first instance of /, ?, ;, or # ends the host.
140
//
141
// If there is an @ in the hostname, then non-host chars *are* allowed
142
// to the left of the last @ sign, unless some host-ending character
143
// comes *before* the @-sign.
144
// URLs are obnoxious.
145
//
146
// ex:
147
// http://a@b@c/ => user:a@b host:c
148
// http://a@b?@c => user:a host:c path:/?@c
149
150
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
151
// Review our test case against browsers more comprehensively.
152
153
// find the first instance of any hostEndingChars
154
var hostEnd = -1;
155
for (var i = 0; i < hostEndingChars.length; i++) {
156
var hec = rest.indexOf(hostEndingChars[i]);
157
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
158
hostEnd = hec;
159
}
160
161
// at this point, either we have an explicit point where the
162
// auth portion cannot go past, or the last @ char is the decider.
163
var auth, atSign;
164
if (hostEnd === -1) {
165
// atSign can be anywhere.
166
atSign = rest.lastIndexOf('@');
167
} else {
168
// atSign must be in auth portion.
169
// http://a@b/c@d => host:b auth:a path:/c@d
170
atSign = rest.lastIndexOf('@', hostEnd);
171
}
172
173
// Now we have a portion which is definitely the auth.
174
// Pull that off.
175
if (atSign !== -1) {
176
auth = rest.slice(0, atSign);
177
rest = rest.slice(atSign + 1);
178
this.auth = decodeURIComponent(auth);
179
}
180
181
// the host is the remaining to the left of the first non-host char
182
hostEnd = -1;
183
for (var i = 0; i < nonHostChars.length; i++) {
184
var hec = rest.indexOf(nonHostChars[i]);
185
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
186
hostEnd = hec;
187
}
188
// if we still have not hit it, then the entire thing is a host.
189
if (hostEnd === -1)
190
hostEnd = rest.length;
191
192
this.host = rest.slice(0, hostEnd);
193
rest = rest.slice(hostEnd);
194
195
// pull out port.
196
this.parseHost();
197
198
// we've indicated that there is a hostname,
199
// so even if it's empty, it has to be present.
200
this.hostname = this.hostname || '';
201
202
// if hostname begins with [ and ends with ]
203
// assume that it's an IPv6 address.
204
var ipv6Hostname = this.hostname[0] === '[' &&
205
this.hostname[this.hostname.length - 1] === ']';
206
207
// validate a little.
208
if (!ipv6Hostname) {
209
var hostparts = this.hostname.split(/\./);
210
for (var i = 0, l = hostparts.length; i < l; i++) {
211
var part = hostparts[i];
212
if (!part) continue;
213
if (!part.match(hostnamePartPattern)) {
214
var newpart = '';
215
for (var j = 0, k = part.length; j < k; j++) {
216
if (part.charCodeAt(j) > 127) {
217
// we replace non-ASCII char with a temporary placeholder
218
// we need this to make sure size of hostname is not
219
// broken by replacing non-ASCII by nothing
220
newpart += 'x';
221
} else {
222
newpart += part[j];
223
}
224
}
225
// we test again with ASCII char only
226
if (!newpart.match(hostnamePartPattern)) {
227
var validParts = hostparts.slice(0, i);
228
var notHost = hostparts.slice(i + 1);
229
var bit = part.match(hostnamePartStart);
230
if (bit) {
231
validParts.push(bit[1]);
232
notHost.unshift(bit[2]);
233
}
234
if (notHost.length) {
235
rest = '/' + notHost.join('.') + rest;
236
}
237
this.hostname = validParts.join('.');
238
break;
239
}
240
}
241
}
242
}
243
244
if (this.hostname.length > hostnameMaxLen) {
245
this.hostname = '';
246
} else {
247
// hostnames are always lower case.
248
this.hostname = this.hostname.toLowerCase();
249
}
250
251
if (!ipv6Hostname) {
252
// IDNA Support: Returns a puny coded representation of "domain".
253
// It only converts the part of the domain name that
254
// has non ASCII characters. I.e. it dosent matter if
255
// you call it with a domain that already is in ASCII.
256
var domainArray = this.hostname.split('.');
257
var newOut = [];
258
for (var i = 0; i < domainArray.length; ++i) {
259
var s = domainArray[i];
260
newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
261
'xn--' + punycode.encode(s) : s);
262
}
263
this.hostname = newOut.join('.');
264
}
265
266
var p = this.port ? ':' + this.port : '';
267
var h = this.hostname || '';
268
this.host = h + p;
269
this.href += this.host;
270
271
// strip [ and ] from the hostname
272
// the host field still retains them, though
273
if (ipv6Hostname) {
274
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
275
if (rest[0] !== '/') {
276
rest = '/' + rest;
277
}
278
}
279
}
280
281
// now rest is set to the post-host stuff.
282
// chop off any delim chars.
283
if (!unsafeProtocol[lowerProto]) {
284
285
// First, make 100% sure that any "autoEscape" chars get
286
// escaped, even if encodeURIComponent doesn't think they
287
// need to be.
288
for (var i = 0, l = autoEscape.length; i < l; i++) {
289
var ae = autoEscape[i];
290
var esc = encodeURIComponent(ae);
291
if (esc === ae) {
292
esc = escape(ae);
293
}
294
rest = rest.split(ae).join(esc);
295
}
296
}
297
298
299
// chop off from the tail first.
300
var hash = rest.indexOf('#');
301
if (hash !== -1) {
302
// got a fragment string.
303
this.hash = rest.substr(hash);
304
rest = rest.slice(0, hash);
305
}
306
var qm = rest.indexOf('?');
307
if (qm !== -1) {
308
this.search = rest.substr(qm);
309
this.query = rest.substr(qm + 1);
310
if (parseQueryString) {
311
this.query = querystring.parse(this.query);
312
}
313
rest = rest.slice(0, qm);
314
} else if (parseQueryString) {
315
// no query string, but parseQueryString still requested
316
this.search = '';
317
this.query = {};
318
}
319
if (rest) this.pathname = rest;
320
if (slashedProtocol[lowerProto] &&
321
this.hostname && !this.pathname) {
322
this.pathname = '/';
323
}
324
325
//to support http.request
326
if (this.pathname || this.search) {
327
var p = this.pathname || '';
328
var s = this.search || '';
329
this.path = p + s;
330
}
331
332
// finally, reconstruct the href based on what has been validated.
333
this.href = this.format();
334
return this;
335
};
336
337
// format a parsed object into a url string
338
function urlFormat(obj) {
339
// ensure it's an object, and not a string url.
340
// If it's an obj, this is a no-op.
341
// this way, you can call url_format() on strings
342
// to clean up potentially wonky urls.
343
if (isString(obj)) obj = urlParse(obj);
344
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
345
return obj.format();
346
}
347
348
Url.prototype.format = function() {
349
var auth = this.auth || '';
350
if (auth) {
351
auth = encodeURIComponent(auth);
352
auth = auth.replace(/%3A/i, ':');
353
auth += '@';
354
}
355
356
var protocol = this.protocol || '',
357
pathname = this.pathname || '',
358
hash = this.hash || '',
359
host = false,
360
query = '';
361
362
if (this.host) {
363
host = auth + this.host;
364
} else if (this.hostname) {
365
host = auth + (this.hostname.indexOf(':') === -1 ?
366
this.hostname :
367
'[' + this.hostname + ']');
368
if (this.port) {
369
host += ':' + this.port;
370
}
371
}
372
373
if (this.query &&
374
isObject(this.query) &&
375
Object.keys(this.query).length) {
376
query = querystring.stringify(this.query);
377
}
378
379
var search = this.search || (query && ('?' + query)) || '';
380
381
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
382
383
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
384
// unless they had them to begin with.
385
if (this.slashes ||
386
(!protocol || slashedProtocol[protocol]) && host !== false) {
387
host = '//' + (host || '');
388
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
389
} else if (!host) {
390
host = '';
391
}
392
393
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
394
if (search && search.charAt(0) !== '?') search = '?' + search;
395
396
pathname = pathname.replace(/[?#]/g, function(match) {
397
return encodeURIComponent(match);
398
});
399
search = search.replace('#', '%23');
400
401
return protocol + host + pathname + search + hash;
402
};
403
404
function urlResolve(source, relative) {
405
return urlParse(source, false, true).resolve(relative);
406
}
407
408
Url.prototype.resolve = function(relative) {
409
return this.resolveObject(urlParse(relative, false, true)).format();
410
};
411
412
function urlResolveObject(source, relative) {
413
if (!source) return relative;
414
return urlParse(source, false, true).resolveObject(relative);
415
}
416
417
Url.prototype.resolveObject = function(relative) {
418
if (isString(relative)) {
419
var rel = new Url();
420
rel.parse(relative, false, true);
421
relative = rel;
422
}
423
424
var result = new Url();
425
Object.keys(this).forEach(function(k) {
426
result[k] = this[k];
427
}, this);
428
429
// hash is always overridden, no matter what.
430
// even href="" will remove it.
431
result.hash = relative.hash;
432
433
// if the relative url is empty, then there's nothing left to do here.
434
if (relative.href === '') {
435
result.href = result.format();
436
return result;
437
}
438
439
// hrefs like //foo/bar always cut to the protocol.
440
if (relative.slashes && !relative.protocol) {
441
// take everything except the protocol from relative
442
Object.keys(relative).forEach(function(k) {
443
if (k !== 'protocol')
444
result[k] = relative[k];
445
});
446
447
//urlParse appends trailing / to urls like http://www.example.com
448
if (slashedProtocol[result.protocol] &&
449
result.hostname && !result.pathname) {
450
result.path = result.pathname = '/';
451
}
452
453
result.href = result.format();
454
return result;
455
}
456
457
if (relative.protocol && relative.protocol !== result.protocol) {
458
// if it's a known url protocol, then changing
459
// the protocol does weird things
460
// first, if it's not file:, then we MUST have a host,
461
// and if there was a path
462
// to begin with, then we MUST have a path.
463
// if it is file:, then the host is dropped,
464
// because that's known to be hostless.
465
// anything else is assumed to be absolute.
466
if (!slashedProtocol[relative.protocol]) {
467
Object.keys(relative).forEach(function(k) {
468
result[k] = relative[k];
469
});
470
result.href = result.format();
471
return result;
472
}
473
474
result.protocol = relative.protocol;
475
if (!relative.host && !hostlessProtocol[relative.protocol]) {
476
var relPath = (relative.pathname || '').split('/');
477
while (relPath.length && !(relative.host = relPath.shift()));
478
if (!relative.host) relative.host = '';
479
if (!relative.hostname) relative.hostname = '';
480
if (relPath[0] !== '') relPath.unshift('');
481
if (relPath.length < 2) relPath.unshift('');
482
result.pathname = relPath.join('/');
483
} else {
484
result.pathname = relative.pathname;
485
}
486
result.search = relative.search;
487
result.query = relative.query;
488
result.host = relative.host || '';
489
result.auth = relative.auth;
490
result.hostname = relative.hostname || relative.host;
491
result.port = relative.port;
492
// to support http.request
493
if (result.pathname || result.search) {
494
var p = result.pathname || '';
495
var s = result.search || '';
496
result.path = p + s;
497
}
498
result.slashes = result.slashes || relative.slashes;
499
result.href = result.format();
500
return result;
501
}
502
503
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
504
isRelAbs = (
505
relative.host ||
506
relative.pathname && relative.pathname.charAt(0) === '/'
507
),
508
mustEndAbs = (isRelAbs || isSourceAbs ||
509
(result.host && relative.pathname)),
510
removeAllDots = mustEndAbs,
511
srcPath = result.pathname && result.pathname.split('/') || [],
512
relPath = relative.pathname && relative.pathname.split('/') || [],
513
psychotic = result.protocol && !slashedProtocol[result.protocol];
514
515
// if the url is a non-slashed url, then relative
516
// links like ../.. should be able
517
// to crawl up to the hostname, as well. This is strange.
518
// result.protocol has already been set by now.
519
// Later on, put the first path part into the host field.
520
if (psychotic) {
521
result.hostname = '';
522
result.port = null;
523
if (result.host) {
524
if (srcPath[0] === '') srcPath[0] = result.host;
525
else srcPath.unshift(result.host);
526
}
527
result.host = '';
528
if (relative.protocol) {
529
relative.hostname = null;
530
relative.port = null;
531
if (relative.host) {
532
if (relPath[0] === '') relPath[0] = relative.host;
533
else relPath.unshift(relative.host);
534
}
535
relative.host = null;
536
}
537
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
538
}
539
540
if (isRelAbs) {
541
// it's absolute.
542
result.host = (relative.host || relative.host === '') ?
543
relative.host : result.host;
544
result.hostname = (relative.hostname || relative.hostname === '') ?
545
relative.hostname : result.hostname;
546
result.search = relative.search;
547
result.query = relative.query;
548
srcPath = relPath;
549
// fall through to the dot-handling below.
550
} else if (relPath.length) {
551
// it's relative
552
// throw away the existing file, and take the new path instead.
553
if (!srcPath) srcPath = [];
554
srcPath.pop();
555
srcPath = srcPath.concat(relPath);
556
result.search = relative.search;
557
result.query = relative.query;
558
} else if (!isNullOrUndefined(relative.search)) {
559
// just pull out the search.
560
// like href='?foo'.
561
// Put this after the other two cases because it simplifies the booleans
562
if (psychotic) {
563
result.hostname = result.host = srcPath.shift();
564
//occationaly the auth can get stuck only in host
565
//this especialy happens in cases like
566
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
567
var authInHost = result.host && result.host.indexOf('@') > 0 ?
568
result.host.split('@') : false;
569
if (authInHost) {
570
result.auth = authInHost.shift();
571
result.host = result.hostname = authInHost.shift();
572
}
573
}
574
result.search = relative.search;
575
result.query = relative.query;
576
//to support http.request
577
if (!isNull(result.pathname) || !isNull(result.search)) {
578
result.path = (result.pathname ? result.pathname : '') +
579
(result.search ? result.search : '');
580
}
581
result.href = result.format();
582
return result;
583
}
584
585
if (!srcPath.length) {
586
// no path at all. easy.
587
// we've already handled the other stuff above.
588
result.pathname = null;
589
//to support http.request
590
if (result.search) {
591
result.path = '/' + result.search;
592
} else {
593
result.path = null;
594
}
595
result.href = result.format();
596
return result;
597
}
598
599
// if a url ENDs in . or .., then it must get a trailing slash.
600
// however, if it ends in anything else non-slashy,
601
// then it must NOT get a trailing slash.
602
var last = srcPath.slice(-1)[0];
603
var hasTrailingSlash = (
604
(result.host || relative.host) && (last === '.' || last === '..') ||
605
last === '');
606
607
// strip single dots, resolve double dots to parent dir
608
// if the path tries to go above the root, `up` ends up > 0
609
var up = 0;
610
for (var i = srcPath.length; i >= 0; i--) {
611
last = srcPath[i];
612
if (last == '.') {
613
srcPath.splice(i, 1);
614
} else if (last === '..') {
615
srcPath.splice(i, 1);
616
up++;
617
} else if (up) {
618
srcPath.splice(i, 1);
619
up--;
620
}
621
}
622
623
// if the path is allowed to go above the root, restore leading ..s
624
if (!mustEndAbs && !removeAllDots) {
625
for (; up--; up) {
626
srcPath.unshift('..');
627
}
628
}
629
630
if (mustEndAbs && srcPath[0] !== '' &&
631
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
632
srcPath.unshift('');
633
}
634
635
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
636
srcPath.push('');
637
}
638
639
var isAbsolute = srcPath[0] === '' ||
640
(srcPath[0] && srcPath[0].charAt(0) === '/');
641
642
// put the host back
643
if (psychotic) {
644
result.hostname = result.host = isAbsolute ? '' :
645
srcPath.length ? srcPath.shift() : '';
646
//occationaly the auth can get stuck only in host
647
//this especialy happens in cases like
648
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
649
var authInHost = result.host && result.host.indexOf('@') > 0 ?
650
result.host.split('@') : false;
651
if (authInHost) {
652
result.auth = authInHost.shift();
653
result.host = result.hostname = authInHost.shift();
654
}
655
}
656
657
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
658
659
if (mustEndAbs && !isAbsolute) {
660
srcPath.unshift('');
661
}
662
663
if (!srcPath.length) {
664
result.pathname = null;
665
result.path = null;
666
} else {
667
result.pathname = srcPath.join('/');
668
}
669
670
//to support request.http
671
if (!isNull(result.pathname) || !isNull(result.search)) {
672
result.path = (result.pathname ? result.pathname : '') +
673
(result.search ? result.search : '');
674
}
675
result.auth = relative.auth || result.auth;
676
result.slashes = result.slashes || relative.slashes;
677
result.href = result.format();
678
return result;
679
};
680
681
Url.prototype.parseHost = function() {
682
var host = this.host;
683
var port = portPattern.exec(host);
684
if (port) {
685
port = port[0];
686
if (port !== ':') {
687
this.port = port.substr(1);
688
}
689
host = host.substr(0, host.length - port.length);
690
}
691
if (host) this.hostname = host;
692
};
693
694
function isString(arg) {
695
return typeof arg === "string";
696
}
697
698
function isObject(arg) {
699
return typeof arg === 'object' && arg !== null;
700
}
701
702
function isNull(arg) {
703
return arg === null;
704
}
705
function isNullOrUndefined(arg) {
706
return arg == null;
707
}
708
709