uri.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Class for parsing and formatting URIs.
  16. *
  17. * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to
  18. * create a new instance of the goog.Uri object from Uri parts.
  19. *
  20. * e.g: <code>var myUri = new goog.Uri(window.location);</code>
  21. *
  22. * Implements RFC 3986 for parsing/formatting URIs.
  23. * http://www.ietf.org/rfc/rfc3986.txt
  24. *
  25. * Some changes have been made to the interface (more like .NETs), though the
  26. * internal representation is now of un-encoded parts, this will change the
  27. * behavior slightly.
  28. *
  29. * @author msamuel@google.com (Mike Samuel)
  30. */
  31. goog.provide('goog.Uri');
  32. goog.provide('goog.Uri.QueryData');
  33. goog.require('goog.array');
  34. goog.require('goog.asserts');
  35. goog.require('goog.string');
  36. goog.require('goog.structs');
  37. goog.require('goog.structs.Map');
  38. goog.require('goog.uri.utils');
  39. goog.require('goog.uri.utils.ComponentIndex');
  40. goog.require('goog.uri.utils.StandardQueryParam');
  41. /**
  42. * This class contains setters and getters for the parts of the URI.
  43. * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part
  44. * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the
  45. * decoded path, <code>/foo bar</code>.
  46. *
  47. * Reserved characters (see RFC 3986 section 2.2) can be present in
  48. * their percent-encoded form in scheme, domain, and path URI components and
  49. * will not be auto-decoded. For example:
  50. * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will
  51. * return <code>relative/path%2fto/resource</code>.
  52. *
  53. * The constructor accepts an optional unparsed, raw URI string. The parser
  54. * is relaxed, so special characters that aren't escaped but don't cause
  55. * ambiguities will not cause parse failures.
  56. *
  57. * All setters return <code>this</code> and so may be chained, a la
  58. * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.
  59. *
  60. * @param {*=} opt_uri Optional string URI to parse
  61. * (use goog.Uri.create() to create a URI from parts), or if
  62. * a goog.Uri is passed, a clone is created.
  63. * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore
  64. * the case of the parameter name.
  65. *
  66. * @throws URIError If opt_uri is provided and URI is malformed (that is,
  67. * if decodeURIComponent fails on any of the URI components).
  68. * @constructor
  69. * @struct
  70. */
  71. goog.Uri = function(opt_uri, opt_ignoreCase) {
  72. /**
  73. * Scheme such as "http".
  74. * @private {string}
  75. */
  76. this.scheme_ = '';
  77. /**
  78. * User credentials in the form "username:password".
  79. * @private {string}
  80. */
  81. this.userInfo_ = '';
  82. /**
  83. * Domain part, e.g. "www.google.com".
  84. * @private {string}
  85. */
  86. this.domain_ = '';
  87. /**
  88. * Port, e.g. 8080.
  89. * @private {?number}
  90. */
  91. this.port_ = null;
  92. /**
  93. * Path, e.g. "/tests/img.png".
  94. * @private {string}
  95. */
  96. this.path_ = '';
  97. /**
  98. * The fragment without the #.
  99. * @private {string}
  100. */
  101. this.fragment_ = '';
  102. /**
  103. * Whether or not this Uri should be treated as Read Only.
  104. * @private {boolean}
  105. */
  106. this.isReadOnly_ = false;
  107. /**
  108. * Whether or not to ignore case when comparing query params.
  109. * @private {boolean}
  110. */
  111. this.ignoreCase_ = false;
  112. /**
  113. * Object representing query data.
  114. * @private {!goog.Uri.QueryData}
  115. */
  116. this.queryData_;
  117. // Parse in the uri string
  118. var m;
  119. if (opt_uri instanceof goog.Uri) {
  120. this.ignoreCase_ =
  121. goog.isDef(opt_ignoreCase) ? opt_ignoreCase : opt_uri.getIgnoreCase();
  122. this.setScheme(opt_uri.getScheme());
  123. this.setUserInfo(opt_uri.getUserInfo());
  124. this.setDomain(opt_uri.getDomain());
  125. this.setPort(opt_uri.getPort());
  126. this.setPath(opt_uri.getPath());
  127. this.setQueryData(opt_uri.getQueryData().clone());
  128. this.setFragment(opt_uri.getFragment());
  129. } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {
  130. this.ignoreCase_ = !!opt_ignoreCase;
  131. // Set the parts -- decoding as we do so.
  132. // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,
  133. // whereas in other browsers they will be undefined.
  134. this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);
  135. this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);
  136. this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);
  137. this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);
  138. this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);
  139. this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);
  140. this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);
  141. } else {
  142. this.ignoreCase_ = !!opt_ignoreCase;
  143. this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);
  144. }
  145. };
  146. /**
  147. * If true, we preserve the type of query parameters set programmatically.
  148. *
  149. * This means that if you set a parameter to a boolean, and then call
  150. * getParameterValue, you will get a boolean back.
  151. *
  152. * If false, we will coerce parameters to strings, just as they would
  153. * appear in real URIs.
  154. *
  155. * TODO(nicksantos): Remove this once people have time to fix all tests.
  156. *
  157. * @type {boolean}
  158. */
  159. goog.Uri.preserveParameterTypesCompatibilityFlag = false;
  160. /**
  161. * Parameter name added to stop caching.
  162. * @type {string}
  163. */
  164. goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;
  165. /**
  166. * @return {string} The string form of the url.
  167. * @override
  168. */
  169. goog.Uri.prototype.toString = function() {
  170. var out = [];
  171. var scheme = this.getScheme();
  172. if (scheme) {
  173. out.push(
  174. goog.Uri.encodeSpecialChars_(
  175. scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),
  176. ':');
  177. }
  178. var domain = this.getDomain();
  179. if (domain || scheme == 'file') {
  180. out.push('//');
  181. var userInfo = this.getUserInfo();
  182. if (userInfo) {
  183. out.push(
  184. goog.Uri.encodeSpecialChars_(
  185. userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),
  186. '@');
  187. }
  188. out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));
  189. var port = this.getPort();
  190. if (port != null) {
  191. out.push(':', String(port));
  192. }
  193. }
  194. var path = this.getPath();
  195. if (path) {
  196. if (this.hasDomain() && path.charAt(0) != '/') {
  197. out.push('/');
  198. }
  199. out.push(
  200. goog.Uri.encodeSpecialChars_(
  201. path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :
  202. goog.Uri.reDisallowedInRelativePath_,
  203. true));
  204. }
  205. var query = this.getEncodedQuery();
  206. if (query) {
  207. out.push('?', query);
  208. }
  209. var fragment = this.getFragment();
  210. if (fragment) {
  211. out.push(
  212. '#', goog.Uri.encodeSpecialChars_(
  213. fragment, goog.Uri.reDisallowedInFragment_));
  214. }
  215. return out.join('');
  216. };
  217. /**
  218. * Resolves the given relative URI (a goog.Uri object), using the URI
  219. * represented by this instance as the base URI.
  220. *
  221. * There are several kinds of relative URIs:<br>
  222. * 1. foo - replaces the last part of the path, the whole query and fragment<br>
  223. * 2. /foo - replaces the the path, the query and fragment<br>
  224. * 3. //foo - replaces everything from the domain on. foo is a domain name<br>
  225. * 4. ?foo - replace the query and fragment<br>
  226. * 5. #foo - replace the fragment only
  227. *
  228. * Additionally, if relative URI has a non-empty path, all ".." and "."
  229. * segments will be resolved, as described in RFC 3986.
  230. *
  231. * @param {!goog.Uri} relativeUri The relative URI to resolve.
  232. * @return {!goog.Uri} The resolved URI.
  233. */
  234. goog.Uri.prototype.resolve = function(relativeUri) {
  235. var absoluteUri = this.clone();
  236. // we satisfy these conditions by looking for the first part of relativeUri
  237. // that is not blank and applying defaults to the rest
  238. var overridden = relativeUri.hasScheme();
  239. if (overridden) {
  240. absoluteUri.setScheme(relativeUri.getScheme());
  241. } else {
  242. overridden = relativeUri.hasUserInfo();
  243. }
  244. if (overridden) {
  245. absoluteUri.setUserInfo(relativeUri.getUserInfo());
  246. } else {
  247. overridden = relativeUri.hasDomain();
  248. }
  249. if (overridden) {
  250. absoluteUri.setDomain(relativeUri.getDomain());
  251. } else {
  252. overridden = relativeUri.hasPort();
  253. }
  254. var path = relativeUri.getPath();
  255. if (overridden) {
  256. absoluteUri.setPort(relativeUri.getPort());
  257. } else {
  258. overridden = relativeUri.hasPath();
  259. if (overridden) {
  260. // resolve path properly
  261. if (path.charAt(0) != '/') {
  262. // path is relative
  263. if (this.hasDomain() && !this.hasPath()) {
  264. // RFC 3986, section 5.2.3, case 1
  265. path = '/' + path;
  266. } else {
  267. // RFC 3986, section 5.2.3, case 2
  268. var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');
  269. if (lastSlashIndex != -1) {
  270. path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;
  271. }
  272. }
  273. }
  274. path = goog.Uri.removeDotSegments(path);
  275. }
  276. }
  277. if (overridden) {
  278. absoluteUri.setPath(path);
  279. } else {
  280. overridden = relativeUri.hasQuery();
  281. }
  282. if (overridden) {
  283. absoluteUri.setQueryData(relativeUri.getQueryData().clone());
  284. } else {
  285. overridden = relativeUri.hasFragment();
  286. }
  287. if (overridden) {
  288. absoluteUri.setFragment(relativeUri.getFragment());
  289. }
  290. return absoluteUri;
  291. };
  292. /**
  293. * Clones the URI instance.
  294. * @return {!goog.Uri} New instance of the URI object.
  295. */
  296. goog.Uri.prototype.clone = function() {
  297. return new goog.Uri(this);
  298. };
  299. /**
  300. * @return {string} The encoded scheme/protocol for the URI.
  301. */
  302. goog.Uri.prototype.getScheme = function() {
  303. return this.scheme_;
  304. };
  305. /**
  306. * Sets the scheme/protocol.
  307. * @throws URIError If opt_decode is true and newScheme is malformed (that is,
  308. * if decodeURIComponent fails).
  309. * @param {string} newScheme New scheme value.
  310. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  311. * @return {!goog.Uri} Reference to this URI object.
  312. */
  313. goog.Uri.prototype.setScheme = function(newScheme, opt_decode) {
  314. this.enforceReadOnly();
  315. this.scheme_ =
  316. opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;
  317. // remove an : at the end of the scheme so somebody can pass in
  318. // window.location.protocol
  319. if (this.scheme_) {
  320. this.scheme_ = this.scheme_.replace(/:$/, '');
  321. }
  322. return this;
  323. };
  324. /**
  325. * @return {boolean} Whether the scheme has been set.
  326. */
  327. goog.Uri.prototype.hasScheme = function() {
  328. return !!this.scheme_;
  329. };
  330. /**
  331. * @return {string} The decoded user info.
  332. */
  333. goog.Uri.prototype.getUserInfo = function() {
  334. return this.userInfo_;
  335. };
  336. /**
  337. * Sets the userInfo.
  338. * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,
  339. * if decodeURIComponent fails).
  340. * @param {string} newUserInfo New userInfo value.
  341. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  342. * @return {!goog.Uri} Reference to this URI object.
  343. */
  344. goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {
  345. this.enforceReadOnly();
  346. this.userInfo_ =
  347. opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;
  348. return this;
  349. };
  350. /**
  351. * @return {boolean} Whether the user info has been set.
  352. */
  353. goog.Uri.prototype.hasUserInfo = function() {
  354. return !!this.userInfo_;
  355. };
  356. /**
  357. * @return {string} The decoded domain.
  358. */
  359. goog.Uri.prototype.getDomain = function() {
  360. return this.domain_;
  361. };
  362. /**
  363. * Sets the domain.
  364. * @throws URIError If opt_decode is true and newDomain is malformed (that is,
  365. * if decodeURIComponent fails).
  366. * @param {string} newDomain New domain value.
  367. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  368. * @return {!goog.Uri} Reference to this URI object.
  369. */
  370. goog.Uri.prototype.setDomain = function(newDomain, opt_decode) {
  371. this.enforceReadOnly();
  372. this.domain_ =
  373. opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;
  374. return this;
  375. };
  376. /**
  377. * @return {boolean} Whether the domain has been set.
  378. */
  379. goog.Uri.prototype.hasDomain = function() {
  380. return !!this.domain_;
  381. };
  382. /**
  383. * @return {?number} The port number.
  384. */
  385. goog.Uri.prototype.getPort = function() {
  386. return this.port_;
  387. };
  388. /**
  389. * Sets the port number.
  390. * @param {*} newPort Port number. Will be explicitly casted to a number.
  391. * @return {!goog.Uri} Reference to this URI object.
  392. */
  393. goog.Uri.prototype.setPort = function(newPort) {
  394. this.enforceReadOnly();
  395. if (newPort) {
  396. newPort = Number(newPort);
  397. if (isNaN(newPort) || newPort < 0) {
  398. throw Error('Bad port number ' + newPort);
  399. }
  400. this.port_ = newPort;
  401. } else {
  402. this.port_ = null;
  403. }
  404. return this;
  405. };
  406. /**
  407. * @return {boolean} Whether the port has been set.
  408. */
  409. goog.Uri.prototype.hasPort = function() {
  410. return this.port_ != null;
  411. };
  412. /**
  413. * @return {string} The decoded path.
  414. */
  415. goog.Uri.prototype.getPath = function() {
  416. return this.path_;
  417. };
  418. /**
  419. * Sets the path.
  420. * @throws URIError If opt_decode is true and newPath is malformed (that is,
  421. * if decodeURIComponent fails).
  422. * @param {string} newPath New path value.
  423. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  424. * @return {!goog.Uri} Reference to this URI object.
  425. */
  426. goog.Uri.prototype.setPath = function(newPath, opt_decode) {
  427. this.enforceReadOnly();
  428. this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;
  429. return this;
  430. };
  431. /**
  432. * @return {boolean} Whether the path has been set.
  433. */
  434. goog.Uri.prototype.hasPath = function() {
  435. return !!this.path_;
  436. };
  437. /**
  438. * @return {boolean} Whether the query string has been set.
  439. */
  440. goog.Uri.prototype.hasQuery = function() {
  441. return this.queryData_.toString() !== '';
  442. };
  443. /**
  444. * Sets the query data.
  445. * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.
  446. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  447. * Applies only if queryData is a string.
  448. * @return {!goog.Uri} Reference to this URI object.
  449. */
  450. goog.Uri.prototype.setQueryData = function(queryData, opt_decode) {
  451. this.enforceReadOnly();
  452. if (queryData instanceof goog.Uri.QueryData) {
  453. this.queryData_ = queryData;
  454. this.queryData_.setIgnoreCase(this.ignoreCase_);
  455. } else {
  456. if (!opt_decode) {
  457. // QueryData accepts encoded query string, so encode it if
  458. // opt_decode flag is not true.
  459. queryData = goog.Uri.encodeSpecialChars_(
  460. queryData, goog.Uri.reDisallowedInQuery_);
  461. }
  462. this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);
  463. }
  464. return this;
  465. };
  466. /**
  467. * Sets the URI query.
  468. * @param {string} newQuery New query value.
  469. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  470. * @return {!goog.Uri} Reference to this URI object.
  471. */
  472. goog.Uri.prototype.setQuery = function(newQuery, opt_decode) {
  473. return this.setQueryData(newQuery, opt_decode);
  474. };
  475. /**
  476. * @return {string} The encoded URI query, not including the ?.
  477. */
  478. goog.Uri.prototype.getEncodedQuery = function() {
  479. return this.queryData_.toString();
  480. };
  481. /**
  482. * @return {string} The decoded URI query, not including the ?.
  483. */
  484. goog.Uri.prototype.getDecodedQuery = function() {
  485. return this.queryData_.toDecodedString();
  486. };
  487. /**
  488. * Returns the query data.
  489. * @return {!goog.Uri.QueryData} QueryData object.
  490. */
  491. goog.Uri.prototype.getQueryData = function() {
  492. return this.queryData_;
  493. };
  494. /**
  495. * @return {string} The encoded URI query, not including the ?.
  496. *
  497. * Warning: This method, unlike other getter methods, returns encoded
  498. * value, instead of decoded one.
  499. */
  500. goog.Uri.prototype.getQuery = function() {
  501. return this.getEncodedQuery();
  502. };
  503. /**
  504. * Sets the value of the named query parameters, clearing previous values for
  505. * that key.
  506. *
  507. * @param {string} key The parameter to set.
  508. * @param {*} value The new value.
  509. * @return {!goog.Uri} Reference to this URI object.
  510. */
  511. goog.Uri.prototype.setParameterValue = function(key, value) {
  512. this.enforceReadOnly();
  513. this.queryData_.set(key, value);
  514. return this;
  515. };
  516. /**
  517. * Sets the values of the named query parameters, clearing previous values for
  518. * that key. Not new values will currently be moved to the end of the query
  519. * string.
  520. *
  521. * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])
  522. * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>
  523. *
  524. * @param {string} key The parameter to set.
  525. * @param {*} values The new values. If values is a single
  526. * string then it will be treated as the sole value.
  527. * @return {!goog.Uri} Reference to this URI object.
  528. */
  529. goog.Uri.prototype.setParameterValues = function(key, values) {
  530. this.enforceReadOnly();
  531. if (!goog.isArray(values)) {
  532. values = [String(values)];
  533. }
  534. this.queryData_.setValues(key, values);
  535. return this;
  536. };
  537. /**
  538. * Returns the value<b>s</b> for a given cgi parameter as a list of decoded
  539. * query parameter values.
  540. * @param {string} name The parameter to get values for.
  541. * @return {!Array<?>} The values for a given cgi parameter as a list of
  542. * decoded query parameter values.
  543. */
  544. goog.Uri.prototype.getParameterValues = function(name) {
  545. return this.queryData_.getValues(name);
  546. };
  547. /**
  548. * Returns the first value for a given cgi parameter or undefined if the given
  549. * parameter name does not appear in the query string.
  550. * @param {string} paramName Unescaped parameter name.
  551. * @return {string|undefined} The first value for a given cgi parameter or
  552. * undefined if the given parameter name does not appear in the query
  553. * string.
  554. */
  555. goog.Uri.prototype.getParameterValue = function(paramName) {
  556. // NOTE(nicksantos): This type-cast is a lie when
  557. // preserveParameterTypesCompatibilityFlag is set to true.
  558. // But this should only be set to true in tests.
  559. return /** @type {string|undefined} */ (this.queryData_.get(paramName));
  560. };
  561. /**
  562. * @return {string} The URI fragment, not including the #.
  563. */
  564. goog.Uri.prototype.getFragment = function() {
  565. return this.fragment_;
  566. };
  567. /**
  568. * Sets the URI fragment.
  569. * @throws URIError If opt_decode is true and newFragment is malformed (that is,
  570. * if decodeURIComponent fails).
  571. * @param {string} newFragment New fragment value.
  572. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  573. * @return {!goog.Uri} Reference to this URI object.
  574. */
  575. goog.Uri.prototype.setFragment = function(newFragment, opt_decode) {
  576. this.enforceReadOnly();
  577. this.fragment_ =
  578. opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;
  579. return this;
  580. };
  581. /**
  582. * @return {boolean} Whether the URI has a fragment set.
  583. */
  584. goog.Uri.prototype.hasFragment = function() {
  585. return !!this.fragment_;
  586. };
  587. /**
  588. * Returns true if this has the same domain as that of uri2.
  589. * @param {!goog.Uri} uri2 The URI object to compare to.
  590. * @return {boolean} true if same domain; false otherwise.
  591. */
  592. goog.Uri.prototype.hasSameDomainAs = function(uri2) {
  593. return ((!this.hasDomain() && !uri2.hasDomain()) ||
  594. this.getDomain() == uri2.getDomain()) &&
  595. ((!this.hasPort() && !uri2.hasPort()) ||
  596. this.getPort() == uri2.getPort());
  597. };
  598. /**
  599. * Adds a random parameter to the Uri.
  600. * @return {!goog.Uri} Reference to this Uri object.
  601. */
  602. goog.Uri.prototype.makeUnique = function() {
  603. this.enforceReadOnly();
  604. this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());
  605. return this;
  606. };
  607. /**
  608. * Removes the named query parameter.
  609. *
  610. * @param {string} key The parameter to remove.
  611. * @return {!goog.Uri} Reference to this URI object.
  612. */
  613. goog.Uri.prototype.removeParameter = function(key) {
  614. this.enforceReadOnly();
  615. this.queryData_.remove(key);
  616. return this;
  617. };
  618. /**
  619. * Sets whether Uri is read only. If this goog.Uri is read-only,
  620. * enforceReadOnly_ will be called at the start of any function that may modify
  621. * this Uri.
  622. * @param {boolean} isReadOnly whether this goog.Uri should be read only.
  623. * @return {!goog.Uri} Reference to this Uri object.
  624. */
  625. goog.Uri.prototype.setReadOnly = function(isReadOnly) {
  626. this.isReadOnly_ = isReadOnly;
  627. return this;
  628. };
  629. /**
  630. * @return {boolean} Whether the URI is read only.
  631. */
  632. goog.Uri.prototype.isReadOnly = function() {
  633. return this.isReadOnly_;
  634. };
  635. /**
  636. * Checks if this Uri has been marked as read only, and if so, throws an error.
  637. * This should be called whenever any modifying function is called.
  638. */
  639. goog.Uri.prototype.enforceReadOnly = function() {
  640. if (this.isReadOnly_) {
  641. throw Error('Tried to modify a read-only Uri');
  642. }
  643. };
  644. /**
  645. * Sets whether to ignore case.
  646. * NOTE: If there are already key/value pairs in the QueryData, and
  647. * ignoreCase_ is set to false, the keys will all be lower-cased.
  648. * @param {boolean} ignoreCase whether this goog.Uri should ignore case.
  649. * @return {!goog.Uri} Reference to this Uri object.
  650. */
  651. goog.Uri.prototype.setIgnoreCase = function(ignoreCase) {
  652. this.ignoreCase_ = ignoreCase;
  653. if (this.queryData_) {
  654. this.queryData_.setIgnoreCase(ignoreCase);
  655. }
  656. return this;
  657. };
  658. /**
  659. * @return {boolean} Whether to ignore case.
  660. */
  661. goog.Uri.prototype.getIgnoreCase = function() {
  662. return this.ignoreCase_;
  663. };
  664. //==============================================================================
  665. // Static members
  666. //==============================================================================
  667. /**
  668. * Creates a uri from the string form. Basically an alias of new goog.Uri().
  669. * If a Uri object is passed to parse then it will return a clone of the object.
  670. *
  671. * @throws URIError If parsing the URI is malformed. The passed URI components
  672. * should all be parseable by decodeURIComponent.
  673. * @param {*} uri Raw URI string or instance of Uri
  674. * object.
  675. * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter
  676. * names in #getParameterValue.
  677. * @return {!goog.Uri} The new URI object.
  678. */
  679. goog.Uri.parse = function(uri, opt_ignoreCase) {
  680. return uri instanceof goog.Uri ? uri.clone() :
  681. new goog.Uri(uri, opt_ignoreCase);
  682. };
  683. /**
  684. * Creates a new goog.Uri object from unencoded parts.
  685. *
  686. * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.
  687. * @param {?string=} opt_userInfo username:password.
  688. * @param {?string=} opt_domain www.google.com.
  689. * @param {?number=} opt_port 9830.
  690. * @param {?string=} opt_path /some/path/to/a/file.html.
  691. * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.
  692. * @param {?string=} opt_fragment The fragment without the #.
  693. * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in
  694. * #getParameterValue.
  695. *
  696. * @return {!goog.Uri} The new URI object.
  697. */
  698. goog.Uri.create = function(
  699. opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,
  700. opt_fragment, opt_ignoreCase) {
  701. var uri = new goog.Uri(null, opt_ignoreCase);
  702. // Only set the parts if they are defined and not empty strings.
  703. opt_scheme && uri.setScheme(opt_scheme);
  704. opt_userInfo && uri.setUserInfo(opt_userInfo);
  705. opt_domain && uri.setDomain(opt_domain);
  706. opt_port && uri.setPort(opt_port);
  707. opt_path && uri.setPath(opt_path);
  708. opt_query && uri.setQueryData(opt_query);
  709. opt_fragment && uri.setFragment(opt_fragment);
  710. return uri;
  711. };
  712. /**
  713. * Resolves a relative Uri against a base Uri, accepting both strings and
  714. * Uri objects.
  715. *
  716. * @param {*} base Base Uri.
  717. * @param {*} rel Relative Uri.
  718. * @return {!goog.Uri} Resolved uri.
  719. */
  720. goog.Uri.resolve = function(base, rel) {
  721. if (!(base instanceof goog.Uri)) {
  722. base = goog.Uri.parse(base);
  723. }
  724. if (!(rel instanceof goog.Uri)) {
  725. rel = goog.Uri.parse(rel);
  726. }
  727. return base.resolve(rel);
  728. };
  729. /**
  730. * Removes dot segments in given path component, as described in
  731. * RFC 3986, section 5.2.4.
  732. *
  733. * @param {string} path A non-empty path component.
  734. * @return {string} Path component with removed dot segments.
  735. */
  736. goog.Uri.removeDotSegments = function(path) {
  737. if (path == '..' || path == '.') {
  738. return '';
  739. } else if (
  740. !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {
  741. // This optimization detects uris which do not contain dot-segments,
  742. // and as a consequence do not require any processing.
  743. return path;
  744. } else {
  745. var leadingSlash = goog.string.startsWith(path, '/');
  746. var segments = path.split('/');
  747. var out = [];
  748. for (var pos = 0; pos < segments.length;) {
  749. var segment = segments[pos++];
  750. if (segment == '.') {
  751. if (leadingSlash && pos == segments.length) {
  752. out.push('');
  753. }
  754. } else if (segment == '..') {
  755. if (out.length > 1 || out.length == 1 && out[0] != '') {
  756. out.pop();
  757. }
  758. if (leadingSlash && pos == segments.length) {
  759. out.push('');
  760. }
  761. } else {
  762. out.push(segment);
  763. leadingSlash = true;
  764. }
  765. }
  766. return out.join('/');
  767. }
  768. };
  769. /**
  770. * Decodes a value or returns the empty string if it isn't defined or empty.
  771. * @throws URIError If decodeURIComponent fails to decode val.
  772. * @param {string|undefined} val Value to decode.
  773. * @param {boolean=} opt_preserveReserved If true, restricted characters will
  774. * not be decoded.
  775. * @return {string} Decoded value.
  776. * @private
  777. */
  778. goog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {
  779. // Don't use UrlDecode() here because val is not a query parameter.
  780. if (!val) {
  781. return '';
  782. }
  783. // decodeURI has the same output for '%2f' and '%252f'. We double encode %25
  784. // so that we can distinguish between the 2 inputs. This is later undone by
  785. // removeDoubleEncoding_.
  786. return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :
  787. decodeURIComponent(val);
  788. };
  789. /**
  790. * If unescapedPart is non null, then escapes any characters in it that aren't
  791. * valid characters in a url and also escapes any special characters that
  792. * appear in extra.
  793. *
  794. * @param {*} unescapedPart The string to encode.
  795. * @param {RegExp} extra A character set of characters in [\01-\177].
  796. * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent
  797. * encoding.
  798. * @return {?string} null iff unescapedPart == null.
  799. * @private
  800. */
  801. goog.Uri.encodeSpecialChars_ = function(
  802. unescapedPart, extra, opt_removeDoubleEncoding) {
  803. if (goog.isString(unescapedPart)) {
  804. var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);
  805. if (opt_removeDoubleEncoding) {
  806. // encodeURI double-escapes %XX sequences used to represent restricted
  807. // characters in some URI components, remove the double escaping here.
  808. encoded = goog.Uri.removeDoubleEncoding_(encoded);
  809. }
  810. return encoded;
  811. }
  812. return null;
  813. };
  814. /**
  815. * Converts a character in [\01-\177] to its unicode character equivalent.
  816. * @param {string} ch One character string.
  817. * @return {string} Encoded string.
  818. * @private
  819. */
  820. goog.Uri.encodeChar_ = function(ch) {
  821. var n = ch.charCodeAt(0);
  822. return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);
  823. };
  824. /**
  825. * Removes double percent-encoding from a string.
  826. * @param {string} doubleEncodedString String
  827. * @return {string} String with double encoding removed.
  828. * @private
  829. */
  830. goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {
  831. return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');
  832. };
  833. /**
  834. * Regular expression for characters that are disallowed in the scheme or
  835. * userInfo part of the URI.
  836. * @type {RegExp}
  837. * @private
  838. */
  839. goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g;
  840. /**
  841. * Regular expression for characters that are disallowed in a relative path.
  842. * Colon is included due to RFC 3986 3.3.
  843. * @type {RegExp}
  844. * @private
  845. */
  846. goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g;
  847. /**
  848. * Regular expression for characters that are disallowed in an absolute path.
  849. * @type {RegExp}
  850. * @private
  851. */
  852. goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g;
  853. /**
  854. * Regular expression for characters that are disallowed in the query.
  855. * @type {RegExp}
  856. * @private
  857. */
  858. goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g;
  859. /**
  860. * Regular expression for characters that are disallowed in the fragment.
  861. * @type {RegExp}
  862. * @private
  863. */
  864. goog.Uri.reDisallowedInFragment_ = /#/g;
  865. /**
  866. * Checks whether two URIs have the same domain.
  867. * @param {string} uri1String First URI string.
  868. * @param {string} uri2String Second URI string.
  869. * @return {boolean} true if the two URIs have the same domain; false otherwise.
  870. */
  871. goog.Uri.haveSameDomain = function(uri1String, uri2String) {
  872. // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.
  873. // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.
  874. var pieces1 = goog.uri.utils.split(uri1String);
  875. var pieces2 = goog.uri.utils.split(uri2String);
  876. return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==
  877. pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&
  878. pieces1[goog.uri.utils.ComponentIndex.PORT] ==
  879. pieces2[goog.uri.utils.ComponentIndex.PORT];
  880. };
  881. /**
  882. * Class used to represent URI query parameters. It is essentially a hash of
  883. * name-value pairs, though a name can be present more than once.
  884. *
  885. * Has the same interface as the collections in goog.structs.
  886. *
  887. * @param {?string=} opt_query Optional encoded query string to parse into
  888. * the object.
  889. * @param {goog.Uri=} opt_uri Optional uri object that should have its
  890. * cache invalidated when this object updates. Deprecated -- this
  891. * is no longer required.
  892. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter
  893. * name in #get.
  894. * @constructor
  895. * @struct
  896. * @final
  897. */
  898. goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {
  899. /**
  900. * The map containing name/value or name/array-of-values pairs.
  901. * May be null if it requires parsing from the query string.
  902. *
  903. * We need to use a Map because we cannot guarantee that the key names will
  904. * not be problematic for IE.
  905. *
  906. * @private {goog.structs.Map<string, !Array<*>>}
  907. */
  908. this.keyMap_ = null;
  909. /**
  910. * The number of params, or null if it requires computing.
  911. * @private {?number}
  912. */
  913. this.count_ = null;
  914. /**
  915. * Encoded query string, or null if it requires computing from the key map.
  916. * @private {?string}
  917. */
  918. this.encodedQuery_ = opt_query || null;
  919. /**
  920. * If true, ignore the case of the parameter name in #get.
  921. * @private {boolean}
  922. */
  923. this.ignoreCase_ = !!opt_ignoreCase;
  924. };
  925. /**
  926. * If the underlying key map is not yet initialized, it parses the
  927. * query string and fills the map with parsed data.
  928. * @private
  929. */
  930. goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {
  931. if (!this.keyMap_) {
  932. this.keyMap_ = new goog.structs.Map();
  933. this.count_ = 0;
  934. if (this.encodedQuery_) {
  935. var self = this;
  936. goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {
  937. self.add(goog.string.urlDecode(name), value);
  938. });
  939. }
  940. }
  941. };
  942. /**
  943. * Creates a new query data instance from a map of names and values.
  944. *
  945. * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter
  946. * names to parameter value. If parameter value is an array, it is
  947. * treated as if the key maps to each individual value in the
  948. * array.
  949. * @param {goog.Uri=} opt_uri URI object that should have its cache
  950. * invalidated when this object updates.
  951. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter
  952. * name in #get.
  953. * @return {!goog.Uri.QueryData} The populated query data instance.
  954. */
  955. goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {
  956. var keys = goog.structs.getKeys(map);
  957. if (typeof keys == 'undefined') {
  958. throw Error('Keys are undefined');
  959. }
  960. var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);
  961. var values = goog.structs.getValues(map);
  962. for (var i = 0; i < keys.length; i++) {
  963. var key = keys[i];
  964. var value = values[i];
  965. if (!goog.isArray(value)) {
  966. queryData.add(key, value);
  967. } else {
  968. queryData.setValues(key, value);
  969. }
  970. }
  971. return queryData;
  972. };
  973. /**
  974. * Creates a new query data instance from parallel arrays of parameter names
  975. * and values. Allows for duplicate parameter names. Throws an error if the
  976. * lengths of the arrays differ.
  977. *
  978. * @param {!Array<string>} keys Parameter names.
  979. * @param {!Array<?>} values Parameter values.
  980. * @param {goog.Uri=} opt_uri URI object that should have its cache
  981. * invalidated when this object updates.
  982. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter
  983. * name in #get.
  984. * @return {!goog.Uri.QueryData} The populated query data instance.
  985. */
  986. goog.Uri.QueryData.createFromKeysValues = function(
  987. keys, values, opt_uri, opt_ignoreCase) {
  988. if (keys.length != values.length) {
  989. throw Error('Mismatched lengths for keys/values');
  990. }
  991. var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);
  992. for (var i = 0; i < keys.length; i++) {
  993. queryData.add(keys[i], values[i]);
  994. }
  995. return queryData;
  996. };
  997. /**
  998. * @return {?number} The number of parameters.
  999. */
  1000. goog.Uri.QueryData.prototype.getCount = function() {
  1001. this.ensureKeyMapInitialized_();
  1002. return this.count_;
  1003. };
  1004. /**
  1005. * Adds a key value pair.
  1006. * @param {string} key Name.
  1007. * @param {*} value Value.
  1008. * @return {!goog.Uri.QueryData} Instance of this object.
  1009. */
  1010. goog.Uri.QueryData.prototype.add = function(key, value) {
  1011. this.ensureKeyMapInitialized_();
  1012. this.invalidateCache_();
  1013. key = this.getKeyName_(key);
  1014. var values = this.keyMap_.get(key);
  1015. if (!values) {
  1016. this.keyMap_.set(key, (values = []));
  1017. }
  1018. values.push(value);
  1019. this.count_ = goog.asserts.assertNumber(this.count_) + 1;
  1020. return this;
  1021. };
  1022. /**
  1023. * Removes all the params with the given key.
  1024. * @param {string} key Name.
  1025. * @return {boolean} Whether any parameter was removed.
  1026. */
  1027. goog.Uri.QueryData.prototype.remove = function(key) {
  1028. this.ensureKeyMapInitialized_();
  1029. key = this.getKeyName_(key);
  1030. if (this.keyMap_.containsKey(key)) {
  1031. this.invalidateCache_();
  1032. // Decrement parameter count.
  1033. this.count_ =
  1034. goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;
  1035. return this.keyMap_.remove(key);
  1036. }
  1037. return false;
  1038. };
  1039. /**
  1040. * Clears the parameters.
  1041. */
  1042. goog.Uri.QueryData.prototype.clear = function() {
  1043. this.invalidateCache_();
  1044. this.keyMap_ = null;
  1045. this.count_ = 0;
  1046. };
  1047. /**
  1048. * @return {boolean} Whether we have any parameters.
  1049. */
  1050. goog.Uri.QueryData.prototype.isEmpty = function() {
  1051. this.ensureKeyMapInitialized_();
  1052. return this.count_ == 0;
  1053. };
  1054. /**
  1055. * Whether there is a parameter with the given name
  1056. * @param {string} key The parameter name to check for.
  1057. * @return {boolean} Whether there is a parameter with the given name.
  1058. */
  1059. goog.Uri.QueryData.prototype.containsKey = function(key) {
  1060. this.ensureKeyMapInitialized_();
  1061. key = this.getKeyName_(key);
  1062. return this.keyMap_.containsKey(key);
  1063. };
  1064. /**
  1065. * Whether there is a parameter with the given value.
  1066. * @param {*} value The value to check for.
  1067. * @return {boolean} Whether there is a parameter with the given value.
  1068. */
  1069. goog.Uri.QueryData.prototype.containsValue = function(value) {
  1070. // NOTE(arv): This solution goes through all the params even if it was the
  1071. // first param. We can get around this by not reusing code or by switching to
  1072. // iterators.
  1073. var vals = this.getValues();
  1074. return goog.array.contains(vals, value);
  1075. };
  1076. /**
  1077. * Runs a callback on every key-value pair in the map, including duplicate keys.
  1078. * This won't maintain original order when duplicate keys are interspersed (like
  1079. * getKeys() / getValues()).
  1080. * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f
  1081. * @param {SCOPE=} opt_scope The value of "this" inside f.
  1082. * @template SCOPE
  1083. */
  1084. goog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {
  1085. this.ensureKeyMapInitialized_();
  1086. this.keyMap_.forEach(function(values, key) {
  1087. goog.array.forEach(values, function(value) {
  1088. f.call(opt_scope, value, key, this);
  1089. }, this);
  1090. }, this);
  1091. };
  1092. /**
  1093. * Returns all the keys of the parameters. If a key is used multiple times
  1094. * it will be included multiple times in the returned array
  1095. * @return {!Array<string>} All the keys of the parameters.
  1096. */
  1097. goog.Uri.QueryData.prototype.getKeys = function() {
  1098. this.ensureKeyMapInitialized_();
  1099. // We need to get the values to know how many keys to add.
  1100. var vals = this.keyMap_.getValues();
  1101. var keys = this.keyMap_.getKeys();
  1102. var rv = [];
  1103. for (var i = 0; i < keys.length; i++) {
  1104. var val = vals[i];
  1105. for (var j = 0; j < val.length; j++) {
  1106. rv.push(keys[i]);
  1107. }
  1108. }
  1109. return rv;
  1110. };
  1111. /**
  1112. * Returns all the values of the parameters with the given name. If the query
  1113. * data has no such key this will return an empty array. If no key is given
  1114. * all values wil be returned.
  1115. * @param {string=} opt_key The name of the parameter to get the values for.
  1116. * @return {!Array<?>} All the values of the parameters with the given name.
  1117. */
  1118. goog.Uri.QueryData.prototype.getValues = function(opt_key) {
  1119. this.ensureKeyMapInitialized_();
  1120. var rv = [];
  1121. if (goog.isString(opt_key)) {
  1122. if (this.containsKey(opt_key)) {
  1123. rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));
  1124. }
  1125. } else {
  1126. // Return all values.
  1127. var values = this.keyMap_.getValues();
  1128. for (var i = 0; i < values.length; i++) {
  1129. rv = goog.array.concat(rv, values[i]);
  1130. }
  1131. }
  1132. return rv;
  1133. };
  1134. /**
  1135. * Sets a key value pair and removes all other keys with the same value.
  1136. *
  1137. * @param {string} key Name.
  1138. * @param {*} value Value.
  1139. * @return {!goog.Uri.QueryData} Instance of this object.
  1140. */
  1141. goog.Uri.QueryData.prototype.set = function(key, value) {
  1142. this.ensureKeyMapInitialized_();
  1143. this.invalidateCache_();
  1144. // TODO(chrishenry): This could be better written as
  1145. // this.remove(key), this.add(key, value), but that would reorder
  1146. // the key (since the key is first removed and then added at the
  1147. // end) and we would have to fix unit tests that depend on key
  1148. // ordering.
  1149. key = this.getKeyName_(key);
  1150. if (this.containsKey(key)) {
  1151. this.count_ =
  1152. goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;
  1153. }
  1154. this.keyMap_.set(key, [value]);
  1155. this.count_ = goog.asserts.assertNumber(this.count_) + 1;
  1156. return this;
  1157. };
  1158. /**
  1159. * Returns the first value associated with the key. If the query data has no
  1160. * such key this will return undefined or the optional default.
  1161. * @param {string} key The name of the parameter to get the value for.
  1162. * @param {*=} opt_default The default value to return if the query data
  1163. * has no such key.
  1164. * @return {*} The first string value associated with the key, or opt_default
  1165. * if there's no value.
  1166. */
  1167. goog.Uri.QueryData.prototype.get = function(key, opt_default) {
  1168. var values = key ? this.getValues(key) : [];
  1169. if (goog.Uri.preserveParameterTypesCompatibilityFlag) {
  1170. return values.length > 0 ? values[0] : opt_default;
  1171. } else {
  1172. return values.length > 0 ? String(values[0]) : opt_default;
  1173. }
  1174. };
  1175. /**
  1176. * Sets the values for a key. If the key already exists, this will
  1177. * override all of the existing values that correspond to the key.
  1178. * @param {string} key The key to set values for.
  1179. * @param {!Array<?>} values The values to set.
  1180. */
  1181. goog.Uri.QueryData.prototype.setValues = function(key, values) {
  1182. this.remove(key);
  1183. if (values.length > 0) {
  1184. this.invalidateCache_();
  1185. this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));
  1186. this.count_ = goog.asserts.assertNumber(this.count_) + values.length;
  1187. }
  1188. };
  1189. /**
  1190. * @return {string} Encoded query string.
  1191. * @override
  1192. */
  1193. goog.Uri.QueryData.prototype.toString = function() {
  1194. if (this.encodedQuery_) {
  1195. return this.encodedQuery_;
  1196. }
  1197. if (!this.keyMap_) {
  1198. return '';
  1199. }
  1200. var sb = [];
  1201. // In the past, we use this.getKeys() and this.getVals(), but that
  1202. // generates a lot of allocations as compared to simply iterating
  1203. // over the keys.
  1204. var keys = this.keyMap_.getKeys();
  1205. for (var i = 0; i < keys.length; i++) {
  1206. var key = keys[i];
  1207. var encodedKey = goog.string.urlEncode(key);
  1208. var val = this.getValues(key);
  1209. for (var j = 0; j < val.length; j++) {
  1210. var param = encodedKey;
  1211. // Ensure that null and undefined are encoded into the url as
  1212. // literal strings.
  1213. if (val[j] !== '') {
  1214. param += '=' + goog.string.urlEncode(val[j]);
  1215. }
  1216. sb.push(param);
  1217. }
  1218. }
  1219. return this.encodedQuery_ = sb.join('&');
  1220. };
  1221. /**
  1222. * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on
  1223. * any of the URI components).
  1224. * @return {string} Decoded query string.
  1225. */
  1226. goog.Uri.QueryData.prototype.toDecodedString = function() {
  1227. return goog.Uri.decodeOrEmpty_(this.toString());
  1228. };
  1229. /**
  1230. * Invalidate the cache.
  1231. * @private
  1232. */
  1233. goog.Uri.QueryData.prototype.invalidateCache_ = function() {
  1234. this.encodedQuery_ = null;
  1235. };
  1236. /**
  1237. * Removes all keys that are not in the provided list. (Modifies this object.)
  1238. * @param {Array<string>} keys The desired keys.
  1239. * @return {!goog.Uri.QueryData} a reference to this object.
  1240. */
  1241. goog.Uri.QueryData.prototype.filterKeys = function(keys) {
  1242. this.ensureKeyMapInitialized_();
  1243. this.keyMap_.forEach(function(value, key) {
  1244. if (!goog.array.contains(keys, key)) {
  1245. this.remove(key);
  1246. }
  1247. }, this);
  1248. return this;
  1249. };
  1250. /**
  1251. * Clone the query data instance.
  1252. * @return {!goog.Uri.QueryData} New instance of the QueryData object.
  1253. */
  1254. goog.Uri.QueryData.prototype.clone = function() {
  1255. var rv = new goog.Uri.QueryData();
  1256. rv.encodedQuery_ = this.encodedQuery_;
  1257. if (this.keyMap_) {
  1258. rv.keyMap_ = this.keyMap_.clone();
  1259. rv.count_ = this.count_;
  1260. }
  1261. return rv;
  1262. };
  1263. /**
  1264. * Helper function to get the key name from a JavaScript object. Converts
  1265. * the object to a string, and to lower case if necessary.
  1266. * @private
  1267. * @param {*} arg The object to get a key name from.
  1268. * @return {string} valid key name which can be looked up in #keyMap_.
  1269. */
  1270. goog.Uri.QueryData.prototype.getKeyName_ = function(arg) {
  1271. var keyName = String(arg);
  1272. if (this.ignoreCase_) {
  1273. keyName = keyName.toLowerCase();
  1274. }
  1275. return keyName;
  1276. };
  1277. /**
  1278. * Ignore case in parameter names.
  1279. * NOTE: If there are already key/value pairs in the QueryData, and
  1280. * ignoreCase_ is set to false, the keys will all be lower-cased.
  1281. * @param {boolean} ignoreCase whether this goog.Uri should ignore case.
  1282. */
  1283. goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {
  1284. var resetKeys = ignoreCase && !this.ignoreCase_;
  1285. if (resetKeys) {
  1286. this.ensureKeyMapInitialized_();
  1287. this.invalidateCache_();
  1288. this.keyMap_.forEach(function(value, key) {
  1289. var lowerCase = key.toLowerCase();
  1290. if (key != lowerCase) {
  1291. this.remove(key);
  1292. this.setValues(lowerCase, value);
  1293. }
  1294. }, this);
  1295. }
  1296. this.ignoreCase_ = ignoreCase;
  1297. };
  1298. /**
  1299. * Extends a query data object with another query data or map like object. This
  1300. * operates 'in-place', it does not create a new QueryData object.
  1301. *
  1302. * @param {...(?goog.Uri.QueryData|?goog.structs.Map<?, ?>|?Object)} var_args
  1303. * The object from which key value pairs will be copied.
  1304. * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different
  1305. * types of parameters.
  1306. */
  1307. goog.Uri.QueryData.prototype.extend = function(var_args) {
  1308. for (var i = 0; i < arguments.length; i++) {
  1309. var data = arguments[i];
  1310. goog.structs.forEach(
  1311. data, function(value, key) { this.add(key, value); }, this);
  1312. }
  1313. };