# 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 * The constructor accepts an optional unparsed, raw URI string.  The parser52 * is relaxed, so special characters that aren't escaped but don't cause53 * ambiguities will not cause parse failures.54 *55 * All setters return <code>this</code> and so may be chained, a la56 * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.57 *58 * @param {*=} opt_uri Optional string URI to parse59 *        (use goog.Uri.create() to create a URI from parts), or if60 *        a goog.Uri is passed, a clone is created.61 * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore62 * the case of the parameter name.63 *64 * @constructor65 */66goog.Uri = function(opt_uri, opt_ignoreCase) {67  // Parse in the uri string68  var m;69  if (opt_uri instanceof goog.Uri) {70    this.ignoreCase_ = goog.isDef(opt_ignoreCase) ?71        opt_ignoreCase : opt_uri.getIgnoreCase();72    this.setScheme(opt_uri.getScheme());73    this.setUserInfo(opt_uri.getUserInfo());74    this.setDomain(opt_uri.getDomain());75    this.setPort(opt_uri.getPort());76    this.setPath(opt_uri.getPath());77    this.setQueryData(opt_uri.getQueryData().clone());78    this.setFragment(opt_uri.getFragment());79  } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {80    this.ignoreCase_ = !!opt_ignoreCase;8182    // Set the parts -- decoding as we do so.83    // COMPATABILITY NOTE - In IE, unmatched fields may be empty strings,84    // whereas in other browsers they will be undefined.85    this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);86    this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);87    this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);88    this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);89    this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);90    this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);91    this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);9293  } else {94    this.ignoreCase_ = !!opt_ignoreCase;95    this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);96  }97};9899100/**101 * If true, we preserve the type of query parameters set programmatically.102 *103 * This means that if you set a parameter to a boolean, and then call104 * getParameterValue, you will get a boolean back.105 *106 * If false, we will coerce parameters to strings, just as they would107 * appear in real URIs.108 *109 * TODO(nicksantos): Remove this once people have time to fix all tests.110 *111 * @type {boolean}112 */113goog.Uri.preserveParameterTypesCompatibilityFlag = false;114115116/**117 * Parameter name added to stop caching.118 * @type {string}119 */120goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;121122123/**124 * Scheme such as "http".125 * @type {string}126 * @private127 */128goog.Uri.prototype.scheme_ = '';129130131/**132 * User credentials in the form "username:password".133 * @type {string}134 * @private135 */136goog.Uri.prototype.userInfo_ = '';137138139/**140 * Domain part, e.g. "www.google.com".141 * @type {string}142 * @private143 */144goog.Uri.prototype.domain_ = '';145146147/**148 * Port, e.g. 8080.149 * @type {?number}150 * @private151 */152goog.Uri.prototype.port_ = null;153154155/**156 * Path, e.g. "/tests/img.png".157 * @type {string}158 * @private159 */160goog.Uri.prototype.path_ = '';161162163/**164 * Object representing query data.165 * @type {!goog.Uri.QueryData}166 * @private167 */168goog.Uri.prototype.queryData_;169170171/**172 * The fragment without the #.173 * @type {string}174 * @private175 */176goog.Uri.prototype.fragment_ = '';177178179/**180 * Whether or not this Uri should be treated as Read Only.181 * @type {boolean}182 * @private183 */184goog.Uri.prototype.isReadOnly_ = false;185186187/**188 * Whether or not to ignore case when comparing query params.189 * @type {boolean}190 * @private191 */192goog.Uri.prototype.ignoreCase_ = false;193194195/**196 * @return {string} The string form of the url.197 * @override198 */199goog.Uri.prototype.toString = function() {200  var out = [];201202  var scheme = this.getScheme();203  if (scheme) {204    out.push(goog.Uri.encodeSpecialChars_(205        scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_), ':');206  }207208  var domain = this.getDomain();209  if (domain) {210    out.push('//');211212    var userInfo = this.getUserInfo();213    if (userInfo) {214      out.push(goog.Uri.encodeSpecialChars_(215          userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_), '@');216    }217218    out.push(goog.string.urlEncode(domain));219220    var port = this.getPort();221    if (port != null) {222      out.push(':', String(port));223    }224  }225226  var path = this.getPath();227  if (path) {228    if (this.hasDomain() && path.charAt(0) != '/') {229      out.push('/');230    }231    out.push(goog.Uri.encodeSpecialChars_(232        path,233        path.charAt(0) == '/' ?234            goog.Uri.reDisallowedInAbsolutePath_ :235            goog.Uri.reDisallowedInRelativePath_));236  }237238  var query = this.getEncodedQuery();239  if (query) {240    out.push('?', query);241  }242243  var fragment = this.getFragment();244  if (fragment) {245    out.push('#', goog.Uri.encodeSpecialChars_(246        fragment, goog.Uri.reDisallowedInFragment_));247  }248  return out.join('');249};250251252/**253 * Resolves the given relative URI (a goog.Uri object), using the URI254 * represented by this instance as the base URI.255 *256 * There are several kinds of relative URIs:<br>257 * 1. foo - replaces the last part of the path, the whole query and fragment<br>258 * 2. /foo - replaces the the path, the query and fragment<br>259 * 3. //foo - replaces everything from the domain on.  foo is a domain name<br>260 * 4. ?foo - replace the query and fragment<br>261 * 5. #foo - replace the fragment only262 *263 * Additionally, if relative URI has a non-empty path, all ".." and "."264 * segments will be resolved, as described in RFC 3986.265 *266 * @param {goog.Uri} relativeUri The relative URI to resolve.267 * @return {!goog.Uri} The resolved URI.268 */269goog.Uri.prototype.resolve = function(relativeUri) {270271  var absoluteUri = this.clone();272273  // we satisfy these conditions by looking for the first part of relativeUri274  // that is not blank and applying defaults to the rest275276  var overridden = relativeUri.hasScheme();277278  if (overridden) {279    absoluteUri.setScheme(relativeUri.getScheme());280  } else {281    overridden = relativeUri.hasUserInfo();282  }283284  if (overridden) {285    absoluteUri.setUserInfo(relativeUri.getUserInfo());286  } else {287    overridden = relativeUri.hasDomain();288  }289290  if (overridden) {291    absoluteUri.setDomain(relativeUri.getDomain());292  } else {293    overridden = relativeUri.hasPort();294  }295296  var path = relativeUri.getPath();297  if (overridden) {298    absoluteUri.setPort(relativeUri.getPort());299  } else {300    overridden = relativeUri.hasPath();301    if (overridden) {302      // resolve path properly303      if (path.charAt(0) != '/') {304        // path is relative305        if (this.hasDomain() && !this.hasPath()) {306          // RFC 3986, section 5.2.3, case 1307          path = '/' + path;308        } else {309          // RFC 3986, section 5.2.3, case 2310          var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');311          if (lastSlashIndex != -1) {312            path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;313          }314        }315      }316      path = goog.Uri.removeDotSegments(path);317    }318  }319320  if (overridden) {321    absoluteUri.setPath(path);322  } else {323    overridden = relativeUri.hasQuery();324  }325326  if (overridden) {327    absoluteUri.setQueryData(relativeUri.getDecodedQuery());328  } else {329    overridden = relativeUri.hasFragment();330  }331332  if (overridden) {333    absoluteUri.setFragment(relativeUri.getFragment());334  }335336  return absoluteUri;337};338339340/**341 * Clones the URI instance.342 * @return {!goog.Uri} New instance of the URI object.343 */344goog.Uri.prototype.clone = function() {345  return new goog.Uri(this);346};347348349/**350 * @return {string} The encoded scheme/protocol for the URI.351 */352goog.Uri.prototype.getScheme = function() {353  return this.scheme_;354};355356357/**358 * Sets the scheme/protocol.359 * @param {string} newScheme New scheme value.360 * @param {boolean=} opt_decode Optional param for whether to decode new value.361 * @return {!goog.Uri} Reference to this URI object.362 */363goog.Uri.prototype.setScheme = function(newScheme, opt_decode) {364  this.enforceReadOnly();365  this.scheme_ = opt_decode ? goog.Uri.decodeOrEmpty_(newScheme) : newScheme;366367  // remove an : at the end of the scheme so somebody can pass in368  // window.location.protocol369  if (this.scheme_) {370    this.scheme_ = this.scheme_.replace(/:$/, '');371  }372  return this;373};374375376/**377 * @return {boolean} Whether the scheme has been set.378 */379goog.Uri.prototype.hasScheme = function() {380  return !!this.scheme_;381};382383384/**385 * @return {string} The decoded user info.386 */387goog.Uri.prototype.getUserInfo = function() {388  return this.userInfo_;389};390391392/**393 * Sets the userInfo.394 * @param {string} newUserInfo New userInfo value.395 * @param {boolean=} opt_decode Optional param for whether to decode new value.396 * @return {!goog.Uri} Reference to this URI object.397 */398goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {399  this.enforceReadOnly();400  this.userInfo_ = opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) :401                   newUserInfo;402  return this;403};404405406/**407 * @return {boolean} Whether the user info has been set.408 */409goog.Uri.prototype.hasUserInfo = function() {410  return !!this.userInfo_;411};412413414/**415 * @return {string} The decoded domain.416 */417goog.Uri.prototype.getDomain = function() {418  return this.domain_;419};420421422/**423 * Sets the domain.424 * @param {string} newDomain New domain value.425 * @param {boolean=} opt_decode Optional param for whether to decode new value.426 * @return {!goog.Uri} Reference to this URI object.427 */428goog.Uri.prototype.setDomain = function(newDomain, opt_decode) {429  this.enforceReadOnly();430  this.domain_ = opt_decode ? goog.Uri.decodeOrEmpty_(newDomain) : newDomain;431  return this;432};433434435/**436 * @return {boolean} Whether the domain has been set.437 */438goog.Uri.prototype.hasDomain = function() {439  return !!this.domain_;440};441442443/**444 * @return {?number} The port number.445 */446goog.Uri.prototype.getPort = function() {447  return this.port_;448};449450451/**452 * Sets the port number.453 * @param {*} newPort Port number. Will be explicitly casted to a number.454 * @return {!goog.Uri} Reference to this URI object.455 */456goog.Uri.prototype.setPort = function(newPort) {457  this.enforceReadOnly();458459  if (newPort) {460    newPort = Number(newPort);461    if (isNaN(newPort) || newPort < 0) {462      throw Error('Bad port number ' + newPort);463    }464    this.port_ = newPort;465  } else {466    this.port_ = null;467  }468469  return this;470};471472473/**474 * @return {boolean} Whether the port has been set.475 */476goog.Uri.prototype.hasPort = function() {477  return this.port_ != null;478};479480481/**482  * @return {string} The decoded path.483 */484goog.Uri.prototype.getPath = function() {485  return this.path_;486};487488489/**490 * Sets the path.491 * @param {string} newPath New path value.492 * @param {boolean=} opt_decode Optional param for whether to decode new value.493 * @return {!goog.Uri} Reference to this URI object.494 */495goog.Uri.prototype.setPath = function(newPath, opt_decode) {496  this.enforceReadOnly();497  this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath) : newPath;498  return this;499};500501502/**503 * @return {boolean} Whether the path has been set.504 */505goog.Uri.prototype.hasPath = function() {506  return !!this.path_;507};508509510/**511 * @return {boolean} Whether the query string has been set.512 */513goog.Uri.prototype.hasQuery = function() {514  return this.queryData_.toString() !== '';515};516517518/**519 * Sets the query data.520 * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.521 * @param {boolean=} opt_decode Optional param for whether to decode new value.522 *     Applies only if queryData is a string.523 * @return {!goog.Uri} Reference to this URI object.524 */525goog.Uri.prototype.setQueryData = function(queryData, opt_decode) {526  this.enforceReadOnly();527528  if (queryData instanceof goog.Uri.QueryData) {529    this.queryData_ = queryData;530    this.queryData_.setIgnoreCase(this.ignoreCase_);531  } else {532    if (!opt_decode) {533      // QueryData accepts encoded query string, so encode it if534      // opt_decode flag is not true.535      queryData = goog.Uri.encodeSpecialChars_(queryData,536                                               goog.Uri.reDisallowedInQuery_);537    }538    this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);539  }540541  return this;542};543544545/**546 * Sets the URI query.547 * @param {string} newQuery New query value.548 * @param {boolean=} opt_decode Optional param for whether to decode new value.549 * @return {!goog.Uri} Reference to this URI object.550 */551goog.Uri.prototype.setQuery = function(newQuery, opt_decode) {552  return this.setQueryData(newQuery, opt_decode);553};554555556/**557 * @return {string} The encoded URI query, not including the ?.558 */559goog.Uri.prototype.getEncodedQuery = function() {560  return this.queryData_.toString();561};562563564/**565 * @return {string} The decoded URI query, not including the ?.566 */567goog.Uri.prototype.getDecodedQuery = function() {568  return this.queryData_.toDecodedString();569};570571572/**573 * Returns the query data.574 * @return {!goog.Uri.QueryData} QueryData object.575 */576goog.Uri.prototype.getQueryData = function() {577  return this.queryData_;578};579580581/**582 * @return {string} The encoded URI query, not including the ?.583 *584 * Warning: This method, unlike other getter methods, returns encoded585 * value, instead of decoded one.586 */587goog.Uri.prototype.getQuery = function() {588  return this.getEncodedQuery();589};590591592/**593 * Sets the value of the named query parameters, clearing previous values for594 * that key.595 *596 * @param {string} key The parameter to set.597 * @param {*} value The new value.598 * @return {!goog.Uri} Reference to this URI object.599 */600goog.Uri.prototype.setParameterValue = function(key, value) {601  this.enforceReadOnly();602  this.queryData_.set(key, value);603  return this;604};605606607/**608 * Sets the values of the named query parameters, clearing previous values for609 * that key.  Not new values will currently be moved to the end of the query610 * string.611 *612 * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])613 * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>614 *615 * @param {string} key The parameter to set.616 * @param {*} values The new values. If values is a single617 *     string then it will be treated as the sole value.618 * @return {!goog.Uri} Reference to this URI object.619 */620goog.Uri.prototype.setParameterValues = function(key, values) {621  this.enforceReadOnly();622623  if (!goog.isArray(values)) {624    values = [String(values)];625  }626627  // TODO(nicksantos): This cast shouldn't be necessary.628  this.queryData_.setValues(key, /** @type {Array} */ (values));629630  return this;631};632633634/**635 * Returns the value<b>s</b> for a given cgi parameter as a list of decoded636 * query parameter values.637 * @param {string} name The parameter to get values for.638 * @return {!Array} The values for a given cgi parameter as a list of639 *     decoded query parameter values.640 */641goog.Uri.prototype.getParameterValues = function(name) {642  return this.queryData_.getValues(name);643};644645646/**647 * Returns the first value for a given cgi parameter or undefined if the given648 * parameter name does not appear in the query string.649 * @param {string} paramName Unescaped parameter name.650 * @return {string|undefined} The first value for a given cgi parameter or651 *     undefined if the given parameter name does not appear in the query652 *     string.653 */654goog.Uri.prototype.getParameterValue = function(paramName) {655  // NOTE(nicksantos): This type-cast is a lie when656  // preserveParameterTypesCompatibilityFlag is set to true.657  // But this should only be set to true in tests.658  return /** @type {string|undefined} */ (this.queryData_.get(paramName));659};660661662/**663 * @return {string} The URI fragment, not including the #.664 */665goog.Uri.prototype.getFragment = function() {666  return this.fragment_;667};668669670/**671 * Sets the URI fragment.672 * @param {string} newFragment New fragment value.673 * @param {boolean=} opt_decode Optional param for whether to decode new value.674 * @return {!goog.Uri} Reference to this URI object.675 */676goog.Uri.prototype.setFragment = function(newFragment, opt_decode) {677  this.enforceReadOnly();678  this.fragment_ = opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) :679                   newFragment;680  return this;681};682683684/**685 * @return {boolean} Whether the URI has a fragment set.686 */687goog.Uri.prototype.hasFragment = function() {688  return !!this.fragment_;689};690691692/**693 * Returns true if this has the same domain as that of uri2.694 * @param {goog.Uri} uri2 The URI object to compare to.695 * @return {boolean} true if same domain; false otherwise.696 */697goog.Uri.prototype.hasSameDomainAs = function(uri2) {698  return ((!this.hasDomain() && !uri2.hasDomain()) ||699          this.getDomain() == uri2.getDomain()) &&700      ((!this.hasPort() && !uri2.hasPort()) ||701          this.getPort() == uri2.getPort());702};703704705/**706 * Adds a random parameter to the Uri.707 * @return {!goog.Uri} Reference to this Uri object.708 */709goog.Uri.prototype.makeUnique = function() {710  this.enforceReadOnly();711  this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());712713  return this;714};715716717/**718 * Removes the named query parameter.719 *720 * @param {string} key The parameter to remove.721 * @return {!goog.Uri} Reference to this URI object.722 */723goog.Uri.prototype.removeParameter = function(key) {724  this.enforceReadOnly();725  this.queryData_.remove(key);726  return this;727};728729730/**731 * Sets whether Uri is read only. If this goog.Uri is read-only,732 * enforceReadOnly_ will be called at the start of any function that may modify733 * this Uri.734 * @param {boolean} isReadOnly whether this goog.Uri should be read only.735 * @return {!goog.Uri} Reference to this Uri object.736 */737goog.Uri.prototype.setReadOnly = function(isReadOnly) {738  this.isReadOnly_ = isReadOnly;739  return this;740};741742743/**744 * @return {boolean} Whether the URI is read only.745 */746goog.Uri.prototype.isReadOnly = function() {747  return this.isReadOnly_;748};749750751/**752 * Checks if this Uri has been marked as read only, and if so, throws an error.753 * This should be called whenever any modifying function is called.754 */755goog.Uri.prototype.enforceReadOnly = function() {756  if (this.isReadOnly_) {757    throw Error('Tried to modify a read-only Uri');758  }759};760761762/**763 * Sets whether to ignore case.764 * NOTE: If there are already key/value pairs in the QueryData, and765 * ignoreCase_ is set to false, the keys will all be lower-cased.766 * @param {boolean} ignoreCase whether this goog.Uri should ignore case.767 * @return {!goog.Uri} Reference to this Uri object.768 */769goog.Uri.prototype.setIgnoreCase = function(ignoreCase) {770  this.ignoreCase_ = ignoreCase;771  if (this.queryData_) {772    this.queryData_.setIgnoreCase(ignoreCase);773  }774  return this;775};776777778/**779 * @return {boolean} Whether to ignore case.780 */781goog.Uri.prototype.getIgnoreCase = function() {782  return this.ignoreCase_;783};784785786//==============================================================================787// Static members788//==============================================================================789790791/**792 * Creates a uri from the string form.  Basically an alias of new goog.Uri().793 * If a Uri object is passed to parse then it will return a clone of the object.794 *795 * @param {*} uri Raw URI string or instance of Uri796 *     object.797 * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter798 * names in #getParameterValue.799 * @return {!goog.Uri} The new URI object.800 */801goog.Uri.parse = function(uri, opt_ignoreCase) {802  return uri instanceof goog.Uri ?803         uri.clone() : new goog.Uri(uri, opt_ignoreCase);804};805806807/**808 * Creates a new goog.Uri object from unencoded parts.809 *810 * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.811 * @param {?string=} opt_userInfo username:password.812 * @param {?string=} opt_domain www.google.com.813 * @param {?number=} opt_port 9830.814 * @param {?string=} opt_path /some/path/to/a/file.html.815 * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.816 * @param {?string=} opt_fragment The fragment without the #.817 * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in818 *     #getParameterValue.819 *820 * @return {!goog.Uri} The new URI object.821 */822goog.Uri.create = function(opt_scheme, opt_userInfo, opt_domain, opt_port,823                           opt_path, opt_query, opt_fragment, opt_ignoreCase) {824825  var uri = new goog.Uri(null, opt_ignoreCase);826827  // Only set the parts if they are defined and not empty strings.828  opt_scheme && uri.setScheme(opt_scheme);829  opt_userInfo && uri.setUserInfo(opt_userInfo);830  opt_domain && uri.setDomain(opt_domain);831  opt_port && uri.setPort(opt_port);832  opt_path && uri.setPath(opt_path);833  opt_query && uri.setQueryData(opt_query);834  opt_fragment && uri.setFragment(opt_fragment);835836  return uri;837};838839840/**841 * Resolves a relative Uri against a base Uri, accepting both strings and842 * Uri objects.843 *844 * @param {*} base Base Uri.845 * @param {*} rel Relative Uri.846 * @return {!goog.Uri} Resolved uri.847 */848goog.Uri.resolve = function(base, rel) {849  if (!(base instanceof goog.Uri)) {850    base = goog.Uri.parse(base);851  }852853  if (!(rel instanceof goog.Uri)) {854    rel = goog.Uri.parse(rel);855  }856857  return base.resolve(rel);858};859860861/**862 * Removes dot segments in given path component, as described in863 * RFC 3986, section 5.2.4.864 *865 * @param {string} path A non-empty path component.866 * @return {string} Path component with removed dot segments.867 */868goog.Uri.removeDotSegments = function(path) {869  if (path == '..' || path == '.') {870    return '';871872  } else if (!goog.string.contains(path, './') &&873             !goog.string.contains(path, '/.')) {874    // This optimization detects uris which do not contain dot-segments,875    // and as a consequence do not require any processing.876    return path;877878  } else {879    var leadingSlash = goog.string.startsWith(path, '/');880    var segments = path.split('/');881    var out = [];882883    for (var pos = 0; pos < segments.length; ) {884      var segment = segments[pos++];885886      if (segment == '.') {887        if (leadingSlash && pos == segments.length) {888          out.push('');889        }890      } else if (segment == '..') {891        if (out.length > 1 || out.length == 1 && out[0] != '') {892          out.pop();893        }894        if (leadingSlash && pos == segments.length) {895          out.push('');896        }897      } else {898        out.push(segment);899        leadingSlash = true;900      }901    }902903    return out.join('/');904  }905};906907908/**909 * Decodes a value or returns the empty string if it isn't defined or empty.910 * @param {string|undefined} val Value to decode.911 * @return {string} Decoded value.912 * @private913 */914goog.Uri.decodeOrEmpty_ = function(val) {915  // Don't use UrlDecode() here because val is not a query parameter.916  return val ? decodeURIComponent(val) : '';917};918919920/**921 * If unescapedPart is non null, then escapes any characters in it that aren't922 * valid characters in a url and also escapes any special characters that923 * appear in extra.924 *925 * @param {*} unescapedPart The string to encode.926 * @param {RegExp} extra A character set of characters in [\01-\177].927 * @return {?string} null iff unescapedPart == null.928 * @private929 */930goog.Uri.encodeSpecialChars_ = function(unescapedPart, extra) {931  if (goog.isString(unescapedPart)) {932    return encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);933  }934  return null;935};936937938/**939 * Converts a character in [\01-\177] to its unicode character equivalent.940 * @param {string} ch One character string.941 * @return {string} Encoded string.942 * @private943 */944goog.Uri.encodeChar_ = function(ch) {945  var n = ch.charCodeAt(0);946  return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);947};948949950/**951 * Regular expression for characters that are disallowed in the scheme or952 * userInfo part of the URI.953 * @type {RegExp}954 * @private955 */956goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g;957958959/**960 * Regular expression for characters that are disallowed in a relative path.961 * @type {RegExp}962 * @private963 */964goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g;965966967/**968 * Regular expression for characters that are disallowed in an absolute path.969 * @type {RegExp}970 * @private971 */972goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g;973974975/**976 * Regular expression for characters that are disallowed in the query.977 * @type {RegExp}978 * @private979 */980goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g;981982983/**984 * Regular expression for characters that are disallowed in the fragment.985 * @type {RegExp}986 * @private987 */988goog.Uri.reDisallowedInFragment_ = /#/g;989990991/**992 * Checks whether two URIs have the same domain.993 * @param {string} uri1String First URI string.994 * @param {string} uri2String Second URI string.995 * @return {boolean} true if the two URIs have the same domain; false otherwise.996 */997goog.Uri.haveSameDomain = function(uri1String, uri2String) {998  // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.999  // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.1000  var pieces1 = goog.uri.utils.split(uri1String);1001  var pieces2 = goog.uri.utils.split(uri2String);1002  return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==1003             pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&1004         pieces1[goog.uri.utils.ComponentIndex.PORT] ==1005             pieces2[goog.uri.utils.ComponentIndex.PORT];1006};1007100810091010/**1011 * Class used to represent URI query parameters.  It is essentially a hash of1012 * name-value pairs, though a name can be present more than once.1013 *1014 * Has the same interface as the collections in goog.structs.1015 *1016 * @param {?string=} opt_query Optional encoded query string to parse into1017 *     the object.1018 * @param {goog.Uri=} opt_uri Optional uri object that should have its1019 *     cache invalidated when this object updates. Deprecated -- this1020 *     is no longer required.1021 * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter1022 *     name in #get.1023 * @constructor1024 * @final1025 */1026goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {1027  /**1028   * Encoded query string, or null if it requires computing from the key map.1029   * @type {?string}1030   * @private1031   */1032  this.encodedQuery_ = opt_query || null;10331034  /**1035   * If true, ignore the case of the parameter name in #get.1036   * @type {boolean}1037   * @private1038   */1039  this.ignoreCase_ = !!opt_ignoreCase;1040};104110421043/**1044 * If the underlying key map is not yet initialized, it parses the1045 * query string and fills the map with parsed data.1046 * @private1047 */1048goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {1049  if (!this.keyMap_) {1050    this.keyMap_ = new goog.structs.Map();1051    this.count_ = 0;10521053    if (this.encodedQuery_) {1054      var pairs = this.encodedQuery_.split('&');1055      for (var i = 0; i < pairs.length; i++) {1056        var indexOfEquals = pairs[i].indexOf('=');1057        var name = null;1058        var value = null;1059        if (indexOfEquals >= 0) {1060          name = pairs[i].substring(0, indexOfEquals);1061          value = pairs[i].substring(indexOfEquals + 1);1062        } else {1063          name = pairs[i];1064        }1065        name = goog.string.urlDecode(name);1066        name = this.getKeyName_(name);1067        this.add(name, value ? goog.string.urlDecode(value) : '');1068      }1069    }1070  }1071};107210731074/**1075 * Creates a new query data instance from a map of names and values.1076 *1077 * @param {!goog.structs.Map|!Object} map Map of string parameter1078 *     names to parameter value. If parameter value is an array, it is1079 *     treated as if the key maps to each individual value in the1080 *     array.1081 * @param {goog.Uri=} opt_uri URI object that should have its cache1082 *     invalidated when this object updates.1083 * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter1084 *     name in #get.1085 * @return {!goog.Uri.QueryData} The populated query data instance.1086 */1087goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {1088  var keys = goog.structs.getKeys(map);1089  if (typeof keys == 'undefined') {1090    throw Error('Keys are undefined');1091  }10921093  var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);1094  var values = goog.structs.getValues(map);1095  for (var i = 0; i < keys.length; i++) {1096    var key = keys[i];1097    var value = values[i];1098    if (!goog.isArray(value)) {1099      queryData.add(key, value);1100    } else {1101      queryData.setValues(key, value);1102    }1103  }1104  return queryData;1105};110611071108/**1109 * Creates a new query data instance from parallel arrays of parameter names1110 * and values. Allows for duplicate parameter names. Throws an error if the1111 * lengths of the arrays differ.1112 *1113 * @param {Array.<string>} keys Parameter names.1114 * @param {Array} values Parameter values.1115 * @param {goog.Uri=} opt_uri URI object that should have its cache1116 *     invalidated when this object updates.1117 * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter1118 *     name in #get.1119 * @return {!goog.Uri.QueryData} The populated query data instance.1120 */1121goog.Uri.QueryData.createFromKeysValues = function(1122    keys, values, opt_uri, opt_ignoreCase) {1123  if (keys.length != values.length) {1124    throw Error('Mismatched lengths for keys/values');1125  }1126  var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);1127  for (var i = 0; i < keys.length; i++) {1128    queryData.add(keys[i], values[i]);1129  }1130  return queryData;1131};113211331134/**1135 * The map containing name/value or name/array-of-values pairs.1136 * May be null if it requires parsing from the query string.1137 *1138 * We need to use a Map because we cannot guarantee that the key names will1139 * not be problematic for IE.1140 *1141 * @type {goog.structs.Map.<string, Array>}1142 * @private1143 */1144goog.Uri.QueryData.prototype.keyMap_ = null;114511461147/**1148 * The number of params, or null if it requires computing.1149 * @type {?number}1150 * @private1151 */1152goog.Uri.QueryData.prototype.count_ = null;115311541155/**1156 * @return {?number} The number of parameters.1157 */1158goog.Uri.QueryData.prototype.getCount = function() {1159  this.ensureKeyMapInitialized_();1160  return this.count_;1161};116211631164/**1165 * Adds a key value pair.1166 * @param {string} key Name.1167 * @param {*} value Value.1168 * @return {!goog.Uri.QueryData} Instance of this object.1169 */1170goog.Uri.QueryData.prototype.add = function(key, value) {1171  this.ensureKeyMapInitialized_();1172  this.invalidateCache_();11731174  key = this.getKeyName_(key);1175  var values = this.keyMap_.get(key);1176  if (!values) {1177    this.keyMap_.set(key, (values = []));1178  }1179  values.push(value);1180  this.count_++;1181  return this;1182};118311841185/**1186 * Removes all the params with the given key.1187 * @param {string} key Name.1188 * @return {boolean} Whether any parameter was removed.1189 */1190goog.Uri.QueryData.prototype.remove = function(key) {1191  this.ensureKeyMapInitialized_();11921193  key = this.getKeyName_(key);1194  if (this.keyMap_.containsKey(key)) {1195    this.invalidateCache_();11961197    // Decrement parameter count.1198    this.count_ -= this.keyMap_.get(key).length;1199    return this.keyMap_.remove(key);1200  }1201  return false;1202};120312041205/**1206 * Clears the parameters.1207 */1208goog.Uri.QueryData.prototype.clear = function() {1209  this.invalidateCache_();1210  this.keyMap_ = null;1211  this.count_ = 0;1212};121312141215/**1216 * @return {boolean} Whether we have any parameters.1217 */1218goog.Uri.QueryData.prototype.isEmpty = function() {1219  this.ensureKeyMapInitialized_();1220  return this.count_ == 0;1221};122212231224/**1225 * Whether there is a parameter with the given name1226 * @param {string} key The parameter name to check for.1227 * @return {boolean} Whether there is a parameter with the given name.1228 */1229goog.Uri.QueryData.prototype.containsKey = function(key) {1230  this.ensureKeyMapInitialized_();1231  key = this.getKeyName_(key);1232  return this.keyMap_.containsKey(key);1233};123412351236/**1237 * Whether there is a parameter with the given value.1238 * @param {*} value The value to check for.1239 * @return {boolean} Whether there is a parameter with the given value.1240 */1241goog.Uri.QueryData.prototype.containsValue = function(value) {1242  // NOTE(arv): This solution goes through all the params even if it was the1243  // first param. We can get around this by not reusing code or by switching to1244  // iterators.1245  var vals = this.getValues();1246  return goog.array.contains(vals, value);1247};124812491250/**1251 * Returns all the keys of the parameters. If a key is used multiple times1252 * it will be included multiple times in the returned array1253 * @return {!Array.<string>} All the keys of the parameters.1254 */1255goog.Uri.QueryData.prototype.getKeys = function() {1256  this.ensureKeyMapInitialized_();1257  // We need to get the values to know how many keys to add.1258  var vals = /** @type {Array.<Array|*>} */ (this.keyMap_.getValues());1259  var keys = this.keyMap_.getKeys();1260  var rv = [];1261  for (var i = 0; i < keys.length; i++) {1262    var val = vals[i];1263    for (var j = 0; j < val.length; j++) {1264      rv.push(keys[i]);1265    }1266  }1267  return rv;1268};126912701271/**1272 * Returns all the values of the parameters with the given name. If the query1273 * data has no such key this will return an empty array. If no key is given1274 * all values wil be returned.1275 * @param {string=} opt_key The name of the parameter to get the values for.1276 * @return {!Array} All the values of the parameters with the given name.1277 */1278goog.Uri.QueryData.prototype.getValues = function(opt_key) {1279  this.ensureKeyMapInitialized_();1280  var rv = [];1281  if (goog.isString(opt_key)) {1282    if (this.containsKey(opt_key)) {1283      rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));1284    }1285  } else {1286    // Return all values.1287    var values = /** @type {Array.<Array|*>} */ (this.keyMap_.getValues());1288    for (var i = 0; i < values.length; i++) {1289      rv = goog.array.concat(rv, values[i]);1290    }1291  }1292  return rv;1293};129412951296/**1297 * Sets a key value pair and removes all other keys with the same value.1298 *1299 * @param {string} key Name.1300 * @param {*} value Value.1301 * @return {!goog.Uri.QueryData} Instance of this object.1302 */1303goog.Uri.QueryData.prototype.set = function(key, value) {1304  this.ensureKeyMapInitialized_();1305  this.invalidateCache_();13061307  // TODO(user): This could be better written as1308  // this.remove(key), this.add(key, value), but that would reorder1309  // the key (since the key is first removed and then added at the1310  // end) and we would have to fix unit tests that depend on key1311  // ordering.1312  key = this.getKeyName_(key);1313  if (this.containsKey(key)) {1314    this.count_ -= this.keyMap_.get(key).length;1315  }1316  this.keyMap_.set(key, [value]);1317  this.count_++;1318  return this;1319};132013211322/**1323 * Returns the first value associated with the key. If the query data has no1324 * such key this will return undefined or the optional default.1325 * @param {string} key The name of the parameter to get the value for.1326 * @param {*=} opt_default The default value to return if the query data1327 *     has no such key.1328 * @return {*} The first string value associated with the key, or opt_default1329 *     if there's no value.1330 */1331goog.Uri.QueryData.prototype.get = function(key, opt_default) {1332  var values = key ? this.getValues(key) : [];1333  if (goog.Uri.preserveParameterTypesCompatibilityFlag) {1334    return values.length > 0 ? values[0] : opt_default;1335  } else {1336    return values.length > 0 ? String(values[0]) : opt_default;1337  }1338};133913401341/**1342 * Sets the values for a key. If the key already exists, this will1343 * override all of the existing values that correspond to the key.1344 * @param {string} key The key to set values for.1345 * @param {Array} values The values to set.1346 */1347goog.Uri.QueryData.prototype.setValues = function(key, values) {1348  this.remove(key);13491350  if (values.length > 0) {1351    this.invalidateCache_();1352    this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));1353    this.count_ += values.length;1354  }1355};135613571358/**1359 * @return {string} Encoded query string.1360 * @override1361 */1362goog.Uri.QueryData.prototype.toString = function() {1363  if (this.encodedQuery_) {1364    return this.encodedQuery_;1365  }13661367  if (!this.keyMap_) {1368    return '';1369  }13701371  var sb = [];13721373  // In the past, we use this.getKeys() and this.getVals(), but that1374  // generates a lot of allocations as compared to simply iterating1375  // over the keys.1376  var keys = this.keyMap_.getKeys();1377  for (var i = 0; i < keys.length; i++) {1378    var key = keys[i];1379    var encodedKey = goog.string.urlEncode(key);1380    var val = this.getValues(key);1381    for (var j = 0; j < val.length; j++) {1382      var param = encodedKey;1383      // Ensure that null and undefined are encoded into the url as1384      // literal strings.1385      if (val[j] !== '') {1386        param += '=' + goog.string.urlEncode(val[j]);1387      }1388      sb.push(param);1389    }1390  }13911392  return this.encodedQuery_ = sb.join('&');1393};139413951396/**1397 * @return {string} Decoded query string.1398 */1399goog.Uri.QueryData.prototype.toDecodedString = function() {1400  return goog.Uri.decodeOrEmpty_(this.toString());1401};140214031404/**1405 * Invalidate the cache.1406 * @private1407 */1408goog.Uri.QueryData.prototype.invalidateCache_ = function() {1409  this.encodedQuery_ = null;1410};141114121413/**1414 * Removes all keys that are not in the provided list. (Modifies this object.)1415 * @param {Array.<string>} keys The desired keys.1416 * @return {!goog.Uri.QueryData} a reference to this object.1417 */1418goog.Uri.QueryData.prototype.filterKeys = function(keys) {1419  this.ensureKeyMapInitialized_();1420  this.keyMap_.forEach(1421      function(value, key) {1422        if (!goog.array.contains(keys, key)) {1423          this.remove(key);1424        }1425      }, this);1426  return this;1427};142814291430/**1431 * Clone the query data instance.1432 * @return {!goog.Uri.QueryData} New instance of the QueryData object.1433 */1434goog.Uri.QueryData.prototype.clone = function() {1435  var rv = new goog.Uri.QueryData();1436  rv.encodedQuery_ = this.encodedQuery_;1437  if (this.keyMap_) {1438    rv.keyMap_ = this.keyMap_.clone();1439    rv.count_ = this.count_;1440  }1441  return rv;1442};144314441445/**1446 * Helper function to get the key name from a JavaScript object. Converts1447 * the object to a string, and to lower case if necessary.1448 * @private1449 * @param {*} arg The object to get a key name from.1450 * @return {string} valid key name which can be looked up in #keyMap_.1451 */1452goog.Uri.QueryData.prototype.getKeyName_ = function(arg) {1453  var keyName = String(arg);1454  if (this.ignoreCase_) {1455    keyName = keyName.toLowerCase();1456  }1457  return keyName;1458};145914601461/**1462 * Ignore case in parameter names.1463 * NOTE: If there are already key/value pairs in the QueryData, and1464 * ignoreCase_ is set to false, the keys will all be lower-cased.1465 * @param {boolean} ignoreCase whether this goog.Uri should ignore case.1466 */1467goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {1468  var resetKeys = ignoreCase && !this.ignoreCase_;1469  if (resetKeys) {1470    this.ensureKeyMapInitialized_();1471    this.invalidateCache_();1472    this.keyMap_.forEach(1473        function(value, key) {1474          var lowerCase = key.toLowerCase();1475          if (key != lowerCase) {1476            this.remove(key);1477            this.setValues(lowerCase, value);1478          }1479        }, this);1480  }1481  this.ignoreCase_ = ignoreCase;1482};148314841485/**1486 * Extends a query data object with another query data or map like object. This1487 * operates 'in-place', it does not create a new QueryData object.1488 *1489 * @param {...(goog.Uri.QueryData|goog.structs.Map|Object)} var_args The object1490 *     from which key value pairs will be copied.1491 */1492goog.Uri.QueryData.prototype.extend = function(var_args) {1493  for (var i = 0; i < arguments.length; i++) {1494    var data = arguments[i];1495    goog.structs.forEach(data,1496        /** @this {goog.Uri.QueryData} */1497        function(value, key) {1498          this.add(key, value);1499        }, this);1500  }1501};