# lib/goog/uri/uri.js

    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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415/**16 * @fileoverview Class for parsing and formatting URIs.17 *18 * Use goog.Uri(string) to parse a URI string.  Use goog.Uri.create(...) to19 * create a new instance of the goog.Uri object from Uri parts.20 *21 * e.g: <code>var myUri = new goog.Uri(window.location);</code>22 *23 * Implements RFC 3986 for parsing/formatting URIs.24 * http://www.ietf.org/rfc/rfc3986.txt25 *26 * Some changes have been made to the interface (more like .NETs), though the27 * internal representation is now of un-encoded parts, this will change the28 * behavior slightly.29 *30 */3132goog.provide('goog.Uri');33goog.provide('goog.Uri.QueryData');3435goog.require('goog.array');36goog.require('goog.string');37goog.require('goog.structs');38goog.require('goog.structs.Map');39goog.require('goog.uri.utils');40goog.require('goog.uri.utils.ComponentIndex');41goog.require('goog.uri.utils.StandardQueryParam');42434445/**46 * This class contains setters and getters for the parts of the URI.47 * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part48 * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the49 * decoded path, <code>/foo bar</code>.50 *51 * Reserved characters (see RFC 3986 section 2.2) can be present in52 * their percent-encoded form in scheme, domain, and path URI components and53 * will not be auto-decoded. For example:54 * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will55 * return <code>relative/path%2fto/resource</code>.56 *57 * The constructor accepts an optional unparsed, raw URI string.  The parser58 * is relaxed, so special characters that aren't escaped but don't cause59 * ambiguities will not cause parse failures.60 *61 * All setters return <code>this</code> and so may be chained, a la62 * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.63 *64 * @param {*=} opt_uri Optional string URI to parse65 *        (use goog.Uri.create() to create a URI from parts), or if66 *        a goog.Uri is passed, a clone is created.67 * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore68 * the case of the parameter name.69 *70 * @constructor71 */72goog.Uri = function(opt_uri, opt_ignoreCase) {73  // Parse in the uri string74  var m;75  if (opt_uri instanceof goog.Uri) {76    this.ignoreCase_ = goog.isDef(opt_ignoreCase) ?77        opt_ignoreCase : opt_uri.getIgnoreCase();78    this.setScheme(opt_uri.getScheme());79    this.setUserInfo(opt_uri.getUserInfo());80    this.setDomain(opt_uri.getDomain());81    this.setPort(opt_uri.getPort());82    this.setPath(opt_uri.getPath());83    this.setQueryData(opt_uri.getQueryData().clone());84    this.setFragment(opt_uri.getFragment());85  } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {86    this.ignoreCase_ = !!opt_ignoreCase;8788    // Set the parts -- decoding as we do so.89    // COMPATABILITY NOTE - In IE, unmatched fields may be empty strings,90    // whereas in other browsers they will be undefined.91    this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);92    this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);93    this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);94    this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);95    this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);96    this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);97    this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);9899  } else {100    this.ignoreCase_ = !!opt_ignoreCase;101    this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);102  }103};104105106/**107 * If true, we preserve the type of query parameters set programmatically.108 *109 * This means that if you set a parameter to a boolean, and then call110 * getParameterValue, you will get a boolean back.111 *112 * If false, we will coerce parameters to strings, just as they would113 * appear in real URIs.114 *115 * TODO(nicksantos): Remove this once people have time to fix all tests.116 *117 * @type {boolean}118 */119goog.Uri.preserveParameterTypesCompatibilityFlag = false;120121122/**123 * Parameter name added to stop caching.124 * @type {string}125 */126goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;127128129/**130 * Scheme such as "http".131 * @type {string}132 * @private133 */134goog.Uri.prototype.scheme_ = '';135136137/**138 * User credentials in the form "username:password".139 * @type {string}140 * @private141 */142goog.Uri.prototype.userInfo_ = '';143144145/**146 * Domain part, e.g. "www.google.com".147 * @type {string}148 * @private149 */150goog.Uri.prototype.domain_ = '';151152153/**154 * Port, e.g. 8080.155 * @type {?number}156 * @private157 */158goog.Uri.prototype.port_ = null;159160161/**162 * Path, e.g. "/tests/img.png".163 * @type {string}164 * @private165 */166goog.Uri.prototype.path_ = '';167168169/**170 * Object representing query data.171 * @type {!goog.Uri.QueryData}172 * @private173 */174goog.Uri.prototype.queryData_;175176177/**178 * The fragment without the #.179 * @type {string}180 * @private181 */182goog.Uri.prototype.fragment_ = '';183184185/**186 * Whether or not this Uri should be treated as Read Only.187 * @type {boolean}188 * @private189 */190goog.Uri.prototype.isReadOnly_ = false;191192193/**194 * Whether or not to ignore case when comparing query params.195 * @type {boolean}196 * @private197 */198goog.Uri.prototype.ignoreCase_ = false;199200201/**202 * @return {string} The string form of the url.203 * @override204 */205goog.Uri.prototype.toString = function() {206  var out = [];207208  var scheme = this.getScheme();209  if (scheme) {210    out.push(goog.Uri.encodeSpecialChars_(211        scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), ':');212  }213214  var domain = this.getDomain();215  if (domain) {216    out.push('//');217218    var userInfo = this.getUserInfo();219    if (userInfo) {220      out.push(goog.Uri.encodeSpecialChars_(221          userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), '@');222    }223224    out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));225226    var port = this.getPort();227    if (port != null) {228      out.push(':', String(port));229    }230  }231232  var path = this.getPath();233  if (path) {234    if (this.hasDomain() && path.charAt(0) != '/') {235      out.push('/');236    }237    out.push(goog.Uri.encodeSpecialChars_(238        path,239        path.charAt(0) == '/' ?240            goog.Uri.reDisallowedInAbsolutePath_ :241            goog.Uri.reDisallowedInRelativePath_,242        true));243  }244245  var query = this.getEncodedQuery();246  if (query) {247    out.push('?', query);248  }249250  var fragment = this.getFragment();251  if (fragment) {252    out.push('#', goog.Uri.encodeSpecialChars_(253        fragment, goog.Uri.reDisallowedInFragment_));254  }255  return out.join('');256};257258259/**260 * Resolves the given relative URI (a goog.Uri object), using the URI261 * represented by this instance as the base URI.262 *263 * There are several kinds of relative URIs:<br>264 * 1. foo - replaces the last part of the path, the whole query and fragment<br>265 * 2. /foo - replaces the the path, the query and fragment<br>266 * 3. //foo - replaces everything from the domain on.  foo is a domain name<br>267 * 4. ?foo - replace the query and fragment<br>268 * 5. #foo - replace the fragment only269 *270 * Additionally, if relative URI has a non-empty path, all ".." and "."271 * segments will be resolved, as described in RFC 3986.272 *273 * @param {goog.Uri} relativeUri The relative URI to resolve.274 * @return {!goog.Uri} The resolved URI.275 */276goog.Uri.prototype.resolve = function(relativeUri) {277278  var absoluteUri = this.clone();279280  // we satisfy these conditions by looking for the first part of relativeUri281  // that is not blank and applying defaults to the rest282283  var overridden = relativeUri.hasScheme();284285  if (overridden) {286    absoluteUri.setScheme(relativeUri.getScheme());287  } else {288    overridden = relativeUri.hasUserInfo();289  }290291  if (overridden) {292    absoluteUri.setUserInfo(relativeUri.getUserInfo());293  } else {294    overridden = relativeUri.hasDomain();295  }296297  if (overridden) {298    absoluteUri.setDomain(relativeUri.getDomain());299  } else {300    overridden = relativeUri.hasPort();301  }302303  var path = relativeUri.getPath();304  if (overridden) {305    absoluteUri.setPort(relativeUri.getPort());306  } else {307    overridden = relativeUri.hasPath();308    if (overridden) {309      // resolve path properly310      if (path.charAt(0) != '/') {311        // path is relative312        if (this.hasDomain() && !this.hasPath()) {313          // RFC 3986, section 5.2.3, case 1314          path = '/' + path;315        } else {316          // RFC 3986, section 5.2.3, case 2317          var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');318          if (lastSlashIndex != -1) {319            path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;320          }321        }322      }323      path = goog.Uri.removeDotSegments(path);324    }325  }326327  if (overridden) {328    absoluteUri.setPath(path);329  } else {330    overridden = relativeUri.hasQuery();331  }332333  if (overridden) {334    absoluteUri.setQueryData(relativeUri.getDecodedQuery());335  } else {336    overridden = relativeUri.hasFragment();337  }338339  if (overridden) {340    absoluteUri.setFragment(relativeUri.getFragment());341  }342343  return absoluteUri;344};345346347/**348 * Clones the URI instance.349 * @return {!goog.Uri} New instance of the URI object.350 */351goog.Uri.prototype.clone = function() {352  return new goog.Uri(this);353};354355356/**357 * @return {string} The encoded scheme/protocol for the URI.358 */359goog.Uri.prototype.getScheme = function() {360  return this.scheme_;361};362363364/**365 * Sets the scheme/protocol.366 * @param {string} newScheme New scheme value.367 * @param {boolean=} opt_decode Optional param for whether to decode new value.368 * @return {!goog.Uri} Reference to this URI object.369 */370goog.Uri.prototype.setScheme = function(newScheme, opt_decode) {371  this.enforceReadOnly();372  this.scheme_ = opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) :373      newScheme;374375  // remove an : at the end of the scheme so somebody can pass in376  // window.location.protocol377  if (this.scheme_) {378    this.scheme_ = this.scheme_.replace(/:$/, '');379  }380  return this;381};382383384/**385 * @return {boolean} Whether the scheme has been set.386 */387goog.Uri.prototype.hasScheme = function() {388  return !!this.scheme_;389};390391392/**393 * @return {string} The decoded user info.394 */395goog.Uri.prototype.getUserInfo = function() {396  return this.userInfo_;397};398399400/**401 * Sets the userInfo.402 * @param {string} newUserInfo New userInfo value.403 * @param {boolean=} opt_decode Optional param for whether to decode new value.404 * @return {!goog.Uri} Reference to this URI object.405 */406goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {407  this.enforceReadOnly();408  this.userInfo_ = opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) :409                   newUserInfo;410  return this;411};412413414/**415 * @return {boolean} Whether the user info has been set.416 */417goog.Uri.prototype.hasUserInfo = function() {418  return !!this.userInfo_;419};420421422/**423 * @return {string} The decoded domain.424 */425goog.Uri.prototype.getDomain = function() {426  return this.domain_;427};428429430/**431 * Sets the domain.432 * @param {string} newDomain New domain value.433 * @param {boolean=} opt_decode Optional param for whether to decode new value.434 * @return {!goog.Uri} Reference to this URI object.435 */436goog.Uri.prototype.setDomain = function(newDomain, opt_decode) {437  this.enforceReadOnly();438  this.domain_ = opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) :439      newDomain;440  return this;441};442443444/**445 * @return {boolean} Whether the domain has been set.446 */447goog.Uri.prototype.hasDomain = function() {448  return !!this.domain_;449};450451452/**453 * @return {?number} The port number.454 */455goog.Uri.prototype.getPort = function() {456  return this.port_;457};458459460/**461 * Sets the port number.462 * @param {*} newPort Port number. Will be explicitly casted to a number.463 * @return {!goog.Uri} Reference to this URI object.464 */465goog.Uri.prototype.setPort = function(newPort) {466  this.enforceReadOnly();467468  if (newPort) {469    newPort = Number(newPort);470    if (isNaN(newPort) || newPort < 0) {471      throw Error('Bad port number ' + newPort);472    }473    this.port_ = newPort;474  } else {475    this.port_ = null;476  }477478  return this;479};480481482/**483 * @return {boolean} Whether the port has been set.484 */485goog.Uri.prototype.hasPort = function() {486  return this.port_ != null;487};488489490/**491  * @return {string} The decoded path.492 */493goog.Uri.prototype.getPath = function() {494  return this.path_;495};496497498/**499 * Sets the path.500 * @param {string} newPath New path value.501 * @param {boolean=} opt_decode Optional param for whether to decode new value.502 * @return {!goog.Uri} Reference to this URI object.503 */504goog.Uri.prototype.setPath = function(newPath, opt_decode) {505  this.enforceReadOnly();506  this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;507  return this;508};509510511/**512 * @return {boolean} Whether the path has been set.513 */514goog.Uri.prototype.hasPath = function() {515  return !!this.path_;516};517518519/**520 * @return {boolean} Whether the query string has been set.521 */522goog.Uri.prototype.hasQuery = function() {523  return this.queryData_.toString() !== '';524};525526527/**528 * Sets the query data.529 * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.530 * @param {boolean=} opt_decode Optional param for whether to decode new value.531 *     Applies only if queryData is a string.532 * @return {!goog.Uri} Reference to this URI object.533 */534goog.Uri.prototype.setQueryData = function(queryData, opt_decode) {535  this.enforceReadOnly();536537  if (queryData instanceof goog.Uri.QueryData) {538    this.queryData_ = queryData;539    this.queryData_.setIgnoreCase(this.ignoreCase_);540  } else {541    if (!opt_decode) {542      // QueryData accepts encoded query string, so encode it if543      // opt_decode flag is not true.544      queryData = goog.Uri.encodeSpecialChars_(queryData,545                                               goog.Uri.reDisallowedInQuery_);546    }547    this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);548  }549550  return this;551};552553554/**555 * Sets the URI query.556 * @param {string} newQuery New query value.557 * @param {boolean=} opt_decode Optional param for whether to decode new value.558 * @return {!goog.Uri} Reference to this URI object.559 */560goog.Uri.prototype.setQuery = function(newQuery, opt_decode) {561  return this.setQueryData(newQuery, opt_decode);562};563564565/**566 * @return {string} The encoded URI query, not including the ?.567 */568goog.Uri.prototype.getEncodedQuery = function() {569  return this.queryData_.toString();570};571572573/**574 * @return {string} The decoded URI query, not including the ?.575 */576goog.Uri.prototype.getDecodedQuery = function() {577  return this.queryData_.toDecodedString();578};579580581/**582 * Returns the query data.583 * @return {!goog.Uri.QueryData} QueryData object.584 */585goog.Uri.prototype.getQueryData = function() {586  return this.queryData_;587};588589590/**591 * @return {string} The encoded URI query, not including the ?.592 *593 * Warning: This method, unlike other getter methods, returns encoded594 * value, instead of decoded one.595 */596goog.Uri.prototype.getQuery = function() {597  return this.getEncodedQuery();598};599600601/**602 * Sets the value of the named query parameters, clearing previous values for603 * that key.604 *605 * @param {string} key The parameter to set.606 * @param {*} value The new value.607 * @return {!goog.Uri} Reference to this URI object.608 */609goog.Uri.prototype.setParameterValue = function(key, value) {610  this.enforceReadOnly();611  this.queryData_.set(key, value);612  return this;613};614615616/**617 * Sets the values of the named query parameters, clearing previous values for618 * that key.  Not new values will currently be moved to the end of the query619 * string.620 *621 * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])622 * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>623 *624 * @param {string} key The parameter to set.625 * @param {*} values The new values. If values is a single626 *     string then it will be treated as the sole value.627 * @return {!goog.Uri} Reference to this URI object.628 */629goog.Uri.prototype.setParameterValues = function(key, values) {630  this.enforceReadOnly();631632  if (!goog.isArray(values)) {633    values = [String(values)];634  }635636  // TODO(nicksantos): This cast shouldn't be necessary.637  this.queryData_.setValues(key, /** @type {Array} */ (values));638639  return this;640};641642643/**644 * Returns the value<b>s</b> for a given cgi parameter as a list of decoded645 * query parameter values.646 * @param {string} name The parameter to get values for.647 * @return {!Array} The values for a given cgi parameter as a list of648 *     decoded query parameter values.649 */650goog.Uri.prototype.getParameterValues = function(name) {651  return this.queryData_.getValues(name);652};653654655/**656 * Returns the first value for a given cgi parameter or undefined if the given657 * parameter name does not appear in the query string.658 * @param {string} paramName Unescaped parameter name.659 * @return {string|undefined} The first value for a given cgi parameter or660 *     undefined if the given parameter name does not appear in the query661 *     string.662 */663goog.Uri.prototype.getParameterValue = function(paramName) {664  // NOTE(nicksantos): This type-cast is a lie when665  // preserveParameterTypesCompatibilityFlag is set to true.666  // But this should only be set to true in tests.667  return /** @type {string|undefined} */ (this.queryData_.get(paramName));668};669670671/**672 * @return {string} The URI fragment, not including the #.673 */674goog.Uri.prototype.getFragment = function() {675  return this.fragment_;676};677678679/**680 * Sets the URI fragment.681 * @param {string} newFragment New fragment value.682 * @param {boolean=} opt_decode Optional param for whether to decode new value.683 * @return {!goog.Uri} Reference to this URI object.684 */685goog.Uri.prototype.setFragment = function(newFragment, opt_decode) {686  this.enforceReadOnly();687  this.fragment_ = opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) :688                   newFragment;689  return this;690};691692693/**694 * @return {boolean} Whether the URI has a fragment set.695 */696goog.Uri.prototype.hasFragment = function() {697  return !!this.fragment_;698};699700701/**702 * Returns true if this has the same domain as that of uri2.703 * @param {goog.Uri} uri2 The URI object to compare to.704 * @return {boolean} true if same domain; false otherwise.705 */706goog.Uri.prototype.hasSameDomainAs = function(uri2) {707  return ((!this.hasDomain() && !uri2.hasDomain()) ||708          this.getDomain() == uri2.getDomain()) &&709      ((!this.hasPort() && !uri2.hasPort()) ||710          this.getPort() == uri2.getPort());711};712713714/**715 * Adds a random parameter to the Uri.716 * @return {!goog.Uri} Reference to this Uri object.717 */718goog.Uri.prototype.makeUnique = function() {719  this.enforceReadOnly();720  this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());721722  return this;723};724725726/**727 * Removes the named query parameter.728 *729 * @param {string} key The parameter to remove.730 * @return {!goog.Uri} Reference to this URI object.731 */732goog.Uri.prototype.removeParameter = function(key) {733  this.enforceReadOnly();734  this.queryData_.remove(key);735  return this;736};737738739/**740 * Sets whether Uri is read only. If this goog.Uri is read-only,741 * enforceReadOnly_ will be called at the start of any function that may modify742 * this Uri.743 * @param {boolean} isReadOnly whether this goog.Uri should be read only.744 * @return {!goog.Uri} Reference to this Uri object.745 */746goog.Uri.prototype.setReadOnly = function(isReadOnly) {747  this.isReadOnly_ = isReadOnly;748  return this;749};750751752/**753 * @return {boolean} Whether the URI is read only.754 */755goog.Uri.prototype.isReadOnly = function() {756  return this.isReadOnly_;757};758759760/**761 * Checks if this Uri has been marked as read only, and if so, throws an error.762 * This should be called whenever any modifying function is called.763 */764goog.Uri.prototype.enforceReadOnly = function() {765  if (this.isReadOnly_) {766    throw Error('Tried to modify a read-only Uri');767  }768};769770771/**772 * Sets whether to ignore case.773 * NOTE: If there are already key/value pairs in the QueryData, and774 * ignoreCase_ is set to false, the keys will all be lower-cased.775 * @param {boolean} ignoreCase whether this goog.Uri should ignore case.776 * @return {!goog.Uri} Reference to this Uri object.777 */778goog.Uri.prototype.setIgnoreCase = function(ignoreCase) {779  this.ignoreCase_ = ignoreCase;780  if (this.queryData_) {781    this.queryData_.setIgnoreCase(ignoreCase);782  }783  return this;784};785786787/**788 * @return {boolean} Whether to ignore case.789 */790goog.Uri.prototype.getIgnoreCase = function() {791  return this.ignoreCase_;792};793794795//==============================================================================796// Static members797//==============================================================================798799800/**801 * Creates a uri from the string form.  Basically an alias of new goog.Uri().802 * If a Uri object is passed to parse then it will return a clone of the object.803 *804 * @param {*} uri Raw URI string or instance of Uri805 *     object.806 * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter807 * names in #getParameterValue.808 * @return {!goog.Uri} The new URI object.809 */810goog.Uri.parse = function(uri, opt_ignoreCase) {811  return uri instanceof goog.Uri ?812         uri.clone() : new goog.Uri(uri, opt_ignoreCase);813};814815816/**817 * Creates a new goog.Uri object from unencoded parts.818 *819 * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.820 * @param {?string=} opt_userInfo username:password.821 * @param {?string=} opt_domain www.google.com.822 * @param {?number=} opt_port 9830.823 * @param {?string=} opt_path /some/path/to/a/file.html.824 * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.825 * @param {?string=} opt_fragment The fragment without the #.826 * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in827 *     #getParameterValue.828 *829 * @return {!goog.Uri} The new URI object.830 */831goog.Uri.create = function(opt_scheme, opt_userInfo, opt_domain, opt_port,832                           opt_path, opt_query, opt_fragment, opt_ignoreCase) {833834  var uri = new goog.Uri(null, opt_ignoreCase);835836  // Only set the parts if they are defined and not empty strings.837  opt_scheme && uri.setScheme(opt_scheme);838  opt_userInfo && uri.setUserInfo(opt_userInfo);839  opt_domain && uri.setDomain(opt_domain);840  opt_port && uri.setPort(opt_port);841  opt_path && uri.setPath(opt_path);842  opt_query && uri.setQueryData(opt_query);843  opt_fragment && uri.setFragment(opt_fragment);844845  return uri;846};847848849/**850 * Resolves a relative Uri against a base Uri, accepting both strings and851 * Uri objects.852 *853 * @param {*} base Base Uri.854 * @param {*} rel Relative Uri.855 * @return {!goog.Uri} Resolved uri.856 */857goog.Uri.resolve = function(base, rel) {858  if (!(base instanceof goog.Uri)) {859    base = goog.Uri.parse(base);860  }861862  if (!(rel instanceof goog.Uri)) {863    rel = goog.Uri.parse(rel);864  }865866  return base.resolve(rel);867};868869870/**871 * Removes dot segments in given path component, as described in872 * RFC 3986, section 5.2.4.873 *874 * @param {string} path A non-empty path component.875 * @return {string} Path component with removed dot segments.876 */877goog.Uri.removeDotSegments = function(path) {878  if (path == '..' || path == '.') {879    return '';880881  } else if (!goog.string.contains(path, './') &&882             !goog.string.contains(path, '/.')) {883    // This optimization detects uris which do not contain dot-segments,884    // and as a consequence do not require any processing.885    return path;886887  } else {888    var leadingSlash = goog.string.startsWith(path, '/');889    var segments = path.split('/');890    var out = [];891892    for (var pos = 0; pos < segments.length; ) {893      var segment = segments[pos++];894895      if (segment == '.') {896        if (leadingSlash && pos == segments.length) {897          out.push('');898        }899      } else if (segment == '..') {900        if (out.length > 1 || out.length == 1 && out[0] != '') {901          out.pop();902        }903        if (leadingSlash && pos == segments.length) {904          out.push('');905        }906      } else {907        out.push(segment);908        leadingSlash = true;909      }910    }911912    return out.join('/');913  }914};915916917/**918 * Decodes a value or returns the empty string if it isn't defined or empty.919 * @param {string|undefined} val Value to decode.920 * @param {boolean=} opt_preserveReserved If true, restricted characters will921 *     not be decoded.922 * @return {string} Decoded value.923 * @private924 */925goog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {926  // Don't use UrlDecode() here because val is not a query parameter.927  if (!val) {928    return '';929  }930931  return opt_preserveReserved ? decodeURI(val) : decodeURIComponent(val);932};933934935/**936 * If unescapedPart is non null, then escapes any characters in it that aren't937 * valid characters in a url and also escapes any special characters that938 * appear in extra.939 *940 * @param {*} unescapedPart The string to encode.941 * @param {RegExp} extra A character set of characters in [\01-\177].942 * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent943 *     encoding.944 * @return {?string} null iff unescapedPart == null.945 * @private946 */947goog.Uri.encodeSpecialChars_ = function(unescapedPart, extra,948    opt_removeDoubleEncoding) {949  if (goog.isString(unescapedPart)) {950    var encoded = encodeURI(unescapedPart).951        replace(extra, goog.Uri.encodeChar_);952    if (opt_removeDoubleEncoding) {953      // encodeURI double-escapes %XX sequences used to represent restricted954      // characters in some URI components, remove the double escaping here.955      encoded = goog.Uri.removeDoubleEncoding_(encoded);956    }957    return encoded;958  }959  return null;960};961962963/**964 * Converts a character in [\01-\177] to its unicode character equivalent.965 * @param {string} ch One character string.966 * @return {string} Encoded string.967 * @private968 */969goog.Uri.encodeChar_ = function(ch) {970  var n = ch.charCodeAt(0);971  return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);972};973974975/**976 * Removes double percent-encoding from a string.977 * @param  {string} doubleEncodedString String978 * @return {string} String with double encoding removed.979 * @private980 */981goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {982  return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');983};984985986/**987 * Regular expression for characters that are disallowed in the scheme or988 * userInfo part of the URI.989 * @type {RegExp}990 * @private991 */992goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g;993994995/**996 * Regular expression for characters that are disallowed in a relative path.997 * Colon is included due to RFC 3986 3.3.998 * @type {RegExp}999 * @private1000 */1001goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g;100210031004/**1005 * Regular expression for characters that are disallowed in an absolute path.1006 * @type {RegExp}1007 * @private1008 */1009goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g;101010111012/**1013 * Regular expression for characters that are disallowed in the query.1014 * @type {RegExp}1015 * @private1016 */1017goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g;101810191020/**1021 * Regular expression for characters that are disallowed in the fragment.1022 * @type {RegExp}1023 * @private1024 */1025goog.Uri.reDisallowedInFragment_ = /#/g;102610271028/**1029 * Checks whether two URIs have the same domain.1030 * @param {string} uri1String First URI string.1031 * @param {string} uri2String Second URI string.1032 * @return {boolean} true if the two URIs have the same domain; false otherwise.1033 */1034goog.Uri.haveSameDomain = function(uri1String, uri2String) {1035  // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.1036  // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.1037  var pieces1 = goog.uri.utils.split(uri1String);1038  var pieces2 = goog.uri.utils.split(uri2String);1039  return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==1040             pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&1041         pieces1[goog.uri.utils.ComponentIndex.PORT] ==1042             pieces2[goog.uri.utils.ComponentIndex.PORT];1043};1044104510461047/**1048 * Class used to represent URI query parameters.  It is essentially a hash of1049 * name-value pairs, though a name can be present more than once.1050 *1051 * Has the same interface as the collections in goog.structs.1052 *1053 * @param {?string=} opt_query Optional encoded query string to parse into1054 *     the object.1055 * @param {goog.Uri=} opt_uri Optional uri object that should have its1056 *     cache invalidated when this object updates. Deprecated -- this1057 *     is no longer required.1058 * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter1059 *     name in #get.1060 * @constructor1061 * @final1062 */1063goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {1064  /**1065   * Encoded query string, or null if it requires computing from the key map.1066   * @type {?string}1067   * @private1068   */1069  this.encodedQuery_ = opt_query || null;10701071  /**1072   * If true, ignore the case of the parameter name in #get.1073   * @type {boolean}1074   * @private1075   */1076  this.ignoreCase_ = !!opt_ignoreCase;1077};107810791080/**1081 * If the underlying key map is not yet initialized, it parses the1082 * query string and fills the map with parsed data.1083 * @private1084 */1085goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {1086  if (!this.keyMap_) {1087    this.keyMap_ = new goog.structs.Map();1088    this.count_ = 0;10891090    if (this.encodedQuery_) {1091      var pairs = this.encodedQuery_.split('&');1092      for (var i = 0; i < pairs.length; i++) {1093        var indexOfEquals = pairs[i].indexOf('=');1094        var name = null;1095        var value = null;1096        if (indexOfEquals >= 0) {1097          name = pairs[i].substring(0, indexOfEquals);1098          value = pairs[i].substring(indexOfEquals + 1);1099        } else {1100          name = pairs[i];1101        }1102        name = goog.string.urlDecode(name);1103        name = this.getKeyName_(name);1104        this.add(name, value ? goog.string.urlDecode(value) : '');1105      }1106    }1107  }1108};110911101111/**1112 * Creates a new query data instance from a map of names and values.1113 *1114 * @param {!goog.structs.Map|!Object} map Map of string parameter1115 *     names to parameter value. If parameter value is an array, it is1116 *     treated as if the key maps to each individual value in the1117 *     array.1118 * @param {goog.Uri=} opt_uri URI object that should have its cache1119 *     invalidated when this object updates.1120 * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter1121 *     name in #get.1122 * @return {!goog.Uri.QueryData} The populated query data instance.1123 */1124goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {1125  var keys = goog.structs.getKeys(map);1126  if (typeof keys == 'undefined') {1127    throw Error('Keys are undefined');1128  }11291130  var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);1131  var values = goog.structs.getValues(map);1132  for (var i = 0; i < keys.length; i++) {1133    var key = keys[i];1134    var value = values[i];1135    if (!goog.isArray(value)) {1136      queryData.add(key, value);1137    } else {1138      queryData.setValues(key, value);1139    }1140  }1141  return queryData;1142};114311441145/**1146 * Creates a new query data instance from parallel arrays of parameter names1147 * and values. Allows for duplicate parameter names. Throws an error if the1148 * lengths of the arrays differ.1149 *1150 * @param {Array.<string>} keys Parameter names.1151 * @param {Array} values Parameter values.1152 * @param {goog.Uri=} opt_uri URI object that should have its cache1153 *     invalidated when this object updates.1154 * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter1155 *     name in #get.1156 * @return {!goog.Uri.QueryData} The populated query data instance.1157 */1158goog.Uri.QueryData.createFromKeysValues = function(1159    keys, values, opt_uri, opt_ignoreCase) {1160  if (keys.length != values.length) {1161    throw Error('Mismatched lengths for keys/values');1162  }1163  var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);1164  for (var i = 0; i < keys.length; i++) {1165    queryData.add(keys[i], values[i]);1166  }1167  return queryData;1168};116911701171/**1172 * The map containing name/value or name/array-of-values pairs.1173 * May be null if it requires parsing from the query string.1174 *1175 * We need to use a Map because we cannot guarantee that the key names will1176 * not be problematic for IE.1177 *1178 * @type {goog.structs.Map.<string, Array>}1179 * @private1180 */1181goog.Uri.QueryData.prototype.keyMap_ = null;118211831184/**1185 * The number of params, or null if it requires computing.1186 * @type {?number}1187 * @private1188 */1189goog.Uri.QueryData.prototype.count_ = null;119011911192/**1193 * @return {?number} The number of parameters.1194 */1195goog.Uri.QueryData.prototype.getCount = function() {1196  this.ensureKeyMapInitialized_();1197  return this.count_;1198};119912001201/**1202 * Adds a key value pair.1203 * @param {string} key Name.1204 * @param {*} value Value.1205 * @return {!goog.Uri.QueryData} Instance of this object.1206 */1207goog.Uri.QueryData.prototype.add = function(key, value) {1208  this.ensureKeyMapInitialized_();1209  this.invalidateCache_();12101211  key = this.getKeyName_(key);1212  var values = this.keyMap_.get(key);1213  if (!values) {1214    this.keyMap_.set(key, (values = []));1215  }1216  values.push(value);1217  this.count_++;1218  return this;1219};122012211222/**1223 * Removes all the params with the given key.1224 * @param {string} key Name.1225 * @return {boolean} Whether any parameter was removed.1226 */1227goog.Uri.QueryData.prototype.remove = function(key) {1228  this.ensureKeyMapInitialized_();12291230  key = this.getKeyName_(key);1231  if (this.keyMap_.containsKey(key)) {1232    this.invalidateCache_();12331234    // Decrement parameter count.1235    this.count_ -= this.keyMap_.get(key).length;1236    return this.keyMap_.remove(key);1237  }1238  return false;1239};124012411242/**1243 * Clears the parameters.1244 */1245goog.Uri.QueryData.prototype.clear = function() {1246  this.invalidateCache_();1247  this.keyMap_ = null;1248  this.count_ = 0;1249};125012511252/**1253 * @return {boolean} Whether we have any parameters.1254 */1255goog.Uri.QueryData.prototype.isEmpty = function() {1256  this.ensureKeyMapInitialized_();1257  return this.count_ == 0;1258};125912601261/**1262 * Whether there is a parameter with the given name1263 * @param {string} key The parameter name to check for.1264 * @return {boolean} Whether there is a parameter with the given name.1265 */1266goog.Uri.QueryData.prototype.containsKey = function(key) {1267  this.ensureKeyMapInitialized_();1268  key = this.getKeyName_(key);1269  return this.keyMap_.containsKey(key);1270};127112721273/**1274 * Whether there is a parameter with the given value.1275 * @param {*} value The value to check for.1276 * @return {boolean} Whether there is a parameter with the given value.1277 */1278goog.Uri.QueryData.prototype.containsValue = function(value) {1279  // NOTE(arv): This solution goes through all the params even if it was the1280  // first param. We can get around this by not reusing code or by switching to1281  // iterators.1282  var vals = this.getValues();1283  return goog.array.contains(vals, value);1284};128512861287/**1288 * Returns all the keys of the parameters. If a key is used multiple times1289 * it will be included multiple times in the returned array1290 * @return {!Array.<string>} All the keys of the parameters.1291 */1292goog.Uri.QueryData.prototype.getKeys = function() {1293  this.ensureKeyMapInitialized_();1294  // We need to get the values to know how many keys to add.1295  var vals = /** @type {Array.<Array|*>} */ (this.keyMap_.getValues());1296  var keys = this.keyMap_.getKeys();1297  var rv = [];1298  for (var i = 0; i < keys.length; i++) {1299    var val = vals[i];1300    for (var j = 0; j < val.length; j++) {1301      rv.push(keys[i]);1302    }1303  }1304  return rv;1305};130613071308/**1309 * Returns all the values of the parameters with the given name. If the query1310 * data has no such key this will return an empty array. If no key is given1311 * all values wil be returned.1312 * @param {string=} opt_key The name of the parameter to get the values for.1313 * @return {!Array} All the values of the parameters with the given name.1314 */1315goog.Uri.QueryData.prototype.getValues = function(opt_key) {1316  this.ensureKeyMapInitialized_();1317  var rv = [];1318  if (goog.isString(opt_key)) {1319    if (this.containsKey(opt_key)) {1320      rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));1321    }1322  } else {1323    // Return all values.1324    var values = /** @type {Array.<Array|*>} */ (this.keyMap_.getValues());1325    for (var i = 0; i < values.length; i++) {1326      rv = goog.array.concat(rv, values[i]);1327    }1328  }1329  return rv;1330};133113321333/**1334 * Sets a key value pair and removes all other keys with the same value.1335 *1336 * @param {string} key Name.1337 * @param {*} value Value.1338 * @return {!goog.Uri.QueryData} Instance of this object.1339 */1340goog.Uri.QueryData.prototype.set = function(key, value) {1341  this.ensureKeyMapInitialized_();1342  this.invalidateCache_();13431344  // TODO(user): This could be better written as1345  // this.remove(key), this.add(key, value), but that would reorder1346  // the key (since the key is first removed and then added at the1347  // end) and we would have to fix unit tests that depend on key1348  // ordering.1349  key = this.getKeyName_(key);1350  if (this.containsKey(key)) {1351    this.count_ -= this.keyMap_.get(key).length;1352  }1353  this.keyMap_.set(key, [value]);1354  this.count_++;1355  return this;1356};135713581359/**1360 * Returns the first value associated with the key. If the query data has no1361 * such key this will return undefined or the optional default.1362 * @param {string} key The name of the parameter to get the value for.1363 * @param {*=} opt_default The default value to return if the query data1364 *     has no such key.1365 * @return {*} The first string value associated with the key, or opt_default1366 *     if there's no value.1367 */1368goog.Uri.QueryData.prototype.get = function(key, opt_default) {1369  var values = key ? this.getValues(key) : [];1370  if (goog.Uri.preserveParameterTypesCompatibilityFlag) {1371    return values.length > 0 ? values[0] : opt_default;1372  } else {1373    return values.length > 0 ? String(values[0]) : opt_default;1374  }1375};137613771378/**1379 * Sets the values for a key. If the key already exists, this will1380 * override all of the existing values that correspond to the key.1381 * @param {string} key The key to set values for.1382 * @param {Array} values The values to set.1383 */1384goog.Uri.QueryData.prototype.setValues = function(key, values) {1385  this.remove(key);13861387  if (values.length > 0) {1388    this.invalidateCache_();1389    this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));1390    this.count_ += values.length;1391  }1392};139313941395/**1396 * @return {string} Encoded query string.1397 * @override1398 */1399goog.Uri.QueryData.prototype.toString = function() {1400  if (this.encodedQuery_) {1401    return this.encodedQuery_;1402  }14031404  if (!this.keyMap_) {1405    return '';1406  }14071408  var sb = [];14091410  // In the past, we use this.getKeys() and this.getVals(), but that1411  // generates a lot of allocations as compared to simply iterating1412  // over the keys.1413  var keys = this.keyMap_.getKeys();1414  for (var i = 0; i < keys.length; i++) {1415    var key = keys[i];1416    var encodedKey = goog.string.urlEncode(key);1417    var val = this.getValues(key);1418    for (var j = 0; j < val.length; j++) {1419      var param = encodedKey;1420      // Ensure that null and undefined are encoded into the url as1421      // literal strings.1422      if (val[j] !== '') {1423        param += '=' + goog.string.urlEncode(val[j]);1424      }1425      sb.push(param);1426    }1427  }14281429  return this.encodedQuery_ = sb.join('&');1430};143114321433/**1434 * @return {string} Decoded query string.1435 */1436goog.Uri.QueryData.prototype.toDecodedString = function() {1437  return goog.Uri.decodeOrEmpty_(this.toString());1438};143914401441/**1442 * Invalidate the cache.1443 * @private1444 */1445goog.Uri.QueryData.prototype.invalidateCache_ = function() {1446  this.encodedQuery_ = null;1447};144814491450/**1451 * Removes all keys that are not in the provided list. (Modifies this object.)1452 * @param {Array.<string>} keys The desired keys.1453 * @return {!goog.Uri.QueryData} a reference to this object.1454 */1455goog.Uri.QueryData.prototype.filterKeys = function(keys) {1456  this.ensureKeyMapInitialized_();1457  this.keyMap_.forEach(1458      function(value, key) {1459        if (!goog.array.contains(keys, key)) {1460          this.remove(key);1461        }1462      }, this);1463  return this;1464};146514661467/**1468 * Clone the query data instance.1469 * @return {!goog.Uri.QueryData} New instance of the QueryData object.1470 */1471goog.Uri.QueryData.prototype.clone = function() {1472  var rv = new goog.Uri.QueryData();1473  rv.encodedQuery_ = this.encodedQuery_;1474  if (this.keyMap_) {1475    rv.keyMap_ = this.keyMap_.clone();1476    rv.count_ = this.count_;1477  }1478  return rv;1479};148014811482/**1483 * Helper function to get the key name from a JavaScript object. Converts1484 * the object to a string, and to lower case if necessary.1485 * @private1486 * @param {*} arg The object to get a key name from.1487 * @return {string} valid key name which can be looked up in #keyMap_.1488 */1489goog.Uri.QueryData.prototype.getKeyName_ = function(arg) {1490  var keyName = String(arg);1491  if (this.ignoreCase_) {1492    keyName = keyName.toLowerCase();1493  }1494  return keyName;1495};149614971498/**1499 * Ignore case in parameter names.1500 * NOTE: If there are already key/value pairs in the QueryData, and1501 * ignoreCase_ is set to false, the keys will all be lower-cased.1502 * @param {boolean} ignoreCase whether this goog.Uri should ignore case.1503 */1504goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {1505  var resetKeys = ignoreCase && !this.ignoreCase_;1506  if (resetKeys) {1507    this.ensureKeyMapInitialized_();1508    this.invalidateCache_();1509    this.keyMap_.forEach(1510        function(value, key) {1511          var lowerCase = key.toLowerCase();1512          if (key != lowerCase) {1513            this.remove(key);1514            this.setValues(lowerCase, value);1515          }1516        }, this);1517  }1518  this.ignoreCase_ = ignoreCase;1519};152015211522/**1523 * Extends a query data object with another query data or map like object. This1524 * operates 'in-place', it does not create a new QueryData object.1525 *1526 * @param {...(goog.Uri.QueryData|goog.structs.Map|Object)} var_args The object1527 *     from which key value pairs will be copied.1528 */1529goog.Uri.QueryData.prototype.extend = function(var_args) {1530  for (var i = 0; i < arguments.length; i++) {1531    var data = arguments[i];1532    goog.structs.forEach(data,1533        /** @this {goog.Uri.QueryData} */1534        function(value, key) {1535          this.add(key, value);1536        }, this);1537  }1538};