This repository has been archived by the owner on Jun 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 146
/
UrlBuilder.js
216 lines (189 loc) · 5.55 KB
/
UrlBuilder.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
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
/*
* Copyright 2012-2016 the original author or authors
* @license MIT, see LICENSE.txt for details
*
* @author Scott Andrews
*/
'use strict';
var mixin, xWWWFormURLEncoder, origin, urlRE, absoluteUrlRE, fullyQualifiedUrlRE;
mixin = require('./util/mixin');
xWWWFormURLEncoder = require('./mime/type/application/x-www-form-urlencoded');
urlRE = /([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i;
absoluteUrlRE = /^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i;
fullyQualifiedUrlRE = /([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i;
/**
* Apply params to the template to create a URL.
*
* Parameters that are not applied directly to the template, are appended
* to the URL as query string parameters.
*
* @param {string} template the URI template
* @param {Object} params parameters to apply to the template
* @return {string} the resulting URL
*/
function buildUrl(template, params) {
// internal builder to convert template with params.
var url, name, queryStringParams, queryString, re;
url = template;
queryStringParams = {};
if (params) {
for (name in params) {
/*jshint forin:false */
re = new RegExp('\\{' + name + '\\}');
if (re.test(url)) {
url = url.replace(re, encodeURIComponent(params[name]), 'g');
}
else {
queryStringParams[name] = params[name];
}
}
queryString = xWWWFormURLEncoder.write(queryStringParams);
if (queryString) {
url += url.indexOf('?') === -1 ? '?' : '&';
url += queryString;
}
}
return url;
}
function startsWith(str, test) {
return str.indexOf(test) === 0;
}
/**
* Create a new URL Builder
*
* @param {string|UrlBuilder} template the base template to build from, may be another UrlBuilder
* @param {Object} [params] base parameters
* @constructor
*/
function UrlBuilder(template, params) {
if (!(this instanceof UrlBuilder)) {
// invoke as a constructor
return new UrlBuilder(template, params);
}
if (template instanceof UrlBuilder) {
this._template = template.template;
this._params = mixin({}, this._params, params);
}
else {
this._template = (template || '').toString();
this._params = params || {};
}
}
UrlBuilder.prototype = {
/**
* Create a new UrlBuilder instance that extends the current builder.
* The current builder is unmodified.
*
* @param {string} [template] URL template to append to the current template
* @param {Object} [params] params to combine with current params. New params override existing params
* @return {UrlBuilder} the new builder
*/
append: function (template, params) {
// TODO consider query strings and fragments
return new UrlBuilder(this._template + template, mixin({}, this._params, params));
},
/**
* Create a new UrlBuilder with a fully qualified URL based on the
* window's location or base href and the current templates relative URL.
*
* Path variables are preserved.
*
* *Browser only*
*
* @return {UrlBuilder} the fully qualified URL template
*/
fullyQualify: function () {
if (typeof location === 'undefined') { return this; }
if (this.isFullyQualified()) { return this; }
var template = this._template;
if (startsWith(template, '//')) {
template = origin.protocol + template;
}
else if (startsWith(template, '/')) {
template = origin.origin + template;
}
else if (!this.isAbsolute()) {
template = origin.origin + origin.pathname.substring(0, origin.pathname.lastIndexOf('/') + 1);
}
if (template.indexOf('/', 8) === -1) {
// default the pathname to '/'
template = template + '/';
}
return new UrlBuilder(template, this._params);
},
/**
* True if the URL is absolute
*
* @return {boolean}
*/
isAbsolute: function () {
return absoluteUrlRE.test(this.build());
},
/**
* True if the URL is fully qualified
*
* @return {boolean}
*/
isFullyQualified: function () {
return fullyQualifiedUrlRE.test(this.build());
},
/**
* True if the URL is cross origin. The protocol, host and port must not be
* the same in order to be cross origin,
*
* @return {boolean}
*/
isCrossOrigin: function () {
if (!origin) {
return true;
}
var url = this.parts();
return url.protocol !== origin.protocol ||
url.hostname !== origin.hostname ||
url.port !== origin.port;
},
/**
* Split a URL into its consituent parts following the naming convention of
* 'window.location'. One difference is that the port will contain the
* protocol default if not specified.
*
* @see https://developer.mozilla.org/en-US/docs/DOM/window.location
*
* @returns {Object} a 'window.location'-like object
*/
parts: function () {
/*jshint maxcomplexity:20 */
var url, parts;
url = this.fullyQualify().build().match(urlRE);
parts = {
href: url[0],
protocol: url[1],
host: url[3] || '',
hostname: url[4] || '',
port: url[6],
pathname: url[7] || '',
search: url[8] || '',
hash: url[9] || ''
};
parts.origin = parts.protocol + '//' + parts.host;
parts.port = parts.port || (parts.protocol === 'https:' ? '443' : parts.protocol === 'http:' ? '80' : '');
return parts;
},
/**
* Expand the template replacing path variables with parameters
*
* @param {Object} [params] params to combine with current params. New params override existing params
* @return {string} the expanded URL
*/
build: function (params) {
return buildUrl(this._template, mixin({}, this._params, params));
},
/**
* @see build
*/
toString: function () {
return this.build();
}
};
origin = typeof location !== 'undefined' ? new UrlBuilder(location.href).parts() : void 0;
module.exports = UrlBuilder;