From 2b4757367470d8e36bc00901dac567e375796ed4 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Tue, 13 Nov 2018 00:24:09 -0500 Subject: update viz 2 to use the newest version, which has some performance improvements and is easier to read the code for. also update the description --- assets/viz/2/goog/uri/uri.js | 1547 ++++++++++++++++++++++++++++++++++++++++ assets/viz/2/goog/uri/utils.js | 1103 ++++++++++++++++++++++++++++ 2 files changed, 2650 insertions(+) create mode 100644 assets/viz/2/goog/uri/uri.js create mode 100644 assets/viz/2/goog/uri/utils.js (limited to 'assets/viz/2/goog/uri') diff --git a/assets/viz/2/goog/uri/uri.js b/assets/viz/2/goog/uri/uri.js new file mode 100644 index 0000000..7873de9 --- /dev/null +++ b/assets/viz/2/goog/uri/uri.js @@ -0,0 +1,1547 @@ +// Copyright 2006 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Class for parsing and formatting URIs. + * + * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to + * create a new instance of the goog.Uri object from Uri parts. + * + * e.g: var myUri = new goog.Uri(window.location); + * + * Implements RFC 3986 for parsing/formatting URIs. + * http://www.ietf.org/rfc/rfc3986.txt + * + * Some changes have been made to the interface (more like .NETs), though the + * internal representation is now of un-encoded parts, this will change the + * behavior slightly. + * + * @author msamuel@google.com (Mike Samuel) + */ + +goog.provide('goog.Uri'); +goog.provide('goog.Uri.QueryData'); + +goog.require('goog.array'); +goog.require('goog.asserts'); +goog.require('goog.string'); +goog.require('goog.structs'); +goog.require('goog.structs.Map'); +goog.require('goog.uri.utils'); +goog.require('goog.uri.utils.ComponentIndex'); +goog.require('goog.uri.utils.StandardQueryParam'); + + + +/** + * This class contains setters and getters for the parts of the URI. + * The getXyz/setXyz methods return the decoded part + * -- sogoog.Uri.parse('/foo%20bar').getPath() will return the + * decoded path, /foo bar. + * + * Reserved characters (see RFC 3986 section 2.2) can be present in + * their percent-encoded form in scheme, domain, and path URI components and + * will not be auto-decoded. For example: + * goog.Uri.parse('rel%61tive/path%2fto/resource').getPath() will + * return relative/path%2fto/resource. + * + * The constructor accepts an optional unparsed, raw URI string. The parser + * is relaxed, so special characters that aren't escaped but don't cause + * ambiguities will not cause parse failures. + * + * All setters return this and so may be chained, a la + * goog.Uri.parse('/foo').setFragment('part').toString(). + * + * @param {*=} opt_uri Optional string URI to parse + * (use goog.Uri.create() to create a URI from parts), or if + * a goog.Uri is passed, a clone is created. + * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore + * the case of the parameter name. + * + * @throws URIError If opt_uri is provided and URI is malformed (that is, + * if decodeURIComponent fails on any of the URI components). + * @constructor + * @struct + */ +goog.Uri = function(opt_uri, opt_ignoreCase) { + /** + * Scheme such as "http". + * @private {string} + */ + this.scheme_ = ''; + + /** + * User credentials in the form "username:password". + * @private {string} + */ + this.userInfo_ = ''; + + /** + * Domain part, e.g. "www.google.com". + * @private {string} + */ + this.domain_ = ''; + + /** + * Port, e.g. 8080. + * @private {?number} + */ + this.port_ = null; + + /** + * Path, e.g. "/tests/img.png". + * @private {string} + */ + this.path_ = ''; + + /** + * The fragment without the #. + * @private {string} + */ + this.fragment_ = ''; + + /** + * Whether or not this Uri should be treated as Read Only. + * @private {boolean} + */ + this.isReadOnly_ = false; + + /** + * Whether or not to ignore case when comparing query params. + * @private {boolean} + */ + this.ignoreCase_ = false; + + /** + * Object representing query data. + * @private {!goog.Uri.QueryData} + */ + this.queryData_; + + // Parse in the uri string + var m; + if (opt_uri instanceof goog.Uri) { + this.ignoreCase_ = + goog.isDef(opt_ignoreCase) ? opt_ignoreCase : opt_uri.getIgnoreCase(); + this.setScheme(opt_uri.getScheme()); + this.setUserInfo(opt_uri.getUserInfo()); + this.setDomain(opt_uri.getDomain()); + this.setPort(opt_uri.getPort()); + this.setPath(opt_uri.getPath()); + this.setQueryData(opt_uri.getQueryData().clone()); + this.setFragment(opt_uri.getFragment()); + } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) { + this.ignoreCase_ = !!opt_ignoreCase; + + // Set the parts -- decoding as we do so. + // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings, + // whereas in other browsers they will be undefined. + this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true); + this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true); + this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true); + this.setPort(m[goog.uri.utils.ComponentIndex.PORT]); + this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true); + this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true); + this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true); + + } else { + this.ignoreCase_ = !!opt_ignoreCase; + this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_); + } +}; + + +/** + * If true, we preserve the type of query parameters set programmatically. + * + * This means that if you set a parameter to a boolean, and then call + * getParameterValue, you will get a boolean back. + * + * If false, we will coerce parameters to strings, just as they would + * appear in real URIs. + * + * TODO(nicksantos): Remove this once people have time to fix all tests. + * + * @type {boolean} + */ +goog.Uri.preserveParameterTypesCompatibilityFlag = false; + + +/** + * Parameter name added to stop caching. + * @type {string} + */ +goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM; + + +/** + * @return {string} The string form of the url. + * @override + */ +goog.Uri.prototype.toString = function() { + var out = []; + + var scheme = this.getScheme(); + if (scheme) { + out.push( + goog.Uri.encodeSpecialChars_( + scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), + ':'); + } + + var domain = this.getDomain(); + if (domain || scheme == 'file') { + out.push('//'); + + var userInfo = this.getUserInfo(); + if (userInfo) { + out.push( + goog.Uri.encodeSpecialChars_( + userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), + '@'); + } + + out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain))); + + var port = this.getPort(); + if (port != null) { + out.push(':', String(port)); + } + } + + var path = this.getPath(); + if (path) { + if (this.hasDomain() && path.charAt(0) != '/') { + out.push('/'); + } + out.push( + goog.Uri.encodeSpecialChars_( + path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ : + goog.Uri.reDisallowedInRelativePath_, + true)); + } + + var query = this.getEncodedQuery(); + if (query) { + out.push('?', query); + } + + var fragment = this.getFragment(); + if (fragment) { + out.push( + '#', goog.Uri.encodeSpecialChars_( + fragment, goog.Uri.reDisallowedInFragment_)); + } + return out.join(''); +}; + + +/** + * Resolves the given relative URI (a goog.Uri object), using the URI + * represented by this instance as the base URI. + * + * There are several kinds of relative URIs:
+ * 1. foo - replaces the last part of the path, the whole query and fragment
+ * 2. /foo - replaces the the path, the query and fragment
+ * 3. //foo - replaces everything from the domain on. foo is a domain name
+ * 4. ?foo - replace the query and fragment
+ * 5. #foo - replace the fragment only + * + * Additionally, if relative URI has a non-empty path, all ".." and "." + * segments will be resolved, as described in RFC 3986. + * + * @param {!goog.Uri} relativeUri The relative URI to resolve. + * @return {!goog.Uri} The resolved URI. + */ +goog.Uri.prototype.resolve = function(relativeUri) { + + var absoluteUri = this.clone(); + + // we satisfy these conditions by looking for the first part of relativeUri + // that is not blank and applying defaults to the rest + + var overridden = relativeUri.hasScheme(); + + if (overridden) { + absoluteUri.setScheme(relativeUri.getScheme()); + } else { + overridden = relativeUri.hasUserInfo(); + } + + if (overridden) { + absoluteUri.setUserInfo(relativeUri.getUserInfo()); + } else { + overridden = relativeUri.hasDomain(); + } + + if (overridden) { + absoluteUri.setDomain(relativeUri.getDomain()); + } else { + overridden = relativeUri.hasPort(); + } + + var path = relativeUri.getPath(); + if (overridden) { + absoluteUri.setPort(relativeUri.getPort()); + } else { + overridden = relativeUri.hasPath(); + if (overridden) { + // resolve path properly + if (path.charAt(0) != '/') { + // path is relative + if (this.hasDomain() && !this.hasPath()) { + // RFC 3986, section 5.2.3, case 1 + path = '/' + path; + } else { + // RFC 3986, section 5.2.3, case 2 + var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/'); + if (lastSlashIndex != -1) { + path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path; + } + } + } + path = goog.Uri.removeDotSegments(path); + } + } + + if (overridden) { + absoluteUri.setPath(path); + } else { + overridden = relativeUri.hasQuery(); + } + + if (overridden) { + absoluteUri.setQueryData(relativeUri.getQueryData().clone()); + } else { + overridden = relativeUri.hasFragment(); + } + + if (overridden) { + absoluteUri.setFragment(relativeUri.getFragment()); + } + + return absoluteUri; +}; + + +/** + * Clones the URI instance. + * @return {!goog.Uri} New instance of the URI object. + */ +goog.Uri.prototype.clone = function() { + return new goog.Uri(this); +}; + + +/** + * @return {string} The encoded scheme/protocol for the URI. + */ +goog.Uri.prototype.getScheme = function() { + return this.scheme_; +}; + + +/** + * Sets the scheme/protocol. + * @throws URIError If opt_decode is true and newScheme is malformed (that is, + * if decodeURIComponent fails). + * @param {string} newScheme New scheme value. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setScheme = function(newScheme, opt_decode) { + this.enforceReadOnly(); + this.scheme_ = + opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme; + + // remove an : at the end of the scheme so somebody can pass in + // window.location.protocol + if (this.scheme_) { + this.scheme_ = this.scheme_.replace(/:$/, ''); + } + return this; +}; + + +/** + * @return {boolean} Whether the scheme has been set. + */ +goog.Uri.prototype.hasScheme = function() { + return !!this.scheme_; +}; + + +/** + * @return {string} The decoded user info. + */ +goog.Uri.prototype.getUserInfo = function() { + return this.userInfo_; +}; + + +/** + * Sets the userInfo. + * @throws URIError If opt_decode is true and newUserInfo is malformed (that is, + * if decodeURIComponent fails). + * @param {string} newUserInfo New userInfo value. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) { + this.enforceReadOnly(); + this.userInfo_ = + opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo; + return this; +}; + + +/** + * @return {boolean} Whether the user info has been set. + */ +goog.Uri.prototype.hasUserInfo = function() { + return !!this.userInfo_; +}; + + +/** + * @return {string} The decoded domain. + */ +goog.Uri.prototype.getDomain = function() { + return this.domain_; +}; + + +/** + * Sets the domain. + * @throws URIError If opt_decode is true and newDomain is malformed (that is, + * if decodeURIComponent fails). + * @param {string} newDomain New domain value. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setDomain = function(newDomain, opt_decode) { + this.enforceReadOnly(); + this.domain_ = + opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain; + return this; +}; + + +/** + * @return {boolean} Whether the domain has been set. + */ +goog.Uri.prototype.hasDomain = function() { + return !!this.domain_; +}; + + +/** + * @return {?number} The port number. + */ +goog.Uri.prototype.getPort = function() { + return this.port_; +}; + + +/** + * Sets the port number. + * @param {*} newPort Port number. Will be explicitly casted to a number. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setPort = function(newPort) { + this.enforceReadOnly(); + + if (newPort) { + newPort = Number(newPort); + if (isNaN(newPort) || newPort < 0) { + throw Error('Bad port number ' + newPort); + } + this.port_ = newPort; + } else { + this.port_ = null; + } + + return this; +}; + + +/** + * @return {boolean} Whether the port has been set. + */ +goog.Uri.prototype.hasPort = function() { + return this.port_ != null; +}; + + +/** + * @return {string} The decoded path. + */ +goog.Uri.prototype.getPath = function() { + return this.path_; +}; + + +/** + * Sets the path. + * @throws URIError If opt_decode is true and newPath is malformed (that is, + * if decodeURIComponent fails). + * @param {string} newPath New path value. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setPath = function(newPath, opt_decode) { + this.enforceReadOnly(); + this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath; + return this; +}; + + +/** + * @return {boolean} Whether the path has been set. + */ +goog.Uri.prototype.hasPath = function() { + return !!this.path_; +}; + + +/** + * @return {boolean} Whether the query string has been set. + */ +goog.Uri.prototype.hasQuery = function() { + return this.queryData_.toString() !== ''; +}; + + +/** + * Sets the query data. + * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * Applies only if queryData is a string. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setQueryData = function(queryData, opt_decode) { + this.enforceReadOnly(); + + if (queryData instanceof goog.Uri.QueryData) { + this.queryData_ = queryData; + this.queryData_.setIgnoreCase(this.ignoreCase_); + } else { + if (!opt_decode) { + // QueryData accepts encoded query string, so encode it if + // opt_decode flag is not true. + queryData = goog.Uri.encodeSpecialChars_( + queryData, goog.Uri.reDisallowedInQuery_); + } + this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_); + } + + return this; +}; + + +/** + * Sets the URI query. + * @param {string} newQuery New query value. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setQuery = function(newQuery, opt_decode) { + return this.setQueryData(newQuery, opt_decode); +}; + + +/** + * @return {string} The encoded URI query, not including the ?. + */ +goog.Uri.prototype.getEncodedQuery = function() { + return this.queryData_.toString(); +}; + + +/** + * @return {string} The decoded URI query, not including the ?. + */ +goog.Uri.prototype.getDecodedQuery = function() { + return this.queryData_.toDecodedString(); +}; + + +/** + * Returns the query data. + * @return {!goog.Uri.QueryData} QueryData object. + */ +goog.Uri.prototype.getQueryData = function() { + return this.queryData_; +}; + + +/** + * @return {string} The encoded URI query, not including the ?. + * + * Warning: This method, unlike other getter methods, returns encoded + * value, instead of decoded one. + */ +goog.Uri.prototype.getQuery = function() { + return this.getEncodedQuery(); +}; + + +/** + * Sets the value of the named query parameters, clearing previous values for + * that key. + * + * @param {string} key The parameter to set. + * @param {*} value The new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setParameterValue = function(key, value) { + this.enforceReadOnly(); + this.queryData_.set(key, value); + return this; +}; + + +/** + * Sets the values of the named query parameters, clearing previous values for + * that key. Not new values will currently be moved to the end of the query + * string. + * + * So, goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new']) + * yields foo?a=b&e=f&c=new.

+ * + * @param {string} key The parameter to set. + * @param {*} values The new values. If values is a single + * string then it will be treated as the sole value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setParameterValues = function(key, values) { + this.enforceReadOnly(); + + if (!goog.isArray(values)) { + values = [String(values)]; + } + + this.queryData_.setValues(key, values); + + return this; +}; + + +/** + * Returns the values for a given cgi parameter as a list of decoded + * query parameter values. + * @param {string} name The parameter to get values for. + * @return {!Array} The values for a given cgi parameter as a list of + * decoded query parameter values. + */ +goog.Uri.prototype.getParameterValues = function(name) { + return this.queryData_.getValues(name); +}; + + +/** + * Returns the first value for a given cgi parameter or undefined if the given + * parameter name does not appear in the query string. + * @param {string} paramName Unescaped parameter name. + * @return {string|undefined} The first value for a given cgi parameter or + * undefined if the given parameter name does not appear in the query + * string. + */ +goog.Uri.prototype.getParameterValue = function(paramName) { + // NOTE(nicksantos): This type-cast is a lie when + // preserveParameterTypesCompatibilityFlag is set to true. + // But this should only be set to true in tests. + return /** @type {string|undefined} */ (this.queryData_.get(paramName)); +}; + + +/** + * @return {string} The URI fragment, not including the #. + */ +goog.Uri.prototype.getFragment = function() { + return this.fragment_; +}; + + +/** + * Sets the URI fragment. + * @throws URIError If opt_decode is true and newFragment is malformed (that is, + * if decodeURIComponent fails). + * @param {string} newFragment New fragment value. + * @param {boolean=} opt_decode Optional param for whether to decode new value. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.setFragment = function(newFragment, opt_decode) { + this.enforceReadOnly(); + this.fragment_ = + opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment; + return this; +}; + + +/** + * @return {boolean} Whether the URI has a fragment set. + */ +goog.Uri.prototype.hasFragment = function() { + return !!this.fragment_; +}; + + +/** + * Returns true if this has the same domain as that of uri2. + * @param {!goog.Uri} uri2 The URI object to compare to. + * @return {boolean} true if same domain; false otherwise. + */ +goog.Uri.prototype.hasSameDomainAs = function(uri2) { + return ((!this.hasDomain() && !uri2.hasDomain()) || + this.getDomain() == uri2.getDomain()) && + ((!this.hasPort() && !uri2.hasPort()) || + this.getPort() == uri2.getPort()); +}; + + +/** + * Adds a random parameter to the Uri. + * @return {!goog.Uri} Reference to this Uri object. + */ +goog.Uri.prototype.makeUnique = function() { + this.enforceReadOnly(); + this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString()); + + return this; +}; + + +/** + * Removes the named query parameter. + * + * @param {string} key The parameter to remove. + * @return {!goog.Uri} Reference to this URI object. + */ +goog.Uri.prototype.removeParameter = function(key) { + this.enforceReadOnly(); + this.queryData_.remove(key); + return this; +}; + + +/** + * Sets whether Uri is read only. If this goog.Uri is read-only, + * enforceReadOnly_ will be called at the start of any function that may modify + * this Uri. + * @param {boolean} isReadOnly whether this goog.Uri should be read only. + * @return {!goog.Uri} Reference to this Uri object. + */ +goog.Uri.prototype.setReadOnly = function(isReadOnly) { + this.isReadOnly_ = isReadOnly; + return this; +}; + + +/** + * @return {boolean} Whether the URI is read only. + */ +goog.Uri.prototype.isReadOnly = function() { + return this.isReadOnly_; +}; + + +/** + * Checks if this Uri has been marked as read only, and if so, throws an error. + * This should be called whenever any modifying function is called. + */ +goog.Uri.prototype.enforceReadOnly = function() { + if (this.isReadOnly_) { + throw Error('Tried to modify a read-only Uri'); + } +}; + + +/** + * Sets whether to ignore case. + * NOTE: If there are already key/value pairs in the QueryData, and + * ignoreCase_ is set to false, the keys will all be lower-cased. + * @param {boolean} ignoreCase whether this goog.Uri should ignore case. + * @return {!goog.Uri} Reference to this Uri object. + */ +goog.Uri.prototype.setIgnoreCase = function(ignoreCase) { + this.ignoreCase_ = ignoreCase; + if (this.queryData_) { + this.queryData_.setIgnoreCase(ignoreCase); + } + return this; +}; + + +/** + * @return {boolean} Whether to ignore case. + */ +goog.Uri.prototype.getIgnoreCase = function() { + return this.ignoreCase_; +}; + + +//============================================================================== +// Static members +//============================================================================== + + +/** + * Creates a uri from the string form. Basically an alias of new goog.Uri(). + * If a Uri object is passed to parse then it will return a clone of the object. + * + * @throws URIError If parsing the URI is malformed. The passed URI components + * should all be parseable by decodeURIComponent. + * @param {*} uri Raw URI string or instance of Uri + * object. + * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter + * names in #getParameterValue. + * @return {!goog.Uri} The new URI object. + */ +goog.Uri.parse = function(uri, opt_ignoreCase) { + return uri instanceof goog.Uri ? uri.clone() : + new goog.Uri(uri, opt_ignoreCase); +}; + + +/** + * Creates a new goog.Uri object from unencoded parts. + * + * @param {?string=} opt_scheme Scheme/protocol or full URI to parse. + * @param {?string=} opt_userInfo username:password. + * @param {?string=} opt_domain www.google.com. + * @param {?number=} opt_port 9830. + * @param {?string=} opt_path /some/path/to/a/file.html. + * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2. + * @param {?string=} opt_fragment The fragment without the #. + * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in + * #getParameterValue. + * + * @return {!goog.Uri} The new URI object. + */ +goog.Uri.create = function( + opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query, + opt_fragment, opt_ignoreCase) { + + var uri = new goog.Uri(null, opt_ignoreCase); + + // Only set the parts if they are defined and not empty strings. + opt_scheme && uri.setScheme(opt_scheme); + opt_userInfo && uri.setUserInfo(opt_userInfo); + opt_domain && uri.setDomain(opt_domain); + opt_port && uri.setPort(opt_port); + opt_path && uri.setPath(opt_path); + opt_query && uri.setQueryData(opt_query); + opt_fragment && uri.setFragment(opt_fragment); + + return uri; +}; + + +/** + * Resolves a relative Uri against a base Uri, accepting both strings and + * Uri objects. + * + * @param {*} base Base Uri. + * @param {*} rel Relative Uri. + * @return {!goog.Uri} Resolved uri. + */ +goog.Uri.resolve = function(base, rel) { + if (!(base instanceof goog.Uri)) { + base = goog.Uri.parse(base); + } + + if (!(rel instanceof goog.Uri)) { + rel = goog.Uri.parse(rel); + } + + return base.resolve(rel); +}; + + +/** + * Removes dot segments in given path component, as described in + * RFC 3986, section 5.2.4. + * + * @param {string} path A non-empty path component. + * @return {string} Path component with removed dot segments. + */ +goog.Uri.removeDotSegments = function(path) { + if (path == '..' || path == '.') { + return ''; + + } else if ( + !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) { + // This optimization detects uris which do not contain dot-segments, + // and as a consequence do not require any processing. + return path; + + } else { + var leadingSlash = goog.string.startsWith(path, '/'); + var segments = path.split('/'); + var out = []; + + for (var pos = 0; pos < segments.length;) { + var segment = segments[pos++]; + + if (segment == '.') { + if (leadingSlash && pos == segments.length) { + out.push(''); + } + } else if (segment == '..') { + if (out.length > 1 || out.length == 1 && out[0] != '') { + out.pop(); + } + if (leadingSlash && pos == segments.length) { + out.push(''); + } + } else { + out.push(segment); + leadingSlash = true; + } + } + + return out.join('/'); + } +}; + + +/** + * Decodes a value or returns the empty string if it isn't defined or empty. + * @throws URIError If decodeURIComponent fails to decode val. + * @param {string|undefined} val Value to decode. + * @param {boolean=} opt_preserveReserved If true, restricted characters will + * not be decoded. + * @return {string} Decoded value. + * @private + */ +goog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) { + // Don't use UrlDecode() here because val is not a query parameter. + if (!val) { + return ''; + } + + // decodeURI has the same output for '%2f' and '%252f'. We double encode %25 + // so that we can distinguish between the 2 inputs. This is later undone by + // removeDoubleEncoding_. + return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) : + decodeURIComponent(val); +}; + + +/** + * If unescapedPart is non null, then escapes any characters in it that aren't + * valid characters in a url and also escapes any special characters that + * appear in extra. + * + * @param {*} unescapedPart The string to encode. + * @param {RegExp} extra A character set of characters in [\01-\177]. + * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent + * encoding. + * @return {?string} null iff unescapedPart == null. + * @private + */ +goog.Uri.encodeSpecialChars_ = function( + unescapedPart, extra, opt_removeDoubleEncoding) { + if (goog.isString(unescapedPart)) { + var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_); + if (opt_removeDoubleEncoding) { + // encodeURI double-escapes %XX sequences used to represent restricted + // characters in some URI components, remove the double escaping here. + encoded = goog.Uri.removeDoubleEncoding_(encoded); + } + return encoded; + } + return null; +}; + + +/** + * Converts a character in [\01-\177] to its unicode character equivalent. + * @param {string} ch One character string. + * @return {string} Encoded string. + * @private + */ +goog.Uri.encodeChar_ = function(ch) { + var n = ch.charCodeAt(0); + return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16); +}; + + +/** + * Removes double percent-encoding from a string. + * @param {string} doubleEncodedString String + * @return {string} String with double encoding removed. + * @private + */ +goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) { + return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1'); +}; + + +/** + * Regular expression for characters that are disallowed in the scheme or + * userInfo part of the URI. + * @type {RegExp} + * @private + */ +goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g; + + +/** + * Regular expression for characters that are disallowed in a relative path. + * Colon is included due to RFC 3986 3.3. + * @type {RegExp} + * @private + */ +goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g; + + +/** + * Regular expression for characters that are disallowed in an absolute path. + * @type {RegExp} + * @private + */ +goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g; + + +/** + * Regular expression for characters that are disallowed in the query. + * @type {RegExp} + * @private + */ +goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g; + + +/** + * Regular expression for characters that are disallowed in the fragment. + * @type {RegExp} + * @private + */ +goog.Uri.reDisallowedInFragment_ = /#/g; + + +/** + * Checks whether two URIs have the same domain. + * @param {string} uri1String First URI string. + * @param {string} uri2String Second URI string. + * @return {boolean} true if the two URIs have the same domain; false otherwise. + */ +goog.Uri.haveSameDomain = function(uri1String, uri2String) { + // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme. + // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain. + var pieces1 = goog.uri.utils.split(uri1String); + var pieces2 = goog.uri.utils.split(uri2String); + return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == + pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && + pieces1[goog.uri.utils.ComponentIndex.PORT] == + pieces2[goog.uri.utils.ComponentIndex.PORT]; +}; + + + +/** + * Class used to represent URI query parameters. It is essentially a hash of + * name-value pairs, though a name can be present more than once. + * + * Has the same interface as the collections in goog.structs. + * + * @param {?string=} opt_query Optional encoded query string to parse into + * the object. + * @param {goog.Uri=} opt_uri Optional uri object that should have its + * cache invalidated when this object updates. Deprecated -- this + * is no longer required. + * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter + * name in #get. + * @constructor + * @struct + * @final + */ +goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) { + /** + * The map containing name/value or name/array-of-values pairs. + * May be null if it requires parsing from the query string. + * + * We need to use a Map because we cannot guarantee that the key names will + * not be problematic for IE. + * + * @private {goog.structs.Map>} + */ + this.keyMap_ = null; + + /** + * The number of params, or null if it requires computing. + * @private {?number} + */ + this.count_ = null; + + /** + * Encoded query string, or null if it requires computing from the key map. + * @private {?string} + */ + this.encodedQuery_ = opt_query || null; + + /** + * If true, ignore the case of the parameter name in #get. + * @private {boolean} + */ + this.ignoreCase_ = !!opt_ignoreCase; +}; + + +/** + * If the underlying key map is not yet initialized, it parses the + * query string and fills the map with parsed data. + * @private + */ +goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() { + if (!this.keyMap_) { + this.keyMap_ = new goog.structs.Map(); + this.count_ = 0; + if (this.encodedQuery_) { + var self = this; + goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) { + self.add(goog.string.urlDecode(name), value); + }); + } + } +}; + + +/** + * Creates a new query data instance from a map of names and values. + * + * @param {!goog.structs.Map|!Object} map Map of string parameter + * names to parameter value. If parameter value is an array, it is + * treated as if the key maps to each individual value in the + * array. + * @param {goog.Uri=} opt_uri URI object that should have its cache + * invalidated when this object updates. + * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter + * name in #get. + * @return {!goog.Uri.QueryData} The populated query data instance. + */ +goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) { + var keys = goog.structs.getKeys(map); + if (typeof keys == 'undefined') { + throw Error('Keys are undefined'); + } + + var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); + var values = goog.structs.getValues(map); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = values[i]; + if (!goog.isArray(value)) { + queryData.add(key, value); + } else { + queryData.setValues(key, value); + } + } + return queryData; +}; + + +/** + * Creates a new query data instance from parallel arrays of parameter names + * and values. Allows for duplicate parameter names. Throws an error if the + * lengths of the arrays differ. + * + * @param {!Array} keys Parameter names. + * @param {!Array} values Parameter values. + * @param {goog.Uri=} opt_uri URI object that should have its cache + * invalidated when this object updates. + * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter + * name in #get. + * @return {!goog.Uri.QueryData} The populated query data instance. + */ +goog.Uri.QueryData.createFromKeysValues = function( + keys, values, opt_uri, opt_ignoreCase) { + if (keys.length != values.length) { + throw Error('Mismatched lengths for keys/values'); + } + var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); + for (var i = 0; i < keys.length; i++) { + queryData.add(keys[i], values[i]); + } + return queryData; +}; + + +/** + * @return {?number} The number of parameters. + */ +goog.Uri.QueryData.prototype.getCount = function() { + this.ensureKeyMapInitialized_(); + return this.count_; +}; + + +/** + * Adds a key value pair. + * @param {string} key Name. + * @param {*} value Value. + * @return {!goog.Uri.QueryData} Instance of this object. + */ +goog.Uri.QueryData.prototype.add = function(key, value) { + this.ensureKeyMapInitialized_(); + this.invalidateCache_(); + + key = this.getKeyName_(key); + var values = this.keyMap_.get(key); + if (!values) { + this.keyMap_.set(key, (values = [])); + } + values.push(value); + this.count_ = goog.asserts.assertNumber(this.count_) + 1; + return this; +}; + + +/** + * Removes all the params with the given key. + * @param {string} key Name. + * @return {boolean} Whether any parameter was removed. + */ +goog.Uri.QueryData.prototype.remove = function(key) { + this.ensureKeyMapInitialized_(); + + key = this.getKeyName_(key); + if (this.keyMap_.containsKey(key)) { + this.invalidateCache_(); + + // Decrement parameter count. + this.count_ = + goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length; + return this.keyMap_.remove(key); + } + return false; +}; + + +/** + * Clears the parameters. + */ +goog.Uri.QueryData.prototype.clear = function() { + this.invalidateCache_(); + this.keyMap_ = null; + this.count_ = 0; +}; + + +/** + * @return {boolean} Whether we have any parameters. + */ +goog.Uri.QueryData.prototype.isEmpty = function() { + this.ensureKeyMapInitialized_(); + return this.count_ == 0; +}; + + +/** + * Whether there is a parameter with the given name + * @param {string} key The parameter name to check for. + * @return {boolean} Whether there is a parameter with the given name. + */ +goog.Uri.QueryData.prototype.containsKey = function(key) { + this.ensureKeyMapInitialized_(); + key = this.getKeyName_(key); + return this.keyMap_.containsKey(key); +}; + + +/** + * Whether there is a parameter with the given value. + * @param {*} value The value to check for. + * @return {boolean} Whether there is a parameter with the given value. + */ +goog.Uri.QueryData.prototype.containsValue = function(value) { + // NOTE(arv): This solution goes through all the params even if it was the + // first param. We can get around this by not reusing code or by switching to + // iterators. + var vals = this.getValues(); + return goog.array.contains(vals, value); +}; + + +/** + * Runs a callback on every key-value pair in the map, including duplicate keys. + * This won't maintain original order when duplicate keys are interspersed (like + * getKeys() / getValues()). + * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f + * @param {SCOPE=} opt_scope The value of "this" inside f. + * @template SCOPE + */ +goog.Uri.QueryData.prototype.forEach = function(f, opt_scope) { + this.ensureKeyMapInitialized_(); + this.keyMap_.forEach(function(values, key) { + goog.array.forEach(values, function(value) { + f.call(opt_scope, value, key, this); + }, this); + }, this); +}; + + +/** + * Returns all the keys of the parameters. If a key is used multiple times + * it will be included multiple times in the returned array + * @return {!Array} All the keys of the parameters. + */ +goog.Uri.QueryData.prototype.getKeys = function() { + this.ensureKeyMapInitialized_(); + // We need to get the values to know how many keys to add. + var vals = this.keyMap_.getValues(); + var keys = this.keyMap_.getKeys(); + var rv = []; + for (var i = 0; i < keys.length; i++) { + var val = vals[i]; + for (var j = 0; j < val.length; j++) { + rv.push(keys[i]); + } + } + return rv; +}; + + +/** + * Returns all the values of the parameters with the given name. If the query + * data has no such key this will return an empty array. If no key is given + * all values wil be returned. + * @param {string=} opt_key The name of the parameter to get the values for. + * @return {!Array} All the values of the parameters with the given name. + */ +goog.Uri.QueryData.prototype.getValues = function(opt_key) { + this.ensureKeyMapInitialized_(); + var rv = []; + if (goog.isString(opt_key)) { + if (this.containsKey(opt_key)) { + rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key))); + } + } else { + // Return all values. + var values = this.keyMap_.getValues(); + for (var i = 0; i < values.length; i++) { + rv = goog.array.concat(rv, values[i]); + } + } + return rv; +}; + + +/** + * Sets a key value pair and removes all other keys with the same value. + * + * @param {string} key Name. + * @param {*} value Value. + * @return {!goog.Uri.QueryData} Instance of this object. + */ +goog.Uri.QueryData.prototype.set = function(key, value) { + this.ensureKeyMapInitialized_(); + this.invalidateCache_(); + + // TODO(chrishenry): This could be better written as + // this.remove(key), this.add(key, value), but that would reorder + // the key (since the key is first removed and then added at the + // end) and we would have to fix unit tests that depend on key + // ordering. + key = this.getKeyName_(key); + if (this.containsKey(key)) { + this.count_ = + goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length; + } + this.keyMap_.set(key, [value]); + this.count_ = goog.asserts.assertNumber(this.count_) + 1; + return this; +}; + + +/** + * Returns the first value associated with the key. If the query data has no + * such key this will return undefined or the optional default. + * @param {string} key The name of the parameter to get the value for. + * @param {*=} opt_default The default value to return if the query data + * has no such key. + * @return {*} The first string value associated with the key, or opt_default + * if there's no value. + */ +goog.Uri.QueryData.prototype.get = function(key, opt_default) { + var values = key ? this.getValues(key) : []; + if (goog.Uri.preserveParameterTypesCompatibilityFlag) { + return values.length > 0 ? values[0] : opt_default; + } else { + return values.length > 0 ? String(values[0]) : opt_default; + } +}; + + +/** + * Sets the values for a key. If the key already exists, this will + * override all of the existing values that correspond to the key. + * @param {string} key The key to set values for. + * @param {!Array} values The values to set. + */ +goog.Uri.QueryData.prototype.setValues = function(key, values) { + this.remove(key); + + if (values.length > 0) { + this.invalidateCache_(); + this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values)); + this.count_ = goog.asserts.assertNumber(this.count_) + values.length; + } +}; + + +/** + * @return {string} Encoded query string. + * @override + */ +goog.Uri.QueryData.prototype.toString = function() { + if (this.encodedQuery_) { + return this.encodedQuery_; + } + + if (!this.keyMap_) { + return ''; + } + + var sb = []; + + // In the past, we use this.getKeys() and this.getVals(), but that + // generates a lot of allocations as compared to simply iterating + // over the keys. + var keys = this.keyMap_.getKeys(); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var encodedKey = goog.string.urlEncode(key); + var val = this.getValues(key); + for (var j = 0; j < val.length; j++) { + var param = encodedKey; + // Ensure that null and undefined are encoded into the url as + // literal strings. + if (val[j] !== '') { + param += '=' + goog.string.urlEncode(val[j]); + } + sb.push(param); + } + } + + return this.encodedQuery_ = sb.join('&'); +}; + + +/** + * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on + * any of the URI components). + * @return {string} Decoded query string. + */ +goog.Uri.QueryData.prototype.toDecodedString = function() { + return goog.Uri.decodeOrEmpty_(this.toString()); +}; + + +/** + * Invalidate the cache. + * @private + */ +goog.Uri.QueryData.prototype.invalidateCache_ = function() { + this.encodedQuery_ = null; +}; + + +/** + * Removes all keys that are not in the provided list. (Modifies this object.) + * @param {Array} keys The desired keys. + * @return {!goog.Uri.QueryData} a reference to this object. + */ +goog.Uri.QueryData.prototype.filterKeys = function(keys) { + this.ensureKeyMapInitialized_(); + this.keyMap_.forEach(function(value, key) { + if (!goog.array.contains(keys, key)) { + this.remove(key); + } + }, this); + return this; +}; + + +/** + * Clone the query data instance. + * @return {!goog.Uri.QueryData} New instance of the QueryData object. + */ +goog.Uri.QueryData.prototype.clone = function() { + var rv = new goog.Uri.QueryData(); + rv.encodedQuery_ = this.encodedQuery_; + if (this.keyMap_) { + rv.keyMap_ = this.keyMap_.clone(); + rv.count_ = this.count_; + } + return rv; +}; + + +/** + * Helper function to get the key name from a JavaScript object. Converts + * the object to a string, and to lower case if necessary. + * @private + * @param {*} arg The object to get a key name from. + * @return {string} valid key name which can be looked up in #keyMap_. + */ +goog.Uri.QueryData.prototype.getKeyName_ = function(arg) { + var keyName = String(arg); + if (this.ignoreCase_) { + keyName = keyName.toLowerCase(); + } + return keyName; +}; + + +/** + * Ignore case in parameter names. + * NOTE: If there are already key/value pairs in the QueryData, and + * ignoreCase_ is set to false, the keys will all be lower-cased. + * @param {boolean} ignoreCase whether this goog.Uri should ignore case. + */ +goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) { + var resetKeys = ignoreCase && !this.ignoreCase_; + if (resetKeys) { + this.ensureKeyMapInitialized_(); + this.invalidateCache_(); + this.keyMap_.forEach(function(value, key) { + var lowerCase = key.toLowerCase(); + if (key != lowerCase) { + this.remove(key); + this.setValues(lowerCase, value); + } + }, this); + } + this.ignoreCase_ = ignoreCase; +}; + + +/** + * Extends a query data object with another query data or map like object. This + * operates 'in-place', it does not create a new QueryData object. + * + * @param {...(?goog.Uri.QueryData|?goog.structs.Map|?Object)} var_args + * The object from which key value pairs will be copied. + * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different + * types of parameters. + */ +goog.Uri.QueryData.prototype.extend = function(var_args) { + for (var i = 0; i < arguments.length; i++) { + var data = arguments[i]; + goog.structs.forEach( + data, function(value, key) { this.add(key, value); }, this); + } +}; diff --git a/assets/viz/2/goog/uri/utils.js b/assets/viz/2/goog/uri/utils.js new file mode 100644 index 0000000..3b8917a --- /dev/null +++ b/assets/viz/2/goog/uri/utils.js @@ -0,0 +1,1103 @@ +// Copyright 2008 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Simple utilities for dealing with URI strings. + * + * This is intended to be a lightweight alternative to constructing goog.Uri + * objects. Whereas goog.Uri adds several kilobytes to the binary regardless + * of how much of its functionality you use, this is designed to be a set of + * mostly-independent utilities so that the compiler includes only what is + * necessary for the task. Estimated savings of porting is 5k pre-gzip and + * 1.5k post-gzip. To ensure the savings remain, future developers should + * avoid adding new functionality to existing functions, but instead create + * new ones and factor out shared code. + * + * Many of these utilities have limited functionality, tailored to common + * cases. The query parameter utilities assume that the parameter keys are + * already encoded, since most keys are compile-time alphanumeric strings. The + * query parameter mutation utilities also do not tolerate fragment identifiers. + * + * By design, these functions can be slower than goog.Uri equivalents. + * Repeated calls to some of functions may be quadratic in behavior for IE, + * although the effect is somewhat limited given the 2kb limit. + * + * One advantage of the limited functionality here is that this approach is + * less sensitive to differences in URI encodings than goog.Uri, since these + * functions operate on strings directly, rather than decoding them and + * then re-encoding. + * + * Uses features of RFC 3986 for parsing/formatting URIs: + * http://www.ietf.org/rfc/rfc3986.txt + * + * @author gboyer@google.com (Garrett Boyer) - The "lightened" design. + * @author msamuel@google.com (Mike Samuel) - Domain knowledge and regexes. + */ + +goog.provide('goog.uri.utils'); +goog.provide('goog.uri.utils.ComponentIndex'); +goog.provide('goog.uri.utils.QueryArray'); +goog.provide('goog.uri.utils.QueryValue'); +goog.provide('goog.uri.utils.StandardQueryParam'); + +goog.require('goog.array'); +goog.require('goog.asserts'); +goog.require('goog.string'); + + +/** + * Character codes inlined to avoid object allocations due to charCode. + * @enum {number} + * @private + */ +goog.uri.utils.CharCode_ = { + AMPERSAND: 38, + EQUAL: 61, + HASH: 35, + QUESTION: 63 +}; + + +/** + * Builds a URI string from already-encoded parts. + * + * No encoding is performed. Any component may be omitted as either null or + * undefined. + * + * @param {?string=} opt_scheme The scheme such as 'http'. + * @param {?string=} opt_userInfo The user name before the '@'. + * @param {?string=} opt_domain The domain such as 'www.google.com', already + * URI-encoded. + * @param {(string|number|null)=} opt_port The port number. + * @param {?string=} opt_path The path, already URI-encoded. If it is not + * empty, it must begin with a slash. + * @param {?string=} opt_queryData The URI-encoded query data. + * @param {?string=} opt_fragment The URI-encoded fragment identifier. + * @return {string} The fully combined URI. + */ +goog.uri.utils.buildFromEncodedParts = function( + opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, + opt_fragment) { + var out = ''; + + if (opt_scheme) { + out += opt_scheme + ':'; + } + + if (opt_domain) { + out += '//'; + + if (opt_userInfo) { + out += opt_userInfo + '@'; + } + + out += opt_domain; + + if (opt_port) { + out += ':' + opt_port; + } + } + + if (opt_path) { + out += opt_path; + } + + if (opt_queryData) { + out += '?' + opt_queryData; + } + + if (opt_fragment) { + out += '#' + opt_fragment; + } + + return out; +}; + + +/** + * A regular expression for breaking a URI into its component parts. + * + * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B + * As the "first-match-wins" algorithm is identical to the "greedy" + * disambiguation method used by POSIX regular expressions, it is natural and + * commonplace to use a regular expression for parsing the potential five + * components of a URI reference. + * + * The following line is the regular expression for breaking-down a + * well-formed URI reference into its components. + * + *
+ * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
+ *  12            3  4          5       6  7        8 9
+ * 
+ * + * The numbers in the second line above are only to assist readability; they + * indicate the reference points for each subexpression (i.e., each paired + * parenthesis). We refer to the value matched for subexpression as $. + * For example, matching the above expression to + *
+ *     http://www.ics.uci.edu/pub/ietf/uri/#Related
+ * 
+ * results in the following subexpression matches: + *
+ *    $1 = http:
+ *    $2 = http
+ *    $3 = //www.ics.uci.edu
+ *    $4 = www.ics.uci.edu
+ *    $5 = /pub/ietf/uri/
+ *    $6 = 
+ *    $7 = 
+ *    $8 = #Related
+ *    $9 = Related
+ * 
+ * where indicates that the component is not present, as is the + * case for the query component in the above example. Therefore, we can + * determine the value of the five components as + *
+ *    scheme    = $2
+ *    authority = $4
+ *    path      = $5
+ *    query     = $7
+ *    fragment  = $9
+ * 
+ * + * The regular expression has been modified slightly to expose the + * userInfo, domain, and port separately from the authority. + * The modified version yields + *
+ *    $1 = http              scheme
+ *    $2 =        userInfo -\
+ *    $3 = www.ics.uci.edu   domain     | authority
+ *    $4 =        port     -/
+ *    $5 = /pub/ietf/uri/    path
+ *    $6 =        query without ?
+ *    $7 = Related           fragment without #
+ * 
+ * @type {!RegExp} + * @private + */ +goog.uri.utils.splitRe_ = new RegExp( + '^' + + '(?:' + + '([^:/?#.]+)' + // scheme - ignore special characters + // used by other URL parts such as :, + // ?, /, #, and . + ':)?' + + '(?://' + + '(?:([^/?#]*)@)?' + // userInfo + '([^/#?]*?)' + // domain + '(?::([0-9]+))?' + // port + '(?=[/#?]|$)' + // authority-terminating character + ')?' + + '([^?#]+)?' + // path + '(?:\\?([^#]*))?' + // query + '(?:#([\\s\\S]*))?' + // fragment + '$'); + + +/** + * The index of each URI component in the return value of goog.uri.utils.split. + * @enum {number} + */ +goog.uri.utils.ComponentIndex = { + SCHEME: 1, + USER_INFO: 2, + DOMAIN: 3, + PORT: 4, + PATH: 5, + QUERY_DATA: 6, + FRAGMENT: 7 +}; + + +/** + * Splits a URI into its component parts. + * + * Each component can be accessed via the component indices; for example: + *
+ * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];
+ * 
+ * + * @param {string} uri The URI string to examine. + * @return {!Array} Each component still URI-encoded. + * Each component that is present will contain the encoded value, whereas + * components that are not present will be undefined or empty, depending + * on the browser's regular expression implementation. Never null, since + * arbitrary strings may still look like path names. + */ +goog.uri.utils.split = function(uri) { + // See @return comment -- never null. + return /** @type {!Array} */ ( + uri.match(goog.uri.utils.splitRe_)); +}; + + +/** + * @param {?string} uri A possibly null string. + * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986 + * reserved characters will not be removed. + * @return {?string} The string URI-decoded, or null if uri is null. + * @private + */ +goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) { + if (!uri) { + return uri; + } + + return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri); +}; + + +/** + * Gets a URI component by index. + * + * It is preferred to use the getPathEncoded() variety of functions ahead, + * since they are more readable. + * + * @param {goog.uri.utils.ComponentIndex} componentIndex The component index. + * @param {string} uri The URI to examine. + * @return {?string} The still-encoded component, or null if the component + * is not present. + * @private + */ +goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) { + // Convert undefined, null, and empty string into null. + return goog.uri.utils.split(uri)[componentIndex] || null; +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The protocol or scheme, or null if none. Does not + * include trailing colons or slashes. + */ +goog.uri.utils.getScheme = function(uri) { + return goog.uri.utils.getComponentByIndex_( + goog.uri.utils.ComponentIndex.SCHEME, uri); +}; + + +/** + * Gets the effective scheme for the URL. If the URL is relative then the + * scheme is derived from the page's location. + * @param {string} uri The URI to examine. + * @return {string} The protocol or scheme, always lower case. + */ +goog.uri.utils.getEffectiveScheme = function(uri) { + var scheme = goog.uri.utils.getScheme(uri); + if (!scheme && goog.global.self && goog.global.self.location) { + var protocol = goog.global.self.location.protocol; + scheme = protocol.substr(0, protocol.length - 1); + } + // NOTE: When called from a web worker in Firefox 3.5, location maybe null. + // All other browsers with web workers support self.location from the worker. + return scheme ? scheme.toLowerCase() : ''; +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The user name still encoded, or null if none. + */ +goog.uri.utils.getUserInfoEncoded = function(uri) { + return goog.uri.utils.getComponentByIndex_( + goog.uri.utils.ComponentIndex.USER_INFO, uri); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The decoded user info, or null if none. + */ +goog.uri.utils.getUserInfo = function(uri) { + return goog.uri.utils.decodeIfPossible_( + goog.uri.utils.getUserInfoEncoded(uri)); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The domain name still encoded, or null if none. + */ +goog.uri.utils.getDomainEncoded = function(uri) { + return goog.uri.utils.getComponentByIndex_( + goog.uri.utils.ComponentIndex.DOMAIN, uri); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The decoded domain, or null if none. + */ +goog.uri.utils.getDomain = function(uri) { + return goog.uri.utils.decodeIfPossible_( + goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?number} The port number, or null if none. + */ +goog.uri.utils.getPort = function(uri) { + // Coerce to a number. If the result of getComponentByIndex_ is null or + // non-numeric, the number coersion yields NaN. This will then return + // null for all non-numeric cases (though also zero, which isn't a relevant + // port number). + return Number( + goog.uri.utils.getComponentByIndex_( + goog.uri.utils.ComponentIndex.PORT, uri)) || + null; +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The path still encoded, or null if none. Includes the + * leading slash, if any. + */ +goog.uri.utils.getPathEncoded = function(uri) { + return goog.uri.utils.getComponentByIndex_( + goog.uri.utils.ComponentIndex.PATH, uri); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The decoded path, or null if none. Includes the leading + * slash, if any. + */ +goog.uri.utils.getPath = function(uri) { + return goog.uri.utils.decodeIfPossible_( + goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The query data still encoded, or null if none. Does not + * include the question mark itself. + */ +goog.uri.utils.getQueryData = function(uri) { + return goog.uri.utils.getComponentByIndex_( + goog.uri.utils.ComponentIndex.QUERY_DATA, uri); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The fragment identifier, or null if none. Does not + * include the hash mark itself. + */ +goog.uri.utils.getFragmentEncoded = function(uri) { + // The hash mark may not appear in any other part of the URL. + var hashIndex = uri.indexOf('#'); + return hashIndex < 0 ? null : uri.substr(hashIndex + 1); +}; + + +/** + * @param {string} uri The URI to examine. + * @param {?string} fragment The encoded fragment identifier, or null if none. + * Does not include the hash mark itself. + * @return {string} The URI with the fragment set. + */ +goog.uri.utils.setFragmentEncoded = function(uri, fragment) { + return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : ''); +}; + + +/** + * @param {string} uri The URI to examine. + * @return {?string} The decoded fragment identifier, or null if none. Does + * not include the hash mark. + */ +goog.uri.utils.getFragment = function(uri) { + return goog.uri.utils.decodeIfPossible_( + goog.uri.utils.getFragmentEncoded(uri)); +}; + + +/** + * Extracts everything up to the port of the URI. + * @param {string} uri The URI string. + * @return {string} Everything up to and including the port. + */ +goog.uri.utils.getHost = function(uri) { + var pieces = goog.uri.utils.split(uri); + return goog.uri.utils.buildFromEncodedParts( + pieces[goog.uri.utils.ComponentIndex.SCHEME], + pieces[goog.uri.utils.ComponentIndex.USER_INFO], + pieces[goog.uri.utils.ComponentIndex.DOMAIN], + pieces[goog.uri.utils.ComponentIndex.PORT]); +}; + + +/** + * Returns the origin for a given URL. + * @param {string} uri The URI string. + * @return {string} Everything up to and including the port. + */ +goog.uri.utils.getOrigin = function(uri) { + var pieces = goog.uri.utils.split(uri); + return goog.uri.utils.buildFromEncodedParts( + pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */, + pieces[goog.uri.utils.ComponentIndex.DOMAIN], + pieces[goog.uri.utils.ComponentIndex.PORT]); +}; + + +/** + * Extracts the path of the URL and everything after. + * @param {string} uri The URI string. + * @return {string} The URI, starting at the path and including the query + * parameters and fragment identifier. + */ +goog.uri.utils.getPathAndAfter = function(uri) { + var pieces = goog.uri.utils.split(uri); + return goog.uri.utils.buildFromEncodedParts( + null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH], + pieces[goog.uri.utils.ComponentIndex.QUERY_DATA], + pieces[goog.uri.utils.ComponentIndex.FRAGMENT]); +}; + + +/** + * Gets the URI with the fragment identifier removed. + * @param {string} uri The URI to examine. + * @return {string} Everything preceding the hash mark. + */ +goog.uri.utils.removeFragment = function(uri) { + // The hash mark may not appear in any other part of the URL. + var hashIndex = uri.indexOf('#'); + return hashIndex < 0 ? uri : uri.substr(0, hashIndex); +}; + + +/** + * Ensures that two URI's have the exact same domain, scheme, and port. + * + * Unlike the version in goog.Uri, this checks protocol, and therefore is + * suitable for checking against the browser's same-origin policy. + * + * @param {string} uri1 The first URI. + * @param {string} uri2 The second URI. + * @return {boolean} Whether they have the same scheme, domain and port. + */ +goog.uri.utils.haveSameDomain = function(uri1, uri2) { + var pieces1 = goog.uri.utils.split(uri1); + var pieces2 = goog.uri.utils.split(uri2); + return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == + pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && + pieces1[goog.uri.utils.ComponentIndex.SCHEME] == + pieces2[goog.uri.utils.ComponentIndex.SCHEME] && + pieces1[goog.uri.utils.ComponentIndex.PORT] == + pieces2[goog.uri.utils.ComponentIndex.PORT]; +}; + + +/** + * Asserts that there are no fragment or query identifiers, only in uncompiled + * mode. + * @param {string} uri The URI to examine. + * @private + */ +goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) { + goog.asserts.assert( + uri.indexOf('#') < 0 && uri.indexOf('?') < 0, + 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]', + uri); +}; + + +/** + * Supported query parameter values by the parameter serializing utilities. + * + * If a value is null or undefined, the key-value pair is skipped, as an easy + * way to omit parameters conditionally. Non-array parameters are converted + * to a string and URI encoded. Array values are expanded into multiple + * &key=value pairs, with each element stringized and URI-encoded. + * + * @typedef {*} + */ +goog.uri.utils.QueryValue; + + +/** + * An array representing a set of query parameters with alternating keys + * and values. + * + * Keys are assumed to be URI encoded already and live at even indices. See + * goog.uri.utils.QueryValue for details on how parameter values are encoded. + * + * Example: + *
+ * var data = [
+ *   // Simple param: ?name=BobBarker
+ *   'name', 'BobBarker',
+ *   // Conditional param -- may be omitted entirely.
+ *   'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,
+ *   // Multi-valued param: &house=LosAngeles&house=NewYork&house=null
+ *   'house', ['LosAngeles', 'NewYork', null]
+ * ];
+ * 
+ * + * @typedef {!Array} + */ +goog.uri.utils.QueryArray; + + +/** + * Parses encoded query parameters and calls callback function for every + * parameter found in the string. + * + * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an + * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means + * that “…&=&…” and “…&&…” will result in an empty key and value. + * + * @param {string} encodedQuery Encoded query string excluding question mark at + * the beginning. + * @param {function(string, string)} callback Function called for every + * parameter found in query string. The first argument (name) will not be + * urldecoded (so the function is consistent with buildQueryData), but the + * second will. If the parameter has no value (i.e. “=” was not present) + * the second argument (value) will be an empty string. + */ +goog.uri.utils.parseQueryData = function(encodedQuery, callback) { + if (!encodedQuery) { + return; + } + var pairs = encodedQuery.split('&'); + for (var i = 0; i < pairs.length; i++) { + var indexOfEquals = pairs[i].indexOf('='); + var name = null; + var value = null; + if (indexOfEquals >= 0) { + name = pairs[i].substring(0, indexOfEquals); + value = pairs[i].substring(indexOfEquals + 1); + } else { + name = pairs[i]; + } + callback(name, value ? goog.string.urlDecode(value) : ''); + } +}; + + +/** + * Split the URI into 3 parts where the [1] is the queryData without a leading + * '?'. For example, the URI http://foo.com/bar?a=b#abc returns + * ['http://foo.com/bar','a=b','#abc']. + * @param {string} uri The URI to parse. + * @return {!Array} An array representation of uri of length 3 where the + * middle value is the queryData without a leading '?'. + * @private + */ +goog.uri.utils.splitQueryData_ = function(uri) { + // Find the query data and and hash. + var hashIndex = uri.indexOf('#'); + if (hashIndex < 0) { + hashIndex = uri.length; + } + var questionIndex = uri.indexOf('?'); + var queryData; + if (questionIndex < 0 || questionIndex > hashIndex) { + questionIndex = hashIndex; + queryData = ''; + } else { + queryData = uri.substring(questionIndex + 1, hashIndex); + } + return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)]; +}; + + +/** + * Join an array created by splitQueryData_ back into a URI. + * @param {!Array} parts A URI in the form generated by splitQueryData_. + * @return {string} The joined URI. + * @private + */ +goog.uri.utils.joinQueryData_ = function(parts) { + return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2]; +}; + + +/** + * @param {string} queryData + * @param {string} newData + * @return {string} + * @private + */ +goog.uri.utils.appendQueryData_ = function(queryData, newData) { + if (!newData) { + return queryData; + } + return queryData ? queryData + '&' + newData : newData; +}; + + +/** + * @param {string} uri + * @param {string} queryData + * @return {string} + * @private + */ +goog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) { + if (!queryData) { + return uri; + } + var parts = goog.uri.utils.splitQueryData_(uri); + parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData); + return goog.uri.utils.joinQueryData_(parts); +}; + + +/** + * Appends key=value pairs to an array, supporting multi-valued objects. + * @param {*} key The key prefix. + * @param {goog.uri.utils.QueryValue} value The value to serialize. + * @param {!Array} pairs The array to which the 'key=value' strings + * should be appended. + * @private + */ +goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) { + goog.asserts.assertString(key); + if (goog.isArray(value)) { + // Convince the compiler it's an array. + goog.asserts.assertArray(value); + for (var j = 0; j < value.length; j++) { + // Convert to string explicitly, to short circuit the null and array + // logic in this function -- this ensures that null and undefined get + // written as literal 'null' and 'undefined', and arrays don't get + // expanded out but instead encoded in the default way. + goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs); + } + } else if (value != null) { + // Skip a top-level null or undefined entirely. + pairs.push( + key + + // Check for empty string. Zero gets encoded into the url as literal + // strings. For empty string, skip the equal sign, to be consistent + // with UriBuilder.java. + (value === '' ? '' : '=' + goog.string.urlEncode(value))); + } +}; + + +/** + * Builds a query data string from a sequence of alternating keys and values. + * Currently generates "&key&" for empty args. + * + * @param {!IArrayLike} keysAndValues + * Alternating keys and values. See the QueryArray typedef. + * @param {number=} opt_startIndex A start offset into the arary, defaults to 0. + * @return {string} The encoded query string, in the form 'a=1&b=2'. + */ +goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) { + goog.asserts.assert( + Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0, + 'goog.uri.utils: Key/value lists must be even in length.'); + + var params = []; + for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) { + var key = /** @type {string} */ (keysAndValues[i]); + goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params); + } + return params.join('&'); +}; + + +/** + * Builds a query data string from a map. + * Currently generates "&key&" for empty args. + * + * @param {!Object} map An object where keys + * are URI-encoded parameter keys, and the values are arbitrary types + * or arrays. Keys with a null value are dropped. + * @return {string} The encoded query string, in the form 'a=1&b=2'. + */ +goog.uri.utils.buildQueryDataFromMap = function(map) { + var params = []; + for (var key in map) { + goog.uri.utils.appendKeyValuePairs_(key, map[key], params); + } + return params.join('&'); +}; + + +/** + * Appends URI parameters to an existing URI. + * + * The variable arguments may contain alternating keys and values. Keys are + * assumed to be already URI encoded. The values should not be URI-encoded, + * and will instead be encoded by this function. + *
+ * appendParams('http://www.foo.com?existing=true',
+ *     'key1', 'value1',
+ *     'key2', 'value?willBeEncoded',
+ *     'key3', ['valueA', 'valueB', 'valueC'],
+ *     'key4', null);
+ * result: 'http://www.foo.com?existing=true&' +
+ *     'key1=value1&' +
+ *     'key2=value%3FwillBeEncoded&' +
+ *     'key3=valueA&key3=valueB&key3=valueC'
+ * 
+ * + * A single call to this function will not exhibit quadratic behavior in IE, + * whereas multiple repeated calls may, although the effect is limited by + * fact that URL's generally can't exceed 2kb. + * + * @param {string} uri The original URI, which may already have query data. + * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)} + * var_args + * An array or argument list conforming to goog.uri.utils.QueryArray. + * @return {string} The URI with all query parameters added. + */ +goog.uri.utils.appendParams = function(uri, var_args) { + var queryData = arguments.length == 2 ? + goog.uri.utils.buildQueryData(arguments[1], 0) : + goog.uri.utils.buildQueryData(arguments, 1); + return goog.uri.utils.appendQueryDataToUri_(uri, queryData); +}; + + +/** + * Appends query parameters from a map. + * + * @param {string} uri The original URI, which may already have query data. + * @param {!Object} map An object where keys are + * URI-encoded parameter keys, and the values are arbitrary types or arrays. + * Keys with a null value are dropped. + * @return {string} The new parameters. + */ +goog.uri.utils.appendParamsFromMap = function(uri, map) { + var queryData = goog.uri.utils.buildQueryDataFromMap(map); + return goog.uri.utils.appendQueryDataToUri_(uri, queryData); +}; + + +/** + * Appends a single URI parameter. + * + * Repeated calls to this can exhibit quadratic behavior in IE6 due to the + * way string append works, though it should be limited given the 2kb limit. + * + * @param {string} uri The original URI, which may already have query data. + * @param {string} key The key, which must already be URI encoded. + * @param {*=} opt_value The value, which will be stringized and encoded + * (assumed not already to be encoded). If omitted, undefined, or null, the + * key will be added as a valueless parameter. + * @return {string} The URI with the query parameter added. + */ +goog.uri.utils.appendParam = function(uri, key, opt_value) { + var value = goog.isDefAndNotNull(opt_value) ? + '=' + goog.string.urlEncode(opt_value) : + ''; + return goog.uri.utils.appendQueryDataToUri_(uri, key + value); +}; + + +/** + * Finds the next instance of a query parameter with the specified name. + * + * Does not instantiate any objects. + * + * @param {string} uri The URI to search. May contain a fragment identifier + * if opt_hashIndex is specified. + * @param {number} startIndex The index to begin searching for the key at. A + * match may be found even if this is one character after the ampersand. + * @param {string} keyEncoded The URI-encoded key. + * @param {number} hashOrEndIndex Index to stop looking at. If a hash + * mark is present, it should be its index, otherwise it should be the + * length of the string. + * @return {number} The position of the first character in the key's name, + * immediately after either a question mark or a dot. + * @private + */ +goog.uri.utils.findParam_ = function( + uri, startIndex, keyEncoded, hashOrEndIndex) { + var index = startIndex; + var keyLength = keyEncoded.length; + + // Search for the key itself and post-filter for surronuding punctuation, + // rather than expensively building a regexp. + while ((index = uri.indexOf(keyEncoded, index)) >= 0 && + index < hashOrEndIndex) { + var precedingChar = uri.charCodeAt(index - 1); + // Ensure that the preceding character is '&' or '?'. + if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND || + precedingChar == goog.uri.utils.CharCode_.QUESTION) { + // Ensure the following character is '&', '=', '#', or NaN + // (end of string). + var followingChar = uri.charCodeAt(index + keyLength); + if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL || + followingChar == goog.uri.utils.CharCode_.AMPERSAND || + followingChar == goog.uri.utils.CharCode_.HASH) { + return index; + } + } + index += keyLength + 1; + } + + return -1; +}; + + +/** + * Regular expression for finding a hash mark or end of string. + * @type {RegExp} + * @private + */ +goog.uri.utils.hashOrEndRe_ = /#|$/; + + +/** + * Determines if the URI contains a specific key. + * + * Performs no object instantiations. + * + * @param {string} uri The URI to process. May contain a fragment + * identifier. + * @param {string} keyEncoded The URI-encoded key. Case-sensitive. + * @return {boolean} Whether the key is present. + */ +goog.uri.utils.hasParam = function(uri, keyEncoded) { + return goog.uri.utils.findParam_( + uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0; +}; + + +/** + * Gets the first value of a query parameter. + * @param {string} uri The URI to process. May contain a fragment. + * @param {string} keyEncoded The URI-encoded key. Case-sensitive. + * @return {?string} The first value of the parameter (URI-decoded), or null + * if the parameter is not found. + */ +goog.uri.utils.getParamValue = function(uri, keyEncoded) { + var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); + var foundIndex = + goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex); + + if (foundIndex < 0) { + return null; + } else { + var endPosition = uri.indexOf('&', foundIndex); + if (endPosition < 0 || endPosition > hashOrEndIndex) { + endPosition = hashOrEndIndex; + } + // Progress forth to the end of the "key=" or "key&" substring. + foundIndex += keyEncoded.length + 1; + // Use substr, because it (unlike substring) will return empty string + // if foundIndex > endPosition. + return goog.string.urlDecode( + uri.substr(foundIndex, endPosition - foundIndex)); + } +}; + + +/** + * Gets all values of a query parameter. + * @param {string} uri The URI to process. May contain a fragment. + * @param {string} keyEncoded The URI-encoded key. Case-sensitive. + * @return {!Array} All URI-decoded values with the given key. + * If the key is not found, this will have length 0, but never be null. + */ +goog.uri.utils.getParamValues = function(uri, keyEncoded) { + var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); + var position = 0; + var foundIndex; + var result = []; + + while ((foundIndex = goog.uri.utils.findParam_( + uri, position, keyEncoded, hashOrEndIndex)) >= 0) { + // Find where this parameter ends, either the '&' or the end of the + // query parameters. + position = uri.indexOf('&', foundIndex); + if (position < 0 || position > hashOrEndIndex) { + position = hashOrEndIndex; + } + + // Progress forth to the end of the "key=" or "key&" substring. + foundIndex += keyEncoded.length + 1; + // Use substr, because it (unlike substring) will return empty string + // if foundIndex > position. + result.push( + goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex))); + } + + return result; +}; + + +/** + * Regexp to find trailing question marks and ampersands. + * @type {RegExp} + * @private + */ +goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/; + + +/** + * Removes all instances of a query parameter. + * @param {string} uri The URI to process. Must not contain a fragment. + * @param {string} keyEncoded The URI-encoded key. + * @return {string} The URI with all instances of the parameter removed. + */ +goog.uri.utils.removeParam = function(uri, keyEncoded) { + var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); + var position = 0; + var foundIndex; + var buffer = []; + + // Look for a query parameter. + while ((foundIndex = goog.uri.utils.findParam_( + uri, position, keyEncoded, hashOrEndIndex)) >= 0) { + // Get the portion of the query string up to, but not including, the ? + // or & starting the parameter. + buffer.push(uri.substring(position, foundIndex)); + // Progress to immediately after the '&'. If not found, go to the end. + // Avoid including the hash mark. + position = Math.min( + (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex); + } + + // Append everything that is remaining. + buffer.push(uri.substr(position)); + + // Join the buffer, and remove trailing punctuation that remains. + return buffer.join('').replace( + goog.uri.utils.trailingQueryPunctuationRe_, '$1'); +}; + + +/** + * Replaces all existing definitions of a parameter with a single definition. + * + * Repeated calls to this can exhibit quadratic behavior due to the need to + * find existing instances and reconstruct the string, though it should be + * limited given the 2kb limit. Consider using appendParams or setParamsFromMap + * to update multiple parameters in bulk. + * + * @param {string} uri The original URI, which may already have query data. + * @param {string} keyEncoded The key, which must already be URI encoded. + * @param {*} value The value, which will be stringized and encoded (assumed + * not already to be encoded). + * @return {string} The URI with the query parameter added. + */ +goog.uri.utils.setParam = function(uri, keyEncoded, value) { + return goog.uri.utils.appendParam( + goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value); +}; + + +/** + * Effeciently set or remove multiple query parameters in a URI. Order of + * unchanged parameters will not be modified, all updated parameters will be + * appended to the end of the query. Params with values of null or undefined are + * removed. + * + * @param {string} uri The URI to process. + * @param {!Object} params A list of + * parameters to update. If null or undefined, the param will be removed. + * @return {string} An updated URI where the query data has been updated with + * the params. + */ +goog.uri.utils.setParamsFromMap = function(uri, params) { + var parts = goog.uri.utils.splitQueryData_(uri); + var queryData = parts[1]; + var buffer = []; + if (queryData) { + goog.array.forEach(queryData.split('&'), function(pair) { + var indexOfEquals = pair.indexOf('='); + var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair; + if (!params.hasOwnProperty(name)) { + buffer.push(pair); + } + }); + } + parts[1] = goog.uri.utils.appendQueryData_( + buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params)); + return goog.uri.utils.joinQueryData_(parts); +}; + + +/** + * Generates a URI path using a given URI and a path with checks to + * prevent consecutive "//". The baseUri passed in must not contain + * query or fragment identifiers. The path to append may not contain query or + * fragment identifiers. + * + * @param {string} baseUri URI to use as the base. + * @param {string} path Path to append. + * @return {string} Updated URI. + */ +goog.uri.utils.appendPath = function(baseUri, path) { + goog.uri.utils.assertNoFragmentsOrQueries_(baseUri); + + // Remove any trailing '/' + if (goog.string.endsWith(baseUri, '/')) { + baseUri = baseUri.substr(0, baseUri.length - 1); + } + // Remove any leading '/' + if (goog.string.startsWith(path, '/')) { + path = path.substr(1); + } + return goog.string.buildString(baseUri, '/', path); +}; + + +/** + * Replaces the path. + * @param {string} uri URI to use as the base. + * @param {string} path New path. + * @return {string} Updated URI. + */ +goog.uri.utils.setPath = function(uri, path) { + // Add any missing '/'. + if (!goog.string.startsWith(path, '/')) { + path = '/' + path; + } + var parts = goog.uri.utils.split(uri); + return goog.uri.utils.buildFromEncodedParts( + parts[goog.uri.utils.ComponentIndex.SCHEME], + parts[goog.uri.utils.ComponentIndex.USER_INFO], + parts[goog.uri.utils.ComponentIndex.DOMAIN], + parts[goog.uri.utils.ComponentIndex.PORT], path, + parts[goog.uri.utils.ComponentIndex.QUERY_DATA], + parts[goog.uri.utils.ComponentIndex.FRAGMENT]); +}; + + +/** + * Standard supported query parameters. + * @enum {string} + */ +goog.uri.utils.StandardQueryParam = { + + /** Unused parameter for unique-ifying. */ + RANDOM: 'zx' +}; + + +/** + * Sets the zx parameter of a URI to a random value. + * @param {string} uri Any URI. + * @return {string} That URI with the "zx" parameter added or replaced to + * contain a random string. + */ +goog.uri.utils.makeUnique = function(uri) { + return goog.uri.utils.setParam( + uri, goog.uri.utils.StandardQueryParam.RANDOM, + goog.string.getRandomString()); +}; -- cgit v1.2.3