Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/third_party/closure/goog/uri/utils.js
4505 views
1
/**
2
* @license
3
* Copyright The Closure Library Authors.
4
* SPDX-License-Identifier: Apache-2.0
5
*/
6
7
/**
8
* @fileoverview Simple utilities for dealing with URI strings.
9
*
10
* This package is deprecated in favour of the Closure URL package (goog.url)
11
* when manipulating URIs for use by a browser. This package uses regular
12
* expressions to parse a potential URI which can fall out of sync with how a
13
* browser will actually interpret the URI. See
14
* `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify
15
* URIs that should instead be parsed using the URL package.
16
*
17
* This is intended to be a lightweight alternative to constructing goog.Uri
18
* objects. Whereas goog.Uri adds several kilobytes to the binary regardless
19
* of how much of its functionality you use, this is designed to be a set of
20
* mostly-independent utilities so that the compiler includes only what is
21
* necessary for the task. Estimated savings of porting is 5k pre-gzip and
22
* 1.5k post-gzip. To ensure the savings remain, future developers should
23
* avoid adding new functionality to existing functions, but instead create
24
* new ones and factor out shared code.
25
*
26
* Many of these utilities have limited functionality, tailored to common
27
* cases. The query parameter utilities assume that the parameter keys are
28
* already encoded, since most keys are compile-time alphanumeric strings. The
29
* query parameter mutation utilities also do not tolerate fragment identifiers.
30
*
31
* By design, these functions can be slower than goog.Uri equivalents.
32
* Repeated calls to some of functions may be quadratic in behavior for IE,
33
* although the effect is somewhat limited given the 2kb limit.
34
*
35
* One advantage of the limited functionality here is that this approach is
36
* less sensitive to differences in URI encodings than goog.Uri, since these
37
* functions operate on strings directly, rather than decoding them and
38
* then re-encoding.
39
*
40
* Uses features of RFC 3986 for parsing/formatting URIs:
41
* http://www.ietf.org/rfc/rfc3986.txt
42
*/
43
44
goog.provide('goog.uri.utils');
45
goog.provide('goog.uri.utils.ComponentIndex');
46
goog.provide('goog.uri.utils.QueryArray');
47
goog.provide('goog.uri.utils.QueryValue');
48
goog.provide('goog.uri.utils.StandardQueryParam');
49
50
goog.require('goog.asserts');
51
goog.require('goog.string');
52
53
54
/**
55
* Character codes inlined to avoid object allocations due to charCode.
56
* @enum {number}
57
* @private
58
*/
59
goog.uri.utils.CharCode_ = {
60
AMPERSAND: 38,
61
EQUAL: 61,
62
HASH: 35,
63
QUESTION: 63
64
};
65
66
67
/**
68
* Builds a URI string from already-encoded parts.
69
*
70
* No encoding is performed. Any component may be omitted as either null or
71
* undefined.
72
*
73
* @param {?string=} opt_scheme The scheme such as 'http'.
74
* @param {?string=} opt_userInfo The user name before the '@'.
75
* @param {?string=} opt_domain The domain such as 'www.google.com', already
76
* URI-encoded.
77
* @param {(string|number|null)=} opt_port The port number.
78
* @param {?string=} opt_path The path, already URI-encoded. If it is not
79
* empty, it must begin with a slash.
80
* @param {?string=} opt_queryData The URI-encoded query data.
81
* @param {?string=} opt_fragment The URI-encoded fragment identifier.
82
* @return {string} The fully combined URI.
83
*/
84
goog.uri.utils.buildFromEncodedParts = function(
85
opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,
86
opt_fragment) {
87
'use strict';
88
var out = '';
89
90
if (opt_scheme) {
91
out += opt_scheme + ':';
92
}
93
94
if (opt_domain) {
95
out += '//';
96
97
if (opt_userInfo) {
98
out += opt_userInfo + '@';
99
}
100
101
out += opt_domain;
102
103
if (opt_port) {
104
out += ':' + opt_port;
105
}
106
}
107
108
if (opt_path) {
109
out += opt_path;
110
}
111
112
if (opt_queryData) {
113
out += '?' + opt_queryData;
114
}
115
116
if (opt_fragment) {
117
out += '#' + opt_fragment;
118
}
119
120
return out;
121
};
122
123
124
/**
125
* A regular expression for breaking a URI into its component parts.
126
*
127
* {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B
128
* As the "first-match-wins" algorithm is identical to the "greedy"
129
* disambiguation method used by POSIX regular expressions, it is natural and
130
* commonplace to use a regular expression for parsing the potential five
131
* components of a URI reference.
132
*
133
* The following line is the regular expression for breaking-down a
134
* well-formed URI reference into its components.
135
*
136
* <pre>
137
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
138
* 12 3 4 5 6 7 8 9
139
* </pre>
140
*
141
* The numbers in the second line above are only to assist readability; they
142
* indicate the reference points for each subexpression (i.e., each paired
143
* parenthesis). We refer to the value matched for subexpression <n> as $<n>.
144
* For example, matching the above expression to
145
* <pre>
146
* http://www.ics.uci.edu/pub/ietf/uri/#Related
147
* </pre>
148
* results in the following subexpression matches:
149
* <pre>
150
* $1 = http:
151
* $2 = http
152
* $3 = //www.ics.uci.edu
153
* $4 = www.ics.uci.edu
154
* $5 = /pub/ietf/uri/
155
* $6 = <undefined>
156
* $7 = <undefined>
157
* $8 = #Related
158
* $9 = Related
159
* </pre>
160
* where <undefined> indicates that the component is not present, as is the
161
* case for the query component in the above example. Therefore, we can
162
* determine the value of the five components as
163
* <pre>
164
* scheme = $2
165
* authority = $4
166
* path = $5
167
* query = $7
168
* fragment = $9
169
* </pre>
170
*
171
* The regular expression has been modified slightly to expose the
172
* userInfo, domain, and port separately from the authority.
173
* The modified version yields
174
* <pre>
175
* $1 = http scheme
176
* $2 = <undefined> userInfo -\
177
* $3 = www.ics.uci.edu domain | authority
178
* $4 = <undefined> port -/
179
* $5 = /pub/ietf/uri/ path
180
* $6 = <undefined> query without ?
181
* $7 = Related fragment without #
182
* </pre>
183
*
184
* TODO(user): separate out the authority terminating characters once this
185
* file is moved to ES6.
186
* @type {!RegExp}
187
* @private
188
*/
189
goog.uri.utils.splitRe_ = new RegExp(
190
'^' + // Anchor against the entire string.
191
'(?:' +
192
'([^:/?#.]+)' + // scheme - ignore special characters
193
// used by other URL parts such as :,
194
// ?, /, #, and .
195
':)?' +
196
'(?://' +
197
'(?:([^\\\\/?#]*)@)?' + // userInfo
198
'([^\\\\/?#]*?)' + // domain
199
'(?::([0-9]+))?' + // port
200
'(?=[\\\\/?#]|$)' + // authority-terminating character.
201
')?' +
202
'([^?#]+)?' + // path
203
'(?:\\?([^#]*))?' + // query
204
'(?:#([\\s\\S]*))?' + // fragment. Can't use '.*' with 's' flag as Firefox
205
// doesn't support the flag, and can't use an
206
// "everything set" ([^]) as IE10 doesn't match any
207
// characters with it.
208
'$');
209
210
211
/**
212
* The index of each URI component in the return value of goog.uri.utils.split.
213
* @enum {number}
214
*/
215
goog.uri.utils.ComponentIndex = {
216
SCHEME: 1,
217
USER_INFO: 2,
218
DOMAIN: 3,
219
PORT: 4,
220
PATH: 5,
221
QUERY_DATA: 6,
222
FRAGMENT: 7
223
};
224
225
/**
226
* @type {?function(string)}
227
* @private
228
*/
229
goog.uri.utils.urlPackageSupportLoggingHandler_ = null;
230
231
/**
232
* @param {?function(string)} handler The handler function to call when a URI
233
* with a protocol that is better supported by the Closure URL package is
234
* detected.
235
*/
236
goog.uri.utils.setUrlPackageSupportLoggingHandler = function(handler) {
237
'use strict';
238
goog.uri.utils.urlPackageSupportLoggingHandler_ = handler;
239
};
240
241
/**
242
* Splits a URI into its component parts.
243
*
244
* Each component can be accessed via the component indices; for example:
245
* <pre>
246
* goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];
247
* </pre>
248
*
249
* @param {string} uri The URI string to examine.
250
* @return {!Array<string|undefined>} Each component still URI-encoded.
251
* Each component that is present will contain the encoded value, whereas
252
* components that are not present will be undefined or empty, depending
253
* on the browser's regular expression implementation. Never null, since
254
* arbitrary strings may still look like path names.
255
*/
256
goog.uri.utils.split = function(uri) {
257
'use strict';
258
// See @return comment -- never null.
259
var result = /** @type {!Array<string|undefined>} */ (
260
uri.match(goog.uri.utils.splitRe_));
261
if (goog.uri.utils.urlPackageSupportLoggingHandler_ &&
262
['http', 'https', 'ws', 'wss',
263
'ftp'].indexOf(result[goog.uri.utils.ComponentIndex.SCHEME]) >= 0) {
264
goog.uri.utils.urlPackageSupportLoggingHandler_(uri);
265
}
266
return result;
267
};
268
269
270
/**
271
* @param {?string} uri A possibly null string.
272
* @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986
273
* reserved characters will not be removed.
274
* @return {?string} The string URI-decoded, or null if uri is null.
275
* @private
276
*/
277
goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {
278
'use strict';
279
if (!uri) {
280
return uri;
281
}
282
283
return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);
284
};
285
286
287
/**
288
* Gets a URI component by index.
289
*
290
* It is preferred to use the getPathEncoded() variety of functions ahead,
291
* since they are more readable.
292
*
293
* @param {goog.uri.utils.ComponentIndex} componentIndex The component index.
294
* @param {string} uri The URI to examine.
295
* @return {?string} The still-encoded component, or null if the component
296
* is not present.
297
* @private
298
*/
299
goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {
300
'use strict';
301
// Convert undefined, null, and empty string into null.
302
return goog.uri.utils.split(uri)[componentIndex] || null;
303
};
304
305
306
/**
307
* @param {string} uri The URI to examine.
308
* @return {?string} The protocol or scheme, or null if none. Does not
309
* include trailing colons or slashes.
310
*/
311
goog.uri.utils.getScheme = function(uri) {
312
'use strict';
313
return goog.uri.utils.getComponentByIndex_(
314
goog.uri.utils.ComponentIndex.SCHEME, uri);
315
};
316
317
318
/**
319
* Gets the effective scheme for the URL. If the URL is relative then the
320
* scheme is derived from the page's location.
321
* @param {string} uri The URI to examine.
322
* @return {string} The protocol or scheme, always lower case.
323
*/
324
goog.uri.utils.getEffectiveScheme = function(uri) {
325
'use strict';
326
var scheme = goog.uri.utils.getScheme(uri);
327
if (!scheme && goog.global.self && goog.global.self.location) {
328
var protocol = goog.global.self.location.protocol;
329
scheme = protocol.slice(0, -1);
330
}
331
// NOTE: When called from a web worker in Firefox 3.5, location may be null.
332
// All other browsers with web workers support self.location from the worker.
333
return scheme ? scheme.toLowerCase() : '';
334
};
335
336
337
/**
338
* @param {string} uri The URI to examine.
339
* @return {?string} The user name still encoded, or null if none.
340
*/
341
goog.uri.utils.getUserInfoEncoded = function(uri) {
342
'use strict';
343
return goog.uri.utils.getComponentByIndex_(
344
goog.uri.utils.ComponentIndex.USER_INFO, uri);
345
};
346
347
348
/**
349
* @param {string} uri The URI to examine.
350
* @return {?string} The decoded user info, or null if none.
351
*/
352
goog.uri.utils.getUserInfo = function(uri) {
353
'use strict';
354
return goog.uri.utils.decodeIfPossible_(
355
goog.uri.utils.getUserInfoEncoded(uri));
356
};
357
358
359
/**
360
* @param {string} uri The URI to examine.
361
* @return {?string} The domain name still encoded, or null if none.
362
*/
363
goog.uri.utils.getDomainEncoded = function(uri) {
364
'use strict';
365
return goog.uri.utils.getComponentByIndex_(
366
goog.uri.utils.ComponentIndex.DOMAIN, uri);
367
};
368
369
370
/**
371
* @param {string} uri The URI to examine.
372
* @return {?string} The decoded domain, or null if none.
373
*/
374
goog.uri.utils.getDomain = function(uri) {
375
'use strict';
376
return goog.uri.utils.decodeIfPossible_(
377
goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);
378
};
379
380
381
/**
382
* @param {string} uri The URI to examine.
383
* @return {?number} The port number, or null if none.
384
*/
385
goog.uri.utils.getPort = function(uri) {
386
'use strict';
387
// Coerce to a number. If the result of getComponentByIndex_ is null or
388
// non-numeric, the number coersion yields NaN. This will then return
389
// null for all non-numeric cases (though also zero, which isn't a relevant
390
// port number).
391
return Number(
392
goog.uri.utils.getComponentByIndex_(
393
goog.uri.utils.ComponentIndex.PORT, uri)) ||
394
null;
395
};
396
397
398
/**
399
* @param {string} uri The URI to examine.
400
* @return {?string} The path still encoded, or null if none. Includes the
401
* leading slash, if any.
402
*/
403
goog.uri.utils.getPathEncoded = function(uri) {
404
'use strict';
405
return goog.uri.utils.getComponentByIndex_(
406
goog.uri.utils.ComponentIndex.PATH, uri);
407
};
408
409
410
/**
411
* @param {string} uri The URI to examine.
412
* @return {?string} The decoded path, or null if none. Includes the leading
413
* slash, if any.
414
*/
415
goog.uri.utils.getPath = function(uri) {
416
'use strict';
417
return goog.uri.utils.decodeIfPossible_(
418
goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);
419
};
420
421
422
/**
423
* @param {string} uri The URI to examine.
424
* @return {?string} The query data still encoded, or null if none. Does not
425
* include the question mark itself.
426
*/
427
goog.uri.utils.getQueryData = function(uri) {
428
'use strict';
429
return goog.uri.utils.getComponentByIndex_(
430
goog.uri.utils.ComponentIndex.QUERY_DATA, uri);
431
};
432
433
434
/**
435
* @param {string} uri The URI to examine.
436
* @return {?string} The fragment identifier, or null if none. Does not
437
* include the hash mark itself.
438
*/
439
goog.uri.utils.getFragmentEncoded = function(uri) {
440
'use strict';
441
// The hash mark may not appear in any other part of the URL.
442
var hashIndex = uri.indexOf('#');
443
return hashIndex < 0 ? null : uri.slice(hashIndex + 1);
444
};
445
446
447
/**
448
* @param {string} uri The URI to examine.
449
* @param {?string} fragment The encoded fragment identifier, or null if none.
450
* Does not include the hash mark itself.
451
* @return {string} The URI with the fragment set.
452
*/
453
goog.uri.utils.setFragmentEncoded = function(uri, fragment) {
454
'use strict';
455
return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');
456
};
457
458
459
/**
460
* @param {string} uri The URI to examine.
461
* @return {?string} The decoded fragment identifier, or null if none. Does
462
* not include the hash mark.
463
*/
464
goog.uri.utils.getFragment = function(uri) {
465
'use strict';
466
return goog.uri.utils.decodeIfPossible_(
467
goog.uri.utils.getFragmentEncoded(uri));
468
};
469
470
471
/**
472
* Extracts everything up to the port of the URI.
473
* @param {string} uri The URI string.
474
* @return {string} Everything up to and including the port.
475
*/
476
goog.uri.utils.getHost = function(uri) {
477
'use strict';
478
var pieces = goog.uri.utils.split(uri);
479
return goog.uri.utils.buildFromEncodedParts(
480
pieces[goog.uri.utils.ComponentIndex.SCHEME],
481
pieces[goog.uri.utils.ComponentIndex.USER_INFO],
482
pieces[goog.uri.utils.ComponentIndex.DOMAIN],
483
pieces[goog.uri.utils.ComponentIndex.PORT]);
484
};
485
486
487
/**
488
* Returns the origin for a given URL.
489
* @param {string} uri The URI string.
490
* @return {string} Everything up to and including the port.
491
*/
492
goog.uri.utils.getOrigin = function(uri) {
493
'use strict';
494
var pieces = goog.uri.utils.split(uri);
495
return goog.uri.utils.buildFromEncodedParts(
496
pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,
497
pieces[goog.uri.utils.ComponentIndex.DOMAIN],
498
pieces[goog.uri.utils.ComponentIndex.PORT]);
499
};
500
501
502
/**
503
* Extracts the path of the URL and everything after.
504
* @param {string} uri The URI string.
505
* @return {string} The URI, starting at the path and including the query
506
* parameters and fragment identifier.
507
*/
508
goog.uri.utils.getPathAndAfter = function(uri) {
509
'use strict';
510
var pieces = goog.uri.utils.split(uri);
511
return goog.uri.utils.buildFromEncodedParts(
512
null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],
513
pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],
514
pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);
515
};
516
517
518
/**
519
* Gets the URI with the fragment identifier removed.
520
* @param {string} uri The URI to examine.
521
* @return {string} Everything preceding the hash mark.
522
*/
523
goog.uri.utils.removeFragment = function(uri) {
524
'use strict';
525
// The hash mark may not appear in any other part of the URL.
526
var hashIndex = uri.indexOf('#');
527
return hashIndex < 0 ? uri : uri.slice(0, hashIndex);
528
};
529
530
531
/**
532
* Ensures that two URI's have the exact same domain, scheme, and port.
533
*
534
* Unlike the version in goog.Uri, this checks protocol, and therefore is
535
* suitable for checking against the browser's same-origin policy.
536
*
537
* @param {string} uri1 The first URI.
538
* @param {string} uri2 The second URI.
539
* @return {boolean} Whether they have the same scheme, domain and port.
540
*/
541
goog.uri.utils.haveSameDomain = function(uri1, uri2) {
542
'use strict';
543
var pieces1 = goog.uri.utils.split(uri1);
544
var pieces2 = goog.uri.utils.split(uri2);
545
return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==
546
pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&
547
pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==
548
pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&
549
pieces1[goog.uri.utils.ComponentIndex.PORT] ==
550
pieces2[goog.uri.utils.ComponentIndex.PORT];
551
};
552
553
554
/**
555
* Asserts that there are no fragment or query identifiers, only in uncompiled
556
* mode.
557
* @param {string} uri The URI to examine.
558
* @private
559
*/
560
goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {
561
'use strict';
562
goog.asserts.assert(
563
uri.indexOf('#') < 0 && uri.indexOf('?') < 0,
564
'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',
565
uri);
566
};
567
568
569
/**
570
* Supported query parameter values by the parameter serializing utilities.
571
*
572
* If a value is null or undefined, the key-value pair is skipped, as an easy
573
* way to omit parameters conditionally. Non-array parameters are converted
574
* to a string and URI encoded. Array values are expanded into multiple
575
* &key=value pairs, with each element stringized and URI-encoded.
576
*
577
* @typedef {*}
578
*/
579
goog.uri.utils.QueryValue;
580
581
582
/**
583
* An array representing a set of query parameters with alternating keys
584
* and values.
585
*
586
* Keys are assumed to be URI encoded already and live at even indices. See
587
* goog.uri.utils.QueryValue for details on how parameter values are encoded.
588
*
589
* Example:
590
* <pre>
591
* var data = [
592
* // Simple param: ?name=BobBarker
593
* 'name', 'BobBarker',
594
* // Conditional param -- may be omitted entirely.
595
* 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,
596
* // Multi-valued param: &house=LosAngeles&house=NewYork&house=null
597
* 'house', ['LosAngeles', 'NewYork', null]
598
* ];
599
* </pre>
600
*
601
* @typedef {!Array<string|goog.uri.utils.QueryValue>}
602
*/
603
goog.uri.utils.QueryArray;
604
605
606
/**
607
* Parses encoded query parameters and calls callback function for every
608
* parameter found in the string.
609
*
610
* Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an
611
* empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means
612
* that “…&=&…” and “…&&…” will result in an empty key and value.
613
*
614
* @param {string} encodedQuery Encoded query string excluding question mark at
615
* the beginning.
616
* @param {function(string, string)} callback Function called for every
617
* parameter found in query string. The first argument (name) will not be
618
* urldecoded (so the function is consistent with buildQueryData), but the
619
* second will. If the parameter has no value (i.e. “=” was not present)
620
* the second argument (value) will be an empty string.
621
*/
622
goog.uri.utils.parseQueryData = function(encodedQuery, callback) {
623
'use strict';
624
if (!encodedQuery) {
625
return;
626
}
627
var pairs = encodedQuery.split('&');
628
for (var i = 0; i < pairs.length; i++) {
629
var indexOfEquals = pairs[i].indexOf('=');
630
var name = null;
631
var value = null;
632
if (indexOfEquals >= 0) {
633
name = pairs[i].substring(0, indexOfEquals);
634
value = pairs[i].substring(indexOfEquals + 1);
635
} else {
636
name = pairs[i];
637
}
638
callback(name, value ? goog.string.urlDecode(value) : '');
639
}
640
};
641
642
643
/**
644
* Split the URI into 3 parts where the [1] is the queryData without a leading
645
* '?'. For example, the URI http://foo.com/bar?a=b#abc returns
646
* ['http://foo.com/bar','a=b','#abc'].
647
* @param {string} uri The URI to parse.
648
* @return {!Array<string>} An array representation of uri of length 3 where the
649
* middle value is the queryData without a leading '?'.
650
* @private
651
*/
652
goog.uri.utils.splitQueryData_ = function(uri) {
653
'use strict';
654
// Find the query data and hash.
655
var hashIndex = uri.indexOf('#');
656
if (hashIndex < 0) {
657
hashIndex = uri.length;
658
}
659
var questionIndex = uri.indexOf('?');
660
var queryData;
661
if (questionIndex < 0 || questionIndex > hashIndex) {
662
questionIndex = hashIndex;
663
queryData = '';
664
} else {
665
queryData = uri.substring(questionIndex + 1, hashIndex);
666
}
667
return [uri.slice(0, questionIndex), queryData, uri.slice(hashIndex)];
668
};
669
670
671
/**
672
* Join an array created by splitQueryData_ back into a URI.
673
* @param {!Array<string>} parts A URI in the form generated by splitQueryData_.
674
* @return {string} The joined URI.
675
* @private
676
*/
677
goog.uri.utils.joinQueryData_ = function(parts) {
678
'use strict';
679
return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];
680
};
681
682
683
/**
684
* @param {string} queryData
685
* @param {string} newData
686
* @return {string}
687
* @private
688
*/
689
goog.uri.utils.appendQueryData_ = function(queryData, newData) {
690
'use strict';
691
if (!newData) {
692
return queryData;
693
}
694
return queryData ? queryData + '&' + newData : newData;
695
};
696
697
698
/**
699
* @param {string} uri
700
* @param {string} queryData
701
* @return {string}
702
* @private
703
*/
704
goog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {
705
'use strict';
706
if (!queryData) {
707
return uri;
708
}
709
var parts = goog.uri.utils.splitQueryData_(uri);
710
parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);
711
return goog.uri.utils.joinQueryData_(parts);
712
};
713
714
715
/**
716
* Appends key=value pairs to an array, supporting multi-valued objects.
717
* @param {*} key The key prefix.
718
* @param {goog.uri.utils.QueryValue} value The value to serialize.
719
* @param {!Array<string>} pairs The array to which the 'key=value' strings
720
* should be appended.
721
* @private
722
*/
723
goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {
724
'use strict';
725
goog.asserts.assertString(key);
726
if (Array.isArray(value)) {
727
// Convince the compiler it's an array.
728
goog.asserts.assertArray(value);
729
for (var j = 0; j < value.length; j++) {
730
// Convert to string explicitly, to short circuit the null and array
731
// logic in this function -- this ensures that null and undefined get
732
// written as literal 'null' and 'undefined', and arrays don't get
733
// expanded out but instead encoded in the default way.
734
goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);
735
}
736
} else if (value != null) {
737
// Skip a top-level null or undefined entirely.
738
pairs.push(
739
key +
740
// Check for empty string. Zero gets encoded into the url as literal
741
// strings. For empty string, skip the equal sign, to be consistent
742
// with UriBuilder.java.
743
(value === '' ? '' : '=' + goog.string.urlEncode(value)));
744
}
745
};
746
747
748
/**
749
* Builds a query data string from a sequence of alternating keys and values.
750
* Currently generates "&key&" for empty args.
751
*
752
* @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues
753
* Alternating keys and values. See the QueryArray typedef.
754
* @param {number=} opt_startIndex A start offset into the arary, defaults to 0.
755
* @return {string} The encoded query string, in the form 'a=1&b=2'.
756
*/
757
goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {
758
'use strict';
759
goog.asserts.assert(
760
Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,
761
'goog.uri.utils: Key/value lists must be even in length.');
762
763
var params = [];
764
for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {
765
var key = /** @type {string} */ (keysAndValues[i]);
766
goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);
767
}
768
return params.join('&');
769
};
770
771
772
/**
773
* Builds a query data string from a map.
774
* Currently generates "&key&" for empty args.
775
*
776
* @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys
777
* are URI-encoded parameter keys, and the values are arbitrary types
778
* or arrays. Keys with a null value are dropped.
779
* @return {string} The encoded query string, in the form 'a=1&b=2'.
780
*/
781
goog.uri.utils.buildQueryDataFromMap = function(map) {
782
'use strict';
783
var params = [];
784
for (var key in map) {
785
goog.uri.utils.appendKeyValuePairs_(key, map[key], params);
786
}
787
return params.join('&');
788
};
789
790
791
/**
792
* Appends URI parameters to an existing URI.
793
*
794
* The variable arguments may contain alternating keys and values. Keys are
795
* assumed to be already URI encoded. The values should not be URI-encoded,
796
* and will instead be encoded by this function.
797
* <pre>
798
* appendParams('http://www.foo.com?existing=true',
799
* 'key1', 'value1',
800
* 'key2', 'value?willBeEncoded',
801
* 'key3', ['valueA', 'valueB', 'valueC'],
802
* 'key4', null);
803
* result: 'http://www.foo.com?existing=true&' +
804
* 'key1=value1&' +
805
* 'key2=value%3FwillBeEncoded&' +
806
* 'key3=valueA&key3=valueB&key3=valueC'
807
* </pre>
808
*
809
* A single call to this function will not exhibit quadratic behavior in IE,
810
* whereas multiple repeated calls may, although the effect is limited by
811
* fact that URL's generally can't exceed 2kb.
812
*
813
* @param {string} uri The original URI, which may already have query data.
814
* @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}
815
* var_args
816
* An array or argument list conforming to goog.uri.utils.QueryArray.
817
* @return {string} The URI with all query parameters added.
818
*/
819
goog.uri.utils.appendParams = function(uri, var_args) {
820
'use strict';
821
var queryData = arguments.length == 2 ?
822
goog.uri.utils.buildQueryData(arguments[1], 0) :
823
goog.uri.utils.buildQueryData(arguments, 1);
824
return goog.uri.utils.appendQueryDataToUri_(uri, queryData);
825
};
826
827
828
/**
829
* Appends query parameters from a map.
830
*
831
* @param {string} uri The original URI, which may already have query data.
832
* @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are
833
* URI-encoded parameter keys, and the values are arbitrary types or arrays.
834
* Keys with a null value are dropped.
835
* @return {string} The new parameters.
836
*/
837
goog.uri.utils.appendParamsFromMap = function(uri, map) {
838
'use strict';
839
var queryData = goog.uri.utils.buildQueryDataFromMap(map);
840
return goog.uri.utils.appendQueryDataToUri_(uri, queryData);
841
};
842
843
844
/**
845
* Appends a single URI parameter.
846
*
847
* Repeated calls to this can exhibit quadratic behavior in IE6 due to the
848
* way string append works, though it should be limited given the 2kb limit.
849
*
850
* @param {string} uri The original URI, which may already have query data.
851
* @param {string} key The key, which must already be URI encoded.
852
* @param {*=} opt_value The value, which will be stringized and encoded
853
* (assumed not already to be encoded). If omitted, undefined, or null, the
854
* key will be added as a valueless parameter.
855
* @return {string} The URI with the query parameter added.
856
*/
857
goog.uri.utils.appendParam = function(uri, key, opt_value) {
858
'use strict';
859
var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';
860
return goog.uri.utils.appendQueryDataToUri_(uri, key + value);
861
};
862
863
864
/**
865
* Finds the next instance of a query parameter with the specified name.
866
*
867
* Does not instantiate any objects.
868
*
869
* @param {string} uri The URI to search. May contain a fragment identifier
870
* if opt_hashIndex is specified.
871
* @param {number} startIndex The index to begin searching for the key at. A
872
* match may be found even if this is one character after the ampersand.
873
* @param {string} keyEncoded The URI-encoded key.
874
* @param {number} hashOrEndIndex Index to stop looking at. If a hash
875
* mark is present, it should be its index, otherwise it should be the
876
* length of the string.
877
* @return {number} The position of the first character in the key's name,
878
* immediately after either a question mark or a dot.
879
* @private
880
*/
881
goog.uri.utils.findParam_ = function(
882
uri, startIndex, keyEncoded, hashOrEndIndex) {
883
'use strict';
884
var index = startIndex;
885
var keyLength = keyEncoded.length;
886
887
// Search for the key itself and post-filter for surronuding punctuation,
888
// rather than expensively building a regexp.
889
while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&
890
index < hashOrEndIndex) {
891
var precedingChar = uri.charCodeAt(index - 1);
892
// Ensure that the preceding character is '&' or '?'.
893
if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||
894
precedingChar == goog.uri.utils.CharCode_.QUESTION) {
895
// Ensure the following character is '&', '=', '#', or NaN
896
// (end of string).
897
var followingChar = uri.charCodeAt(index + keyLength);
898
if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||
899
followingChar == goog.uri.utils.CharCode_.AMPERSAND ||
900
followingChar == goog.uri.utils.CharCode_.HASH) {
901
return index;
902
}
903
}
904
index += keyLength + 1;
905
}
906
907
return -1;
908
};
909
910
911
/**
912
* Regular expression for finding a hash mark or end of string.
913
* @type {RegExp}
914
* @private
915
*/
916
goog.uri.utils.hashOrEndRe_ = /#|$/;
917
918
919
/**
920
* Determines if the URI contains a specific key.
921
*
922
* Performs no object instantiations.
923
*
924
* @param {string} uri The URI to process. May contain a fragment
925
* identifier.
926
* @param {string} keyEncoded The URI-encoded key. Case-sensitive.
927
* @return {boolean} Whether the key is present.
928
*/
929
goog.uri.utils.hasParam = function(uri, keyEncoded) {
930
'use strict';
931
return goog.uri.utils.findParam_(
932
uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;
933
};
934
935
936
/**
937
* Gets the first value of a query parameter.
938
* @param {string} uri The URI to process. May contain a fragment.
939
* @param {string} keyEncoded The URI-encoded key. Case-sensitive.
940
* @return {?string} The first value of the parameter (URI-decoded), or null
941
* if the parameter is not found.
942
*/
943
goog.uri.utils.getParamValue = function(uri, keyEncoded) {
944
'use strict';
945
var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
946
var foundIndex =
947
goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);
948
949
if (foundIndex < 0) {
950
return null;
951
} else {
952
var endPosition = uri.indexOf('&', foundIndex);
953
if (endPosition < 0 || endPosition > hashOrEndIndex) {
954
endPosition = hashOrEndIndex;
955
}
956
// Progress forth to the end of the "key=" or "key&" substring.
957
foundIndex += keyEncoded.length + 1;
958
return goog.string.urlDecode(
959
uri.slice(foundIndex, endPosition !== -1 ? endPosition : 0));
960
}
961
};
962
963
964
/**
965
* Gets all values of a query parameter.
966
* @param {string} uri The URI to process. May contain a fragment.
967
* @param {string} keyEncoded The URI-encoded key. Case-sensitive.
968
* @return {!Array<string>} All URI-decoded values with the given key.
969
* If the key is not found, this will have length 0, but never be null.
970
*/
971
goog.uri.utils.getParamValues = function(uri, keyEncoded) {
972
'use strict';
973
var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
974
var position = 0;
975
var foundIndex;
976
var result = [];
977
978
while ((foundIndex = goog.uri.utils.findParam_(
979
uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
980
// Find where this parameter ends, either the '&' or the end of the
981
// query parameters.
982
position = uri.indexOf('&', foundIndex);
983
if (position < 0 || position > hashOrEndIndex) {
984
position = hashOrEndIndex;
985
}
986
987
// Progress forth to the end of the "key=" or "key&" substring.
988
foundIndex += keyEncoded.length + 1;
989
result.push(
990
goog.string.urlDecode(uri.slice(foundIndex, Math.max(position, 0))));
991
}
992
993
return result;
994
};
995
996
997
/**
998
* Regexp to find trailing question marks and ampersands.
999
* @type {RegExp}
1000
* @private
1001
*/
1002
goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;
1003
1004
1005
/**
1006
* Removes all instances of a query parameter.
1007
* @param {string} uri The URI to process. Must not contain a fragment.
1008
* @param {string} keyEncoded The URI-encoded key.
1009
* @return {string} The URI with all instances of the parameter removed.
1010
*/
1011
goog.uri.utils.removeParam = function(uri, keyEncoded) {
1012
'use strict';
1013
var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
1014
var position = 0;
1015
var foundIndex;
1016
var buffer = [];
1017
1018
// Look for a query parameter.
1019
while ((foundIndex = goog.uri.utils.findParam_(
1020
uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
1021
// Get the portion of the query string up to, but not including, the ?
1022
// or & starting the parameter.
1023
buffer.push(uri.substring(position, foundIndex));
1024
// Progress to immediately after the '&'. If not found, go to the end.
1025
// Avoid including the hash mark.
1026
position = Math.min(
1027
(uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);
1028
}
1029
1030
// Append everything that is remaining.
1031
buffer.push(uri.slice(position));
1032
1033
// Join the buffer, and remove trailing punctuation that remains.
1034
return buffer.join('').replace(
1035
goog.uri.utils.trailingQueryPunctuationRe_, '$1');
1036
};
1037
1038
1039
/**
1040
* Replaces all existing definitions of a parameter with a single definition.
1041
*
1042
* Repeated calls to this can exhibit quadratic behavior due to the need to
1043
* find existing instances and reconstruct the string, though it should be
1044
* limited given the 2kb limit. Consider using appendParams or setParamsFromMap
1045
* to update multiple parameters in bulk.
1046
*
1047
* @param {string} uri The original URI, which may already have query data.
1048
* @param {string} keyEncoded The key, which must already be URI encoded.
1049
* @param {*} value The value, which will be stringized and encoded (assumed
1050
* not already to be encoded).
1051
* @return {string} The URI with the query parameter added.
1052
*/
1053
goog.uri.utils.setParam = function(uri, keyEncoded, value) {
1054
'use strict';
1055
return goog.uri.utils.appendParam(
1056
goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);
1057
};
1058
1059
1060
/**
1061
* Effeciently set or remove multiple query parameters in a URI. Order of
1062
* unchanged parameters will not be modified, all updated parameters will be
1063
* appended to the end of the query. Params with values of null or undefined are
1064
* removed.
1065
*
1066
* @param {string} uri The URI to process.
1067
* @param {!Object<string, goog.uri.utils.QueryValue>} params A list of
1068
* parameters to update. If null or undefined, the param will be removed.
1069
* @return {string} An updated URI where the query data has been updated with
1070
* the params.
1071
*/
1072
goog.uri.utils.setParamsFromMap = function(uri, params) {
1073
'use strict';
1074
var parts = goog.uri.utils.splitQueryData_(uri);
1075
var queryData = parts[1];
1076
var buffer = [];
1077
if (queryData) {
1078
queryData.split('&').forEach(function(pair) {
1079
'use strict';
1080
var indexOfEquals = pair.indexOf('=');
1081
var name = indexOfEquals >= 0 ? pair.slice(0, indexOfEquals) : pair;
1082
if (!params.hasOwnProperty(name)) {
1083
buffer.push(pair);
1084
}
1085
});
1086
}
1087
parts[1] = goog.uri.utils.appendQueryData_(
1088
buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));
1089
return goog.uri.utils.joinQueryData_(parts);
1090
};
1091
1092
1093
/**
1094
* Generates a URI path using a given URI and a path with checks to
1095
* prevent consecutive "//". The baseUri passed in must not contain
1096
* query or fragment identifiers. The path to append may not contain query or
1097
* fragment identifiers.
1098
*
1099
* @param {string} baseUri URI to use as the base.
1100
* @param {string} path Path to append.
1101
* @return {string} Updated URI.
1102
*/
1103
goog.uri.utils.appendPath = function(baseUri, path) {
1104
'use strict';
1105
goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);
1106
1107
// Remove any trailing '/'
1108
if (goog.string.endsWith(baseUri, '/')) {
1109
baseUri = baseUri.slice(0, -1);
1110
}
1111
// Remove any leading '/'
1112
if (goog.string.startsWith(path, '/')) {
1113
path = path.slice(1);
1114
}
1115
return '' + baseUri + '/' + path;
1116
};
1117
1118
1119
/**
1120
* Replaces the path.
1121
* @param {string} uri URI to use as the base.
1122
* @param {string} path New path.
1123
* @return {string} Updated URI.
1124
*/
1125
goog.uri.utils.setPath = function(uri, path) {
1126
'use strict';
1127
// Add any missing '/'.
1128
if (!goog.string.startsWith(path, '/')) {
1129
path = '/' + path;
1130
}
1131
var parts = goog.uri.utils.split(uri);
1132
return goog.uri.utils.buildFromEncodedParts(
1133
parts[goog.uri.utils.ComponentIndex.SCHEME],
1134
parts[goog.uri.utils.ComponentIndex.USER_INFO],
1135
parts[goog.uri.utils.ComponentIndex.DOMAIN],
1136
parts[goog.uri.utils.ComponentIndex.PORT], path,
1137
parts[goog.uri.utils.ComponentIndex.QUERY_DATA],
1138
parts[goog.uri.utils.ComponentIndex.FRAGMENT]);
1139
};
1140
1141
1142
/**
1143
* Standard supported query parameters.
1144
* @enum {string}
1145
*/
1146
goog.uri.utils.StandardQueryParam = {
1147
1148
/** Unused parameter for unique-ifying. */
1149
RANDOM: 'zx'
1150
};
1151
1152
1153
/**
1154
* Sets the zx parameter of a URI to a random value.
1155
* @param {string} uri Any URI.
1156
* @return {string} That URI with the "zx" parameter added or replaced to
1157
* contain a random string.
1158
*/
1159
goog.uri.utils.makeUnique = function(uri) {
1160
'use strict';
1161
return goog.uri.utils.setParam(
1162
uri, goog.uri.utils.StandardQueryParam.RANDOM,
1163
goog.string.getRandomString());
1164
};
1165
1166