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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
|
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Simple utilities for dealing with URI strings.
*
* This is intended to be a lightweight alternative to constructing goog.Uri
* objects. Whereas goog.Uri adds several kilobytes to the binary regardless
* of how much of its functionality you use, this is designed to be a set of
* mostly-independent utilities so that the compiler includes only what is
* necessary for the task. Estimated savings of porting is 5k pre-gzip and
* 1.5k post-gzip. To ensure the savings remain, future developers should
* avoid adding new functionality to existing functions, but instead create
* new ones and factor out shared code.
*
* Many of these utilities have limited functionality, tailored to common
* cases. The query parameter utilities assume that the parameter keys are
* already encoded, since most keys are compile-time alphanumeric strings. The
* query parameter mutation utilities also do not tolerate fragment identifiers.
*
* By design, these functions can be slower than goog.Uri equivalents.
* Repeated calls to some of functions may be quadratic in behavior for IE,
* although the effect is somewhat limited given the 2kb limit.
*
* One advantage of the limited functionality here is that this approach is
* less sensitive to differences in URI encodings than goog.Uri, since these
* functions operate on strings directly, rather than decoding them and
* then re-encoding.
*
* Uses features of RFC 3986 for parsing/formatting URIs:
* http://www.ietf.org/rfc/rfc3986.txt
*
* @author gboyer@google.com (Garrett Boyer) - The "lightened" design.
* @author msamuel@google.com (Mike Samuel) - Domain knowledge and regexes.
*/
goog.provide('goog.uri.utils');
goog.provide('goog.uri.utils.ComponentIndex');
goog.provide('goog.uri.utils.QueryArray');
goog.provide('goog.uri.utils.QueryValue');
goog.provide('goog.uri.utils.StandardQueryParam');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.string');
/**
* Character codes inlined to avoid object allocations due to charCode.
* @enum {number}
* @private
*/
goog.uri.utils.CharCode_ = {
AMPERSAND: 38,
EQUAL: 61,
HASH: 35,
QUESTION: 63
};
/**
* Builds a URI string from already-encoded parts.
*
* No encoding is performed. Any component may be omitted as either null or
* undefined.
*
* @param {?string=} opt_scheme The scheme such as 'http'.
* @param {?string=} opt_userInfo The user name before the '@'.
* @param {?string=} opt_domain The domain such as 'www.google.com', already
* URI-encoded.
* @param {(string|number|null)=} opt_port The port number.
* @param {?string=} opt_path The path, already URI-encoded. If it is not
* empty, it must begin with a slash.
* @param {?string=} opt_queryData The URI-encoded query data.
* @param {?string=} opt_fragment The URI-encoded fragment identifier.
* @return {string} The fully combined URI.
*/
goog.uri.utils.buildFromEncodedParts = function(
opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,
opt_fragment) {
var out = '';
if (opt_scheme) {
out += opt_scheme + ':';
}
if (opt_domain) {
out += '//';
if (opt_userInfo) {
out += opt_userInfo + '@';
}
out += opt_domain;
if (opt_port) {
out += ':' + opt_port;
}
}
if (opt_path) {
out += opt_path;
}
if (opt_queryData) {
out += '?' + opt_queryData;
}
if (opt_fragment) {
out += '#' + opt_fragment;
}
return out;
};
/**
* A regular expression for breaking a URI into its component parts.
*
* {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B
* As the "first-match-wins" algorithm is identical to the "greedy"
* disambiguation method used by POSIX regular expressions, it is natural and
* commonplace to use a regular expression for parsing the potential five
* components of a URI reference.
*
* The following line is the regular expression for breaking-down a
* well-formed URI reference into its components.
*
* <pre>
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
* </pre>
*
* The numbers in the second line above are only to assist readability; they
* indicate the reference points for each subexpression (i.e., each paired
* parenthesis). We refer to the value matched for subexpression <n> as $<n>.
* For example, matching the above expression to
* <pre>
* http://www.ics.uci.edu/pub/ietf/uri/#Related
* </pre>
* results in the following subexpression matches:
* <pre>
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
* </pre>
* where <undefined> indicates that the component is not present, as is the
* case for the query component in the above example. Therefore, we can
* determine the value of the five components as
* <pre>
* scheme = $2
* authority = $4
* path = $5
* query = $7
* fragment = $9
* </pre>
*
* The regular expression has been modified slightly to expose the
* userInfo, domain, and port separately from the authority.
* The modified version yields
* <pre>
* $1 = http scheme
* $2 = <undefined> userInfo -\
* $3 = www.ics.uci.edu domain | authority
* $4 = <undefined> port -/
* $5 = /pub/ietf/uri/ path
* $6 = <undefined> query without ?
* $7 = Related fragment without #
* </pre>
* @type {!RegExp}
* @private
*/
goog.uri.utils.splitRe_ = new RegExp(
'^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
// used by other URL parts such as :,
// ?, /, #, and .
':)?' +
'(?://' +
'(?:([^/?#]*)@)?' + // userInfo
'([^/#?]*?)' + // domain
'(?::([0-9]+))?' + // port
'(?=[/#?]|$)' + // authority-terminating character
')?' +
'([^?#]+)?' + // path
'(?:\\?([^#]*))?' + // query
'(?:#([\\s\\S]*))?' + // fragment
'$');
/**
* The index of each URI component in the return value of goog.uri.utils.split.
* @enum {number}
*/
goog.uri.utils.ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
/**
* Splits a URI into its component parts.
*
* Each component can be accessed via the component indices; for example:
* <pre>
* goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];
* </pre>
*
* @param {string} uri The URI string to examine.
* @return {!Array<string|undefined>} Each component still URI-encoded.
* Each component that is present will contain the encoded value, whereas
* components that are not present will be undefined or empty, depending
* on the browser's regular expression implementation. Never null, since
* arbitrary strings may still look like path names.
*/
goog.uri.utils.split = function(uri) {
// See @return comment -- never null.
return /** @type {!Array<string|undefined>} */ (
uri.match(goog.uri.utils.splitRe_));
};
/**
* @param {?string} uri A possibly null string.
* @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986
* reserved characters will not be removed.
* @return {?string} The string URI-decoded, or null if uri is null.
* @private
*/
goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {
if (!uri) {
return uri;
}
return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);
};
/**
* Gets a URI component by index.
*
* It is preferred to use the getPathEncoded() variety of functions ahead,
* since they are more readable.
*
* @param {goog.uri.utils.ComponentIndex} componentIndex The component index.
* @param {string} uri The URI to examine.
* @return {?string} The still-encoded component, or null if the component
* is not present.
* @private
*/
goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {
// Convert undefined, null, and empty string into null.
return goog.uri.utils.split(uri)[componentIndex] || null;
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The protocol or scheme, or null if none. Does not
* include trailing colons or slashes.
*/
goog.uri.utils.getScheme = function(uri) {
return goog.uri.utils.getComponentByIndex_(
goog.uri.utils.ComponentIndex.SCHEME, uri);
};
/**
* Gets the effective scheme for the URL. If the URL is relative then the
* scheme is derived from the page's location.
* @param {string} uri The URI to examine.
* @return {string} The protocol or scheme, always lower case.
*/
goog.uri.utils.getEffectiveScheme = function(uri) {
var scheme = goog.uri.utils.getScheme(uri);
if (!scheme && goog.global.self && goog.global.self.location) {
var protocol = goog.global.self.location.protocol;
scheme = protocol.substr(0, protocol.length - 1);
}
// NOTE: When called from a web worker in Firefox 3.5, location maybe null.
// All other browsers with web workers support self.location from the worker.
return scheme ? scheme.toLowerCase() : '';
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The user name still encoded, or null if none.
*/
goog.uri.utils.getUserInfoEncoded = function(uri) {
return goog.uri.utils.getComponentByIndex_(
goog.uri.utils.ComponentIndex.USER_INFO, uri);
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The decoded user info, or null if none.
*/
goog.uri.utils.getUserInfo = function(uri) {
return goog.uri.utils.decodeIfPossible_(
goog.uri.utils.getUserInfoEncoded(uri));
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The domain name still encoded, or null if none.
*/
goog.uri.utils.getDomainEncoded = function(uri) {
return goog.uri.utils.getComponentByIndex_(
goog.uri.utils.ComponentIndex.DOMAIN, uri);
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The decoded domain, or null if none.
*/
goog.uri.utils.getDomain = function(uri) {
return goog.uri.utils.decodeIfPossible_(
goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);
};
/**
* @param {string} uri The URI to examine.
* @return {?number} The port number, or null if none.
*/
goog.uri.utils.getPort = function(uri) {
// Coerce to a number. If the result of getComponentByIndex_ is null or
// non-numeric, the number coersion yields NaN. This will then return
// null for all non-numeric cases (though also zero, which isn't a relevant
// port number).
return Number(
goog.uri.utils.getComponentByIndex_(
goog.uri.utils.ComponentIndex.PORT, uri)) ||
null;
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The path still encoded, or null if none. Includes the
* leading slash, if any.
*/
goog.uri.utils.getPathEncoded = function(uri) {
return goog.uri.utils.getComponentByIndex_(
goog.uri.utils.ComponentIndex.PATH, uri);
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The decoded path, or null if none. Includes the leading
* slash, if any.
*/
goog.uri.utils.getPath = function(uri) {
return goog.uri.utils.decodeIfPossible_(
goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The query data still encoded, or null if none. Does not
* include the question mark itself.
*/
goog.uri.utils.getQueryData = function(uri) {
return goog.uri.utils.getComponentByIndex_(
goog.uri.utils.ComponentIndex.QUERY_DATA, uri);
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The fragment identifier, or null if none. Does not
* include the hash mark itself.
*/
goog.uri.utils.getFragmentEncoded = function(uri) {
// The hash mark may not appear in any other part of the URL.
var hashIndex = uri.indexOf('#');
return hashIndex < 0 ? null : uri.substr(hashIndex + 1);
};
/**
* @param {string} uri The URI to examine.
* @param {?string} fragment The encoded fragment identifier, or null if none.
* Does not include the hash mark itself.
* @return {string} The URI with the fragment set.
*/
goog.uri.utils.setFragmentEncoded = function(uri, fragment) {
return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');
};
/**
* @param {string} uri The URI to examine.
* @return {?string} The decoded fragment identifier, or null if none. Does
* not include the hash mark.
*/
goog.uri.utils.getFragment = function(uri) {
return goog.uri.utils.decodeIfPossible_(
goog.uri.utils.getFragmentEncoded(uri));
};
/**
* Extracts everything up to the port of the URI.
* @param {string} uri The URI string.
* @return {string} Everything up to and including the port.
*/
goog.uri.utils.getHost = function(uri) {
var pieces = goog.uri.utils.split(uri);
return goog.uri.utils.buildFromEncodedParts(
pieces[goog.uri.utils.ComponentIndex.SCHEME],
pieces[goog.uri.utils.ComponentIndex.USER_INFO],
pieces[goog.uri.utils.ComponentIndex.DOMAIN],
pieces[goog.uri.utils.ComponentIndex.PORT]);
};
/**
* Returns the origin for a given URL.
* @param {string} uri The URI string.
* @return {string} Everything up to and including the port.
*/
goog.uri.utils.getOrigin = function(uri) {
var pieces = goog.uri.utils.split(uri);
return goog.uri.utils.buildFromEncodedParts(
pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,
pieces[goog.uri.utils.ComponentIndex.DOMAIN],
pieces[goog.uri.utils.ComponentIndex.PORT]);
};
/**
* Extracts the path of the URL and everything after.
* @param {string} uri The URI string.
* @return {string} The URI, starting at the path and including the query
* parameters and fragment identifier.
*/
goog.uri.utils.getPathAndAfter = function(uri) {
var pieces = goog.uri.utils.split(uri);
return goog.uri.utils.buildFromEncodedParts(
null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],
pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],
pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);
};
/**
* Gets the URI with the fragment identifier removed.
* @param {string} uri The URI to examine.
* @return {string} Everything preceding the hash mark.
*/
goog.uri.utils.removeFragment = function(uri) {
// The hash mark may not appear in any other part of the URL.
var hashIndex = uri.indexOf('#');
return hashIndex < 0 ? uri : uri.substr(0, hashIndex);
};
/**
* Ensures that two URI's have the exact same domain, scheme, and port.
*
* Unlike the version in goog.Uri, this checks protocol, and therefore is
* suitable for checking against the browser's same-origin policy.
*
* @param {string} uri1 The first URI.
* @param {string} uri2 The second URI.
* @return {boolean} Whether they have the same scheme, domain and port.
*/
goog.uri.utils.haveSameDomain = function(uri1, uri2) {
var pieces1 = goog.uri.utils.split(uri1);
var pieces2 = goog.uri.utils.split(uri2);
return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==
pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&
pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==
pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&
pieces1[goog.uri.utils.ComponentIndex.PORT] ==
pieces2[goog.uri.utils.ComponentIndex.PORT];
};
/**
* Asserts that there are no fragment or query identifiers, only in uncompiled
* mode.
* @param {string} uri The URI to examine.
* @private
*/
goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {
goog.asserts.assert(
uri.indexOf('#') < 0 && uri.indexOf('?') < 0,
'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',
uri);
};
/**
* Supported query parameter values by the parameter serializing utilities.
*
* If a value is null or undefined, the key-value pair is skipped, as an easy
* way to omit parameters conditionally. Non-array parameters are converted
* to a string and URI encoded. Array values are expanded into multiple
* &key=value pairs, with each element stringized and URI-encoded.
*
* @typedef {*}
*/
goog.uri.utils.QueryValue;
/**
* An array representing a set of query parameters with alternating keys
* and values.
*
* Keys are assumed to be URI encoded already and live at even indices. See
* goog.uri.utils.QueryValue for details on how parameter values are encoded.
*
* Example:
* <pre>
* var data = [
* // Simple param: ?name=BobBarker
* 'name', 'BobBarker',
* // Conditional param -- may be omitted entirely.
* 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,
* // Multi-valued param: &house=LosAngeles&house=NewYork&house=null
* 'house', ['LosAngeles', 'NewYork', null]
* ];
* </pre>
*
* @typedef {!Array<string|goog.uri.utils.QueryValue>}
*/
goog.uri.utils.QueryArray;
/**
* Parses encoded query parameters and calls callback function for every
* parameter found in the string.
*
* Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an
* empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means
* that “…&=&…” and “…&&…” will result in an empty key and value.
*
* @param {string} encodedQuery Encoded query string excluding question mark at
* the beginning.
* @param {function(string, string)} callback Function called for every
* parameter found in query string. The first argument (name) will not be
* urldecoded (so the function is consistent with buildQueryData), but the
* second will. If the parameter has no value (i.e. “=” was not present)
* the second argument (value) will be an empty string.
*/
goog.uri.utils.parseQueryData = function(encodedQuery, callback) {
if (!encodedQuery) {
return;
}
var pairs = encodedQuery.split('&');
for (var i = 0; i < pairs.length; i++) {
var indexOfEquals = pairs[i].indexOf('=');
var name = null;
var value = null;
if (indexOfEquals >= 0) {
name = pairs[i].substring(0, indexOfEquals);
value = pairs[i].substring(indexOfEquals + 1);
} else {
name = pairs[i];
}
callback(name, value ? goog.string.urlDecode(value) : '');
}
};
/**
* Split the URI into 3 parts where the [1] is the queryData without a leading
* '?'. For example, the URI http://foo.com/bar?a=b#abc returns
* ['http://foo.com/bar','a=b','#abc'].
* @param {string} uri The URI to parse.
* @return {!Array<string>} An array representation of uri of length 3 where the
* middle value is the queryData without a leading '?'.
* @private
*/
goog.uri.utils.splitQueryData_ = function(uri) {
// Find the query data and and hash.
var hashIndex = uri.indexOf('#');
if (hashIndex < 0) {
hashIndex = uri.length;
}
var questionIndex = uri.indexOf('?');
var queryData;
if (questionIndex < 0 || questionIndex > hashIndex) {
questionIndex = hashIndex;
queryData = '';
} else {
queryData = uri.substring(questionIndex + 1, hashIndex);
}
return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];
};
/**
* Join an array created by splitQueryData_ back into a URI.
* @param {!Array<string>} parts A URI in the form generated by splitQueryData_.
* @return {string} The joined URI.
* @private
*/
goog.uri.utils.joinQueryData_ = function(parts) {
return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];
};
/**
* @param {string} queryData
* @param {string} newData
* @return {string}
* @private
*/
goog.uri.utils.appendQueryData_ = function(queryData, newData) {
if (!newData) {
return queryData;
}
return queryData ? queryData + '&' + newData : newData;
};
/**
* @param {string} uri
* @param {string} queryData
* @return {string}
* @private
*/
goog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {
if (!queryData) {
return uri;
}
var parts = goog.uri.utils.splitQueryData_(uri);
parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);
return goog.uri.utils.joinQueryData_(parts);
};
/**
* Appends key=value pairs to an array, supporting multi-valued objects.
* @param {*} key The key prefix.
* @param {goog.uri.utils.QueryValue} value The value to serialize.
* @param {!Array<string>} pairs The array to which the 'key=value' strings
* should be appended.
* @private
*/
goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {
goog.asserts.assertString(key);
if (goog.isArray(value)) {
// Convince the compiler it's an array.
goog.asserts.assertArray(value);
for (var j = 0; j < value.length; j++) {
// Convert to string explicitly, to short circuit the null and array
// logic in this function -- this ensures that null and undefined get
// written as literal 'null' and 'undefined', and arrays don't get
// expanded out but instead encoded in the default way.
goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);
}
} else if (value != null) {
// Skip a top-level null or undefined entirely.
pairs.push(
key +
// Check for empty string. Zero gets encoded into the url as literal
// strings. For empty string, skip the equal sign, to be consistent
// with UriBuilder.java.
(value === '' ? '' : '=' + goog.string.urlEncode(value)));
}
};
/**
* Builds a query data string from a sequence of alternating keys and values.
* Currently generates "&key&" for empty args.
*
* @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues
* Alternating keys and values. See the QueryArray typedef.
* @param {number=} opt_startIndex A start offset into the arary, defaults to 0.
* @return {string} The encoded query string, in the form 'a=1&b=2'.
*/
goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {
goog.asserts.assert(
Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,
'goog.uri.utils: Key/value lists must be even in length.');
var params = [];
for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {
var key = /** @type {string} */ (keysAndValues[i]);
goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);
}
return params.join('&');
};
/**
* Builds a query data string from a map.
* Currently generates "&key&" for empty args.
*
* @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys
* are URI-encoded parameter keys, and the values are arbitrary types
* or arrays. Keys with a null value are dropped.
* @return {string} The encoded query string, in the form 'a=1&b=2'.
*/
goog.uri.utils.buildQueryDataFromMap = function(map) {
var params = [];
for (var key in map) {
goog.uri.utils.appendKeyValuePairs_(key, map[key], params);
}
return params.join('&');
};
/**
* Appends URI parameters to an existing URI.
*
* The variable arguments may contain alternating keys and values. Keys are
* assumed to be already URI encoded. The values should not be URI-encoded,
* and will instead be encoded by this function.
* <pre>
* appendParams('http://www.foo.com?existing=true',
* 'key1', 'value1',
* 'key2', 'value?willBeEncoded',
* 'key3', ['valueA', 'valueB', 'valueC'],
* 'key4', null);
* result: 'http://www.foo.com?existing=true&' +
* 'key1=value1&' +
* 'key2=value%3FwillBeEncoded&' +
* 'key3=valueA&key3=valueB&key3=valueC'
* </pre>
*
* A single call to this function will not exhibit quadratic behavior in IE,
* whereas multiple repeated calls may, although the effect is limited by
* fact that URL's generally can't exceed 2kb.
*
* @param {string} uri The original URI, which may already have query data.
* @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}
* var_args
* An array or argument list conforming to goog.uri.utils.QueryArray.
* @return {string} The URI with all query parameters added.
*/
goog.uri.utils.appendParams = function(uri, var_args) {
var queryData = arguments.length == 2 ?
goog.uri.utils.buildQueryData(arguments[1], 0) :
goog.uri.utils.buildQueryData(arguments, 1);
return goog.uri.utils.appendQueryDataToUri_(uri, queryData);
};
/**
* Appends query parameters from a map.
*
* @param {string} uri The original URI, which may already have query data.
* @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are
* URI-encoded parameter keys, and the values are arbitrary types or arrays.
* Keys with a null value are dropped.
* @return {string} The new parameters.
*/
goog.uri.utils.appendParamsFromMap = function(uri, map) {
var queryData = goog.uri.utils.buildQueryDataFromMap(map);
return goog.uri.utils.appendQueryDataToUri_(uri, queryData);
};
/**
* Appends a single URI parameter.
*
* Repeated calls to this can exhibit quadratic behavior in IE6 due to the
* way string append works, though it should be limited given the 2kb limit.
*
* @param {string} uri The original URI, which may already have query data.
* @param {string} key The key, which must already be URI encoded.
* @param {*=} opt_value The value, which will be stringized and encoded
* (assumed not already to be encoded). If omitted, undefined, or null, the
* key will be added as a valueless parameter.
* @return {string} The URI with the query parameter added.
*/
goog.uri.utils.appendParam = function(uri, key, opt_value) {
var value = goog.isDefAndNotNull(opt_value) ?
'=' + goog.string.urlEncode(opt_value) :
'';
return goog.uri.utils.appendQueryDataToUri_(uri, key + value);
};
/**
* Finds the next instance of a query parameter with the specified name.
*
* Does not instantiate any objects.
*
* @param {string} uri The URI to search. May contain a fragment identifier
* if opt_hashIndex is specified.
* @param {number} startIndex The index to begin searching for the key at. A
* match may be found even if this is one character after the ampersand.
* @param {string} keyEncoded The URI-encoded key.
* @param {number} hashOrEndIndex Index to stop looking at. If a hash
* mark is present, it should be its index, otherwise it should be the
* length of the string.
* @return {number} The position of the first character in the key's name,
* immediately after either a question mark or a dot.
* @private
*/
goog.uri.utils.findParam_ = function(
uri, startIndex, keyEncoded, hashOrEndIndex) {
var index = startIndex;
var keyLength = keyEncoded.length;
// Search for the key itself and post-filter for surronuding punctuation,
// rather than expensively building a regexp.
while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&
index < hashOrEndIndex) {
var precedingChar = uri.charCodeAt(index - 1);
// Ensure that the preceding character is '&' or '?'.
if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||
precedingChar == goog.uri.utils.CharCode_.QUESTION) {
// Ensure the following character is '&', '=', '#', or NaN
// (end of string).
var followingChar = uri.charCodeAt(index + keyLength);
if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||
followingChar == goog.uri.utils.CharCode_.AMPERSAND ||
followingChar == goog.uri.utils.CharCode_.HASH) {
return index;
}
}
index += keyLength + 1;
}
return -1;
};
/**
* Regular expression for finding a hash mark or end of string.
* @type {RegExp}
* @private
*/
goog.uri.utils.hashOrEndRe_ = /#|$/;
/**
* Determines if the URI contains a specific key.
*
* Performs no object instantiations.
*
* @param {string} uri The URI to process. May contain a fragment
* identifier.
* @param {string} keyEncoded The URI-encoded key. Case-sensitive.
* @return {boolean} Whether the key is present.
*/
goog.uri.utils.hasParam = function(uri, keyEncoded) {
return goog.uri.utils.findParam_(
uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;
};
/**
* Gets the first value of a query parameter.
* @param {string} uri The URI to process. May contain a fragment.
* @param {string} keyEncoded The URI-encoded key. Case-sensitive.
* @return {?string} The first value of the parameter (URI-decoded), or null
* if the parameter is not found.
*/
goog.uri.utils.getParamValue = function(uri, keyEncoded) {
var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
var foundIndex =
goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);
if (foundIndex < 0) {
return null;
} else {
var endPosition = uri.indexOf('&', foundIndex);
if (endPosition < 0 || endPosition > hashOrEndIndex) {
endPosition = hashOrEndIndex;
}
// Progress forth to the end of the "key=" or "key&" substring.
foundIndex += keyEncoded.length + 1;
// Use substr, because it (unlike substring) will return empty string
// if foundIndex > endPosition.
return goog.string.urlDecode(
uri.substr(foundIndex, endPosition - foundIndex));
}
};
/**
* Gets all values of a query parameter.
* @param {string} uri The URI to process. May contain a fragment.
* @param {string} keyEncoded The URI-encoded key. Case-sensitive.
* @return {!Array<string>} All URI-decoded values with the given key.
* If the key is not found, this will have length 0, but never be null.
*/
goog.uri.utils.getParamValues = function(uri, keyEncoded) {
var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
var position = 0;
var foundIndex;
var result = [];
while ((foundIndex = goog.uri.utils.findParam_(
uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
// Find where this parameter ends, either the '&' or the end of the
// query parameters.
position = uri.indexOf('&', foundIndex);
if (position < 0 || position > hashOrEndIndex) {
position = hashOrEndIndex;
}
// Progress forth to the end of the "key=" or "key&" substring.
foundIndex += keyEncoded.length + 1;
// Use substr, because it (unlike substring) will return empty string
// if foundIndex > position.
result.push(
goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));
}
return result;
};
/**
* Regexp to find trailing question marks and ampersands.
* @type {RegExp}
* @private
*/
goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;
/**
* Removes all instances of a query parameter.
* @param {string} uri The URI to process. Must not contain a fragment.
* @param {string} keyEncoded The URI-encoded key.
* @return {string} The URI with all instances of the parameter removed.
*/
goog.uri.utils.removeParam = function(uri, keyEncoded) {
var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
var position = 0;
var foundIndex;
var buffer = [];
// Look for a query parameter.
while ((foundIndex = goog.uri.utils.findParam_(
uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
// Get the portion of the query string up to, but not including, the ?
// or & starting the parameter.
buffer.push(uri.substring(position, foundIndex));
// Progress to immediately after the '&'. If not found, go to the end.
// Avoid including the hash mark.
position = Math.min(
(uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);
}
// Append everything that is remaining.
buffer.push(uri.substr(position));
// Join the buffer, and remove trailing punctuation that remains.
return buffer.join('').replace(
goog.uri.utils.trailingQueryPunctuationRe_, '$1');
};
/**
* Replaces all existing definitions of a parameter with a single definition.
*
* Repeated calls to this can exhibit quadratic behavior due to the need to
* find existing instances and reconstruct the string, though it should be
* limited given the 2kb limit. Consider using appendParams or setParamsFromMap
* to update multiple parameters in bulk.
*
* @param {string} uri The original URI, which may already have query data.
* @param {string} keyEncoded The key, which must already be URI encoded.
* @param {*} value The value, which will be stringized and encoded (assumed
* not already to be encoded).
* @return {string} The URI with the query parameter added.
*/
goog.uri.utils.setParam = function(uri, keyEncoded, value) {
return goog.uri.utils.appendParam(
goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);
};
/**
* Effeciently set or remove multiple query parameters in a URI. Order of
* unchanged parameters will not be modified, all updated parameters will be
* appended to the end of the query. Params with values of null or undefined are
* removed.
*
* @param {string} uri The URI to process.
* @param {!Object<string, goog.uri.utils.QueryValue>} params A list of
* parameters to update. If null or undefined, the param will be removed.
* @return {string} An updated URI where the query data has been updated with
* the params.
*/
goog.uri.utils.setParamsFromMap = function(uri, params) {
var parts = goog.uri.utils.splitQueryData_(uri);
var queryData = parts[1];
var buffer = [];
if (queryData) {
goog.array.forEach(queryData.split('&'), function(pair) {
var indexOfEquals = pair.indexOf('=');
var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;
if (!params.hasOwnProperty(name)) {
buffer.push(pair);
}
});
}
parts[1] = goog.uri.utils.appendQueryData_(
buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));
return goog.uri.utils.joinQueryData_(parts);
};
/**
* Generates a URI path using a given URI and a path with checks to
* prevent consecutive "//". The baseUri passed in must not contain
* query or fragment identifiers. The path to append may not contain query or
* fragment identifiers.
*
* @param {string} baseUri URI to use as the base.
* @param {string} path Path to append.
* @return {string} Updated URI.
*/
goog.uri.utils.appendPath = function(baseUri, path) {
goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);
// Remove any trailing '/'
if (goog.string.endsWith(baseUri, '/')) {
baseUri = baseUri.substr(0, baseUri.length - 1);
}
// Remove any leading '/'
if (goog.string.startsWith(path, '/')) {
path = path.substr(1);
}
return goog.string.buildString(baseUri, '/', path);
};
/**
* Replaces the path.
* @param {string} uri URI to use as the base.
* @param {string} path New path.
* @return {string} Updated URI.
*/
goog.uri.utils.setPath = function(uri, path) {
// Add any missing '/'.
if (!goog.string.startsWith(path, '/')) {
path = '/' + path;
}
var parts = goog.uri.utils.split(uri);
return goog.uri.utils.buildFromEncodedParts(
parts[goog.uri.utils.ComponentIndex.SCHEME],
parts[goog.uri.utils.ComponentIndex.USER_INFO],
parts[goog.uri.utils.ComponentIndex.DOMAIN],
parts[goog.uri.utils.ComponentIndex.PORT], path,
parts[goog.uri.utils.ComponentIndex.QUERY_DATA],
parts[goog.uri.utils.ComponentIndex.FRAGMENT]);
};
/**
* Standard supported query parameters.
* @enum {string}
*/
goog.uri.utils.StandardQueryParam = {
/** Unused parameter for unique-ifying. */
RANDOM: 'zx'
};
/**
* Sets the zx parameter of a URI to a random value.
* @param {string} uri Any URI.
* @return {string} That URI with the "zx" parameter added or replaced to
* contain a random string.
*/
goog.uri.utils.makeUnique = function(uri) {
return goog.uri.utils.setParam(
uri, goog.uri.utils.StandardQueryParam.RANDOM,
goog.string.getRandomString());
};
|