Moved web root into root of project; this makes deployment easier.

Also deleted 'docs', which is now redundant.
This commit is contained in:
Simon Brooke 2020-02-27 14:18:29 +00:00
parent a5204c66b9
commit 743d8a1740
No known key found for this signature in database
GPG key ID: A7A4F18D1D4DF987
1592 changed files with 53626 additions and 139250 deletions

View file

@ -0,0 +1,130 @@
// Copyright 2007 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 Error codes shared between goog.net.IframeIo and
* goog.net.XhrIo.
*/
goog.provide('goog.net.ErrorCode');
/**
* Error codes
* @enum {number}
*/
goog.net.ErrorCode = {
/**
* There is no error condition.
*/
NO_ERROR: 0,
/**
* The most common error from iframeio, unfortunately, is that the browser
* responded with an error page that is classed as a different domain. The
* situations, are when a browser error page is shown -- 404, access denied,
* DNS failure, connection reset etc.)
*
*/
ACCESS_DENIED: 1,
/**
* Currently the only case where file not found will be caused is when the
* code is running on the local file system and a non-IE browser makes a
* request to a file that doesn't exist.
*/
FILE_NOT_FOUND: 2,
/**
* If Firefox shows a browser error page, such as a connection reset by
* server or access denied, then it will fail silently without the error or
* load handlers firing.
*/
FF_SILENT_ERROR: 3,
/**
* Custom error provided by the client through the error check hook.
*/
CUSTOM_ERROR: 4,
/**
* Exception was thrown while processing the request.
*/
EXCEPTION: 5,
/**
* The Http response returned a non-successful http status code.
*/
HTTP_ERROR: 6,
/**
* The request was aborted.
*/
ABORT: 7,
/**
* The request timed out.
*/
TIMEOUT: 8,
/**
* The resource is not available offline.
*/
OFFLINE: 9
};
/**
* Returns a friendly error message for an error code. These messages are for
* debugging and are not localized.
* @param {goog.net.ErrorCode} errorCode An error code.
* @return {string} A message for debugging.
*/
goog.net.ErrorCode.getDebugMessage = function(errorCode) {
switch (errorCode) {
case goog.net.ErrorCode.NO_ERROR:
return 'No Error';
case goog.net.ErrorCode.ACCESS_DENIED:
return 'Access denied to content document';
case goog.net.ErrorCode.FILE_NOT_FOUND:
return 'File not found';
case goog.net.ErrorCode.FF_SILENT_ERROR:
return 'Firefox silently errored';
case goog.net.ErrorCode.CUSTOM_ERROR:
return 'Application custom error';
case goog.net.ErrorCode.EXCEPTION:
return 'An exception occurred';
case goog.net.ErrorCode.HTTP_ERROR:
return 'Http response at 400 or 500 level';
case goog.net.ErrorCode.ABORT:
return 'Request was aborted';
case goog.net.ErrorCode.TIMEOUT:
return 'Request timed out';
case goog.net.ErrorCode.OFFLINE:
return 'The resource is not available offline';
default:
return 'Unrecognized error code';
}
};

View file

@ -0,0 +1,42 @@
// 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 Common events for the network classes.
*/
goog.provide('goog.net.EventType');
/**
* Event names for network events
* @enum {string}
*/
goog.net.EventType = {
COMPLETE: 'complete',
SUCCESS: 'success',
ERROR: 'error',
ABORT: 'abort',
READY: 'ready',
READY_STATE_CHANGE: 'readystatechange',
TIMEOUT: 'timeout',
INCREMENTAL_DATA: 'incrementaldata',
PROGRESS: 'progress',
// DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by
// goog.net.XhrIo to allow binding listeners specific to each type of
// progress.
DOWNLOAD_PROGRESS: 'downloadprogress',
UPLOAD_PROGRESS: 'uploadprogress'
};

View file

@ -0,0 +1,116 @@
// Copyright 2011 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 Constants for HTTP status codes.
*/
goog.provide('goog.net.HttpStatus');
/**
* HTTP Status Codes defined in RFC 2616 and RFC 6585.
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
* @see http://tools.ietf.org/html/rfc6585
* @enum {number}
*/
goog.net.HttpStatus = {
// Informational 1xx
CONTINUE: 100,
SWITCHING_PROTOCOLS: 101,
// Successful 2xx
OK: 200,
CREATED: 201,
ACCEPTED: 202,
NON_AUTHORITATIVE_INFORMATION: 203,
NO_CONTENT: 204,
RESET_CONTENT: 205,
PARTIAL_CONTENT: 206,
// Redirection 3xx
MULTIPLE_CHOICES: 300,
MOVED_PERMANENTLY: 301,
FOUND: 302,
SEE_OTHER: 303,
NOT_MODIFIED: 304,
USE_PROXY: 305,
TEMPORARY_REDIRECT: 307,
// Client Error 4xx
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
PAYMENT_REQUIRED: 402,
FORBIDDEN: 403,
NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
NOT_ACCEPTABLE: 406,
PROXY_AUTHENTICATION_REQUIRED: 407,
REQUEST_TIMEOUT: 408,
CONFLICT: 409,
GONE: 410,
LENGTH_REQUIRED: 411,
PRECONDITION_FAILED: 412,
REQUEST_ENTITY_TOO_LARGE: 413,
REQUEST_URI_TOO_LONG: 414,
UNSUPPORTED_MEDIA_TYPE: 415,
REQUEST_RANGE_NOT_SATISFIABLE: 416,
EXPECTATION_FAILED: 417,
PRECONDITION_REQUIRED: 428,
TOO_MANY_REQUESTS: 429,
REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
// Server Error 5xx
INTERNAL_SERVER_ERROR: 500,
NOT_IMPLEMENTED: 501,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504,
HTTP_VERSION_NOT_SUPPORTED: 505,
NETWORK_AUTHENTICATION_REQUIRED: 511,
/*
* IE returns this code for 204 due to its use of URLMon, which returns this
* code for 'Operation Aborted'. The status text is 'Unknown', the response
* headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.
*/
QUIRK_IE_NO_CONTENT: 1223
};
/**
* Returns whether the given status should be considered successful.
*
* Successful codes are OK (200), CREATED (201), ACCEPTED (202),
* NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),
* and IE's no content code (1223).
*
* @param {number} status The status code to test.
* @return {boolean} Whether the status code should be considered successful.
*/
goog.net.HttpStatus.isSuccess = function(status) {
switch (status) {
case goog.net.HttpStatus.OK:
case goog.net.HttpStatus.CREATED:
case goog.net.HttpStatus.ACCEPTED:
case goog.net.HttpStatus.NO_CONTENT:
case goog.net.HttpStatus.PARTIAL_CONTENT:
case goog.net.HttpStatus.NOT_MODIFIED:
case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:
return true;
default:
return false;
}
};

View file

@ -0,0 +1,393 @@
// Copyright 2011 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 A utility to load JavaScript files via DOM script tags.
* Refactored from goog.net.Jsonp. Works cross-domain.
*
*/
goog.provide('goog.net.jsloader');
goog.provide('goog.net.jsloader.Error');
goog.provide('goog.net.jsloader.ErrorCode');
goog.provide('goog.net.jsloader.Options');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.debug.Error');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.safe');
goog.require('goog.html.TrustedResourceUrl');
goog.require('goog.object');
/**
* The name of the property of goog.global under which the JavaScript
* verification object is stored by the loaded script.
* @private {string}
*/
goog.net.jsloader.GLOBAL_VERIFY_OBJS_ = 'closure_verification';
/**
* The default length of time, in milliseconds, we are prepared to wait for a
* load request to complete.
* @type {number}
*/
goog.net.jsloader.DEFAULT_TIMEOUT = 5000;
/**
* Optional parameters for goog.net.jsloader.send.
* timeout: The length of time, in milliseconds, we are prepared to wait
* for a load request to complete, or 0 or negative for no timeout. Default
* is 5 seconds.
* document: The HTML document under which to load the JavaScript. Default is
* the current document.
* cleanupWhenDone: If true clean up the script tag after script completes to
* load. This is important if you just want to read data from the JavaScript
* and then throw it away. Default is false.
* attributes: Additional attributes to set on the script tag.
*
* @typedef {{
* timeout: (number|undefined),
* document: (HTMLDocument|undefined),
* cleanupWhenDone: (boolean|undefined),
* attributes: (!Object<string, string>|undefined)
* }}
*/
goog.net.jsloader.Options;
/**
* Scripts (URIs) waiting to be loaded.
* @private {!Array<!goog.html.TrustedResourceUrl>}
*/
goog.net.jsloader.scriptsToLoad_ = [];
/**
* The deferred result of loading the URIs in scriptsToLoad_.
* We need to return this to a caller that wants to load URIs while
* a deferred is already working on them.
* @private {!goog.async.Deferred<null>}
*/
goog.net.jsloader.scriptLoadingDeferred_;
/**
* Loads and evaluates the JavaScript files at the specified URIs, guaranteeing
* the order of script loads.
*
* Because we have to load the scripts in serial (load script 1, exec script 1,
* load script 2, exec script 2, and so on), this will be slower than doing
* the network fetches in parallel.
*
* If you need to load a large number of scripts but dependency order doesn't
* matter, you should just call goog.net.jsloader.safeLoad N times.
*
* If you need to load a large number of scripts on the same domain,
* you may want to use goog.module.ModuleLoader.
*
* @param {Array<!goog.html.TrustedResourceUrl>} trustedUris The URIs to load.
* @param {goog.net.jsloader.Options=} opt_options Optional parameters. See
* goog.net.jsloader.options documentation for details.
* @return {!goog.async.Deferred} The deferred result, that may be used to add
* callbacks
*/
goog.net.jsloader.safeLoadMany = function(trustedUris, opt_options) {
// Loading the scripts in serial introduces asynchronosity into the flow.
// Therefore, there are race conditions where client A can kick off the load
// sequence for client B, even though client A's scripts haven't all been
// loaded yet.
//
// To work around this issue, all module loads share a queue.
if (!trustedUris.length) {
return goog.async.Deferred.succeed(null);
}
var isAnotherModuleLoading = goog.net.jsloader.scriptsToLoad_.length;
goog.array.extend(goog.net.jsloader.scriptsToLoad_, trustedUris);
if (isAnotherModuleLoading) {
// jsloader is still loading some other scripts.
// In order to prevent the race condition noted above, we just add
// these URIs to the end of the scripts' queue and return the deferred
// result of the ongoing script load, so the caller knows when they
// finish loading.
return goog.net.jsloader.scriptLoadingDeferred_;
}
trustedUris = goog.net.jsloader.scriptsToLoad_;
var popAndLoadNextScript = function() {
var trustedUri = trustedUris.shift();
var deferred = goog.net.jsloader.safeLoad(trustedUri, opt_options);
if (trustedUris.length) {
deferred.addBoth(popAndLoadNextScript);
}
return deferred;
};
goog.net.jsloader.scriptLoadingDeferred_ = popAndLoadNextScript();
return goog.net.jsloader.scriptLoadingDeferred_;
};
/**
* Loads and evaluates a JavaScript file.
* When the script loads, a user callback is called.
* It is the client's responsibility to verify that the script ran successfully.
*
* @param {!goog.html.TrustedResourceUrl} trustedUri The URI of the JavaScript.
* @param {goog.net.jsloader.Options=} opt_options Optional parameters. See
* goog.net.jsloader.Options documentation for details.
* @return {!goog.async.Deferred} The deferred result, that may be used to add
* callbacks and/or cancel the transmission.
* The error callback will be called with a single goog.net.jsloader.Error
* parameter.
*/
goog.net.jsloader.safeLoad = function(trustedUri, opt_options) {
var options = opt_options || {};
var doc = options.document || document;
var uri = goog.html.TrustedResourceUrl.unwrap(trustedUri);
var script = goog.dom.createElement(goog.dom.TagName.SCRIPT);
var request = {script_: script, timeout_: undefined};
var deferred = new goog.async.Deferred(goog.net.jsloader.cancel_, request);
// Set a timeout.
var timeout = null;
var timeoutDuration = goog.isDefAndNotNull(options.timeout) ?
options.timeout :
goog.net.jsloader.DEFAULT_TIMEOUT;
if (timeoutDuration > 0) {
timeout = window.setTimeout(function() {
goog.net.jsloader.cleanup_(script, true);
deferred.errback(
new goog.net.jsloader.Error(
goog.net.jsloader.ErrorCode.TIMEOUT,
'Timeout reached for loading script ' + uri));
}, timeoutDuration);
request.timeout_ = timeout;
}
// Hang the user callback to be called when the script completes to load.
// NOTE(user): This callback will be called in IE even upon error. In any
// case it is the client's responsibility to verify that the script ran
// successfully.
script.onload = script.onreadystatechange = function() {
if (!script.readyState || script.readyState == 'loaded' ||
script.readyState == 'complete') {
var removeScriptNode = options.cleanupWhenDone || false;
goog.net.jsloader.cleanup_(script, removeScriptNode, timeout);
deferred.callback(null);
}
};
// Add an error callback.
// NOTE(user): Not supported in IE.
script.onerror = function() {
goog.net.jsloader.cleanup_(script, true, timeout);
deferred.errback(
new goog.net.jsloader.Error(
goog.net.jsloader.ErrorCode.LOAD_ERROR,
'Error while loading script ' + uri));
};
var properties = options.attributes || {};
goog.object.extend(
properties, {'type': 'text/javascript', 'charset': 'UTF-8'});
goog.dom.setProperties(script, properties);
// NOTE(user): Safari never loads the script if we don't set the src
// attribute before appending.
goog.dom.safe.setScriptSrc(script, trustedUri);
var scriptParent = goog.net.jsloader.getScriptParentElement_(doc);
scriptParent.appendChild(script);
return deferred;
};
/**
* Loads a JavaScript file and verifies it was evaluated successfully, using a
* verification object.
* The verification object is set by the loaded JavaScript at the end of the
* script.
* We verify this object was set and return its value in the success callback.
* If the object is not defined we trigger an error callback.
*
* @param {!goog.html.TrustedResourceUrl} trustedUri The URI of the JavaScript.
* @param {string} verificationObjName The name of the verification object that
* the loaded script should set.
* @param {goog.net.jsloader.Options} options Optional parameters. See
* goog.net.jsloader.Options documentation for details.
* @return {!goog.async.Deferred} The deferred result, that may be used to add
* callbacks and/or cancel the transmission.
* The success callback will be called with a single parameter containing
* the value of the verification object.
* The error callback will be called with a single goog.net.jsloader.Error
* parameter.
*/
goog.net.jsloader.safeLoadAndVerify = function(
trustedUri, verificationObjName, options) {
// Define the global objects variable.
if (!goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_]) {
goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_] = {};
}
var verifyObjs = goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_];
var uri = goog.html.TrustedResourceUrl.unwrap(trustedUri);
// Verify that the expected object does not exist yet.
if (goog.isDef(verifyObjs[verificationObjName])) {
// TODO(user): Error or reset variable?
return goog.async.Deferred.fail(
new goog.net.jsloader.Error(
goog.net.jsloader.ErrorCode.VERIFY_OBJECT_ALREADY_EXISTS,
'Verification object ' + verificationObjName +
' already defined.'));
}
// Send request to load the JavaScript.
var sendDeferred = goog.net.jsloader.safeLoad(trustedUri, options);
// Create a deferred object wrapping the send result.
var deferred =
new goog.async.Deferred(goog.bind(sendDeferred.cancel, sendDeferred));
// Call user back with object that was set by the script.
sendDeferred.addCallback(function() {
var result = verifyObjs[verificationObjName];
if (goog.isDef(result)) {
deferred.callback(result);
delete verifyObjs[verificationObjName];
} else {
// Error: script was not loaded properly.
deferred.errback(
new goog.net.jsloader.Error(
goog.net.jsloader.ErrorCode.VERIFY_ERROR, 'Script ' + uri +
' loaded, but verification object ' + verificationObjName +
' was not defined.'));
}
});
// Pass error to new deferred object.
sendDeferred.addErrback(function(error) {
if (goog.isDef(verifyObjs[verificationObjName])) {
delete verifyObjs[verificationObjName];
}
deferred.errback(error);
});
return deferred;
};
/**
* Gets the DOM element under which we should add new script elements.
* How? Take the first head element, and if not found take doc.documentElement,
* which always exists.
*
* @param {!HTMLDocument} doc The relevant document.
* @return {!Element} The script parent element.
* @private
*/
goog.net.jsloader.getScriptParentElement_ = function(doc) {
var headElements = goog.dom.getElementsByTagName(goog.dom.TagName.HEAD, doc);
if (!headElements || goog.array.isEmpty(headElements)) {
return doc.documentElement;
} else {
return headElements[0];
}
};
/**
* Cancels a given request.
* @this {{script_: Element, timeout_: number}} The request context.
* @private
*/
goog.net.jsloader.cancel_ = function() {
var request = this;
if (request && request.script_) {
var scriptNode = request.script_;
if (scriptNode && scriptNode.tagName == goog.dom.TagName.SCRIPT) {
goog.net.jsloader.cleanup_(scriptNode, true, request.timeout_);
}
}
};
/**
* Removes the script node and the timeout.
*
* @param {Node} scriptNode The node to be cleaned up.
* @param {boolean} removeScriptNode If true completely remove the script node.
* @param {?number=} opt_timeout The timeout handler to cleanup.
* @private
*/
goog.net.jsloader.cleanup_ = function(
scriptNode, removeScriptNode, opt_timeout) {
if (goog.isDefAndNotNull(opt_timeout)) {
goog.global.clearTimeout(opt_timeout);
}
scriptNode.onload = goog.nullFunction;
scriptNode.onerror = goog.nullFunction;
scriptNode.onreadystatechange = goog.nullFunction;
// Do this after a delay (removing the script node of a running script can
// confuse older IEs).
if (removeScriptNode) {
window.setTimeout(function() { goog.dom.removeNode(scriptNode); }, 0);
}
};
/**
* Possible error codes for jsloader.
* @enum {number}
*/
goog.net.jsloader.ErrorCode = {
LOAD_ERROR: 0,
TIMEOUT: 1,
VERIFY_ERROR: 2,
VERIFY_OBJECT_ALREADY_EXISTS: 3
};
/**
* A jsloader error.
*
* @param {goog.net.jsloader.ErrorCode} code The error code.
* @param {string=} opt_message Additional message.
* @constructor
* @extends {goog.debug.Error}
* @final
*/
goog.net.jsloader.Error = function(code, opt_message) {
var msg = 'Jsloader error (code #' + code + ')';
if (opt_message) {
msg += ': ' + opt_message;
}
goog.net.jsloader.Error.base(this, 'constructor', msg);
/**
* The code for this error.
*
* @type {goog.net.jsloader.ErrorCode}
*/
this.code = code;
};
goog.inherits(goog.net.jsloader.Error, goog.debug.Error);

View file

@ -0,0 +1,381 @@
// 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.
// The original file lives here: http://go/cross_domain_channel.js
/**
* @fileoverview Implements a cross-domain communication channel. A
* typical web page is prevented by browser security from sending
* request, such as a XMLHttpRequest, to other servers than the ones
* from which it came. The Jsonp class provides a workaround by
* using dynamically generated script tags. Typical usage:.
*
* var jsonp = new goog.net.Jsonp(new goog.Uri('http://my.host.com/servlet'));
* var payload = { 'foo': 1, 'bar': true };
* jsonp.send(payload, function(reply) { alert(reply) });
*
* This script works in all browsers that are currently supported by
* the Google Maps API, which is IE 6.0+, Firefox 0.8+, Safari 1.2.4+,
* Netscape 7.1+, Mozilla 1.4+, Opera 8.02+.
*
*/
goog.provide('goog.net.Jsonp');
goog.require('goog.Uri');
goog.require('goog.html.legacyconversions');
goog.require('goog.net.jsloader');
// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
//
// This class allows us (Google) to send data from non-Google and thus
// UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return
// anything sensitive, such as session or cookie specific data. Return
// only data that you want parties external to Google to have. Also
// NEVER use this method to send data from web pages to untrusted
// servers, or redirects to unknown servers (www.google.com/cache,
// /q=xx&btnl, /url, www.googlepages.com, etc.)
//
// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
/**
* Creates a new cross domain channel that sends data to the specified
* host URL. By default, if no reply arrives within 5s, the channel
* assumes the call failed to complete successfully.
*
* @param {goog.Uri|string} uri The Uri of the server side code that receives
* data posted through this channel (e.g.,
* "http://maps.google.com/maps/geo").
*
* @param {string=} opt_callbackParamName The parameter name that is used to
* specify the callback. Defaults to "callback".
*
* @constructor
* @final
*/
goog.net.Jsonp = function(uri, opt_callbackParamName) {
/**
* The uri_ object will be used to encode the payload that is sent to the
* server.
* @type {goog.Uri}
* @private
*/
this.uri_ = new goog.Uri(uri);
/**
* This is the callback parameter name that is added to the uri.
* @type {string}
* @private
*/
this.callbackParamName_ =
opt_callbackParamName ? opt_callbackParamName : 'callback';
/**
* The length of time, in milliseconds, this channel is prepared
* to wait for for a request to complete. The default value is 5 seconds.
* @type {number}
* @private
*/
this.timeout_ = 5000;
/**
* The nonce to use in the dynamically generated script tags. This is used for
* allowing the script callbacks to execute when the page has an enforced
* Content Security Policy.
* @type {string}
* @private
*/
this.nonce_ = '';
};
/**
* The prefix for the callback name which will be stored on goog.global.
*/
goog.net.Jsonp.CALLBACKS = '_callbacks_';
/**
* Used to generate unique callback IDs. The counter must be global because
* all channels share a common callback object.
* @private
*/
goog.net.Jsonp.scriptCounter_ = 0;
/**
* Static private method which returns the global unique callback id.
*
* @param {string} id The id of the script node.
* @return {string} A global unique id used to store callback on goog.global
* object.
* @private
*/
goog.net.Jsonp.getCallbackId_ = function(id) {
return goog.net.Jsonp.CALLBACKS + '__' + id;
};
/**
* Sets the length of time, in milliseconds, this channel is prepared
* to wait for for a request to complete. If the call is not competed
* within the set time span, it is assumed to have failed. To wait
* indefinitely for a request to complete set the timout to a negative
* number.
*
* @param {number} timeout The length of time before calls are
* interrupted.
*/
goog.net.Jsonp.prototype.setRequestTimeout = function(timeout) {
this.timeout_ = timeout;
};
/**
* Returns the current timeout value, in milliseconds.
*
* @return {number} The timeout value.
*/
goog.net.Jsonp.prototype.getRequestTimeout = function() {
return this.timeout_;
};
/**
* Sets the nonce value for CSP. This nonce value will be added to any created
* script elements and must match the nonce provided in the
* Content-Security-Policy header sent by the server for the callback to pass
* CSP enforcement.
*
* @param {string} nonce The CSP nonce value.
*/
goog.net.Jsonp.prototype.setNonce = function(nonce) {
this.nonce_ = nonce;
};
/**
* Sends the given payload to the URL specified at the construction
* time. The reply is delivered to the given replyCallback. If the
* errorCallback is specified and the reply does not arrive within the
* timeout period set on this channel, the errorCallback is invoked
* with the original payload.
*
* If no reply callback is specified, then the response is expected to
* consist of calls to globally registered functions. No &callback=
* URL parameter will be sent in the request, and the script element
* will be cleaned up after the timeout.
*
* @param {Object=} opt_payload Name-value pairs. If given, these will be
* added as parameters to the supplied URI as GET parameters to the
* given server URI.
*
* @param {Function=} opt_replyCallback A function expecting one
* argument, called when the reply arrives, with the response data.
*
* @param {Function=} opt_errorCallback A function expecting one
* argument, called on timeout, with the payload (if given), otherwise
* null.
*
* @param {string=} opt_callbackParamValue Value to be used as the
* parameter value for the callback parameter (callbackParamName).
* To be used when the value needs to be fixed by the client for a
* particular request, to make use of the cached responses for the request.
* NOTE: If multiple requests are made with the same
* opt_callbackParamValue, only the last call will work whenever the
* response comes back.
*
* @return {!Object} A request descriptor that may be used to cancel this
* transmission, or null, if the message may not be cancelled.
*/
goog.net.Jsonp.prototype.send = function(
opt_payload, opt_replyCallback, opt_errorCallback, opt_callbackParamValue) {
var payload = opt_payload || null;
var id = opt_callbackParamValue ||
'_' + (goog.net.Jsonp.scriptCounter_++).toString(36) +
goog.now().toString(36);
var callbackId = goog.net.Jsonp.getCallbackId_(id);
// Create a new Uri object onto which this payload will be added
var uri = this.uri_.clone();
if (payload) {
goog.net.Jsonp.addPayloadToUri_(payload, uri);
}
if (opt_replyCallback) {
var reply = goog.net.Jsonp.newReplyHandler_(id, opt_replyCallback);
// Register the callback on goog.global to make it discoverable
// by jsonp response.
goog.global[callbackId] = reply;
uri.setParameterValues(this.callbackParamName_, callbackId);
}
var options = {timeout: this.timeout_, cleanupWhenDone: true};
if (this.nonce_) {
options.attributes = {'nonce': this.nonce_};
}
var deferred = goog.net.jsloader.safeLoad(
goog.html.legacyconversions.trustedResourceUrlFromString(uri.toString()),
options);
var error = goog.net.Jsonp.newErrorHandler_(id, payload, opt_errorCallback);
deferred.addErrback(error);
return {id_: id, deferred_: deferred};
};
/**
* Cancels a given request. The request must be exactly the object returned by
* the send method.
*
* @param {Object} request The request object returned by the send method.
*/
goog.net.Jsonp.prototype.cancel = function(request) {
if (request) {
if (request.deferred_) {
request.deferred_.cancel();
}
if (request.id_) {
goog.net.Jsonp.cleanup_(request.id_, false);
}
}
};
/**
* Creates a timeout callback that calls the given timeoutCallback with the
* original payload.
*
* @param {string} id The id of the script node.
* @param {Object} payload The payload that was sent to the server.
* @param {Function=} opt_errorCallback The function called on timeout.
* @return {!Function} A zero argument function that handles callback duties.
* @private
*/
goog.net.Jsonp.newErrorHandler_ = function(id, payload, opt_errorCallback) {
/**
* When we call across domains with a request, this function is the
* timeout handler. Once it's done executing the user-specified
* error-handler, it removes the script node and original function.
*/
return function() {
goog.net.Jsonp.cleanup_(id, false);
if (opt_errorCallback) {
opt_errorCallback(payload);
}
};
};
/**
* Creates a reply callback that calls the given replyCallback with data
* returned by the server.
*
* @param {string} id The id of the script node.
* @param {Function} replyCallback The function called on reply.
* @return {!Function} A reply callback function.
* @private
*/
goog.net.Jsonp.newReplyHandler_ = function(id, replyCallback) {
/**
* This function is the handler for the all-is-well response. It
* clears the error timeout handler, calls the user's handler, then
* removes the script node and itself.
*
* @param {...Object} var_args The response data sent from the server.
*/
var handler = function(var_args) {
goog.net.Jsonp.cleanup_(id, true);
replyCallback.apply(undefined, arguments);
};
return handler;
};
/**
* Removes the reply handler registered on goog.global object.
*
* @param {string} id The id of the script node to be removed.
* @param {boolean} deleteReplyHandler If true, delete the reply handler
* instead of setting it to nullFunction (if we know the callback could
* never be called again).
* @private
*/
goog.net.Jsonp.cleanup_ = function(id, deleteReplyHandler) {
var callbackId = goog.net.Jsonp.getCallbackId_(id);
if (goog.global[callbackId]) {
if (deleteReplyHandler) {
try {
delete goog.global[callbackId];
} catch (e) {
// NOTE: Workaround to delete property on 'window' in IE <= 8, see:
// http://stackoverflow.com/questions/1073414/deleting-a-window-property-in-ie
goog.global[callbackId] = undefined;
}
} else {
// Removing the script tag doesn't necessarily prevent the script
// from firing, so we make the callback a noop.
goog.global[callbackId] = goog.nullFunction;
}
}
};
/**
* Returns URL encoded payload. The payload should be a map of name-value
* pairs, in the form {"foo": 1, "bar": true, ...}. If the map is empty,
* the URI will be unchanged.
*
* <p>The method uses hasOwnProperty() to assure the properties are on the
* object, not on its prototype.
*
* @param {!Object} payload A map of value name pairs to be encoded.
* A value may be specified as an array, in which case a query parameter
* will be created for each value, e.g.:
* {"foo": [1,2]} will encode to "foo=1&foo=2".
*
* @param {!goog.Uri} uri A Uri object onto which the payload key value pairs
* will be encoded.
*
* @return {!goog.Uri} A reference to the Uri sent as a parameter.
* @private
*/
goog.net.Jsonp.addPayloadToUri_ = function(payload, uri) {
for (var name in payload) {
// NOTE(user): Safari/1.3 doesn't have hasOwnProperty(). In that
// case, we iterate over all properties as a very lame workaround.
if (!payload.hasOwnProperty || payload.hasOwnProperty(name)) {
uri.setParameterValues(name, payload[name]);
}
}
return uri;
};
// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
//
// This class allows us (Google) to send data from non-Google and thus
// UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return
// anything sensitive, such as session or cookie specific data. Return
// only data that you want parties external to Google to have. Also
// NEVER use this method to send data from web pages to untrusted
// servers, or redirects to unknown servers (www.google.com/cache,
// /q=xx&btnl, /url, www.googlepages.com, etc.)
//
// WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING

View file

@ -0,0 +1,70 @@
// Copyright 2010 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 Implementation of XmlHttpFactory which allows construction from
* simple factory methods.
* @author dbk@google.com (David Barrett-Kahn)
*/
goog.provide('goog.net.WrapperXmlHttpFactory');
/** @suppress {extraRequire} Typedef. */
goog.require('goog.net.XhrLike');
goog.require('goog.net.XmlHttpFactory');
/**
* An xhr factory subclass which can be constructed using two factory methods.
* This exists partly to allow the preservation of goog.net.XmlHttp.setFactory()
* with an unchanged signature.
* @param {function():!goog.net.XhrLike.OrNative} xhrFactory
* A function which returns a new XHR object.
* @param {function():!Object} optionsFactory A function which returns the
* options associated with xhr objects from this factory.
* @extends {goog.net.XmlHttpFactory}
* @constructor
* @final
*/
goog.net.WrapperXmlHttpFactory = function(xhrFactory, optionsFactory) {
goog.net.XmlHttpFactory.call(this);
/**
* XHR factory method.
* @type {function() : !goog.net.XhrLike.OrNative}
* @private
*/
this.xhrFactory_ = xhrFactory;
/**
* Options factory method.
* @type {function() : !Object}
* @private
*/
this.optionsFactory_ = optionsFactory;
};
goog.inherits(goog.net.WrapperXmlHttpFactory, goog.net.XmlHttpFactory);
/** @override */
goog.net.WrapperXmlHttpFactory.prototype.createInstance = function() {
return this.xhrFactory_();
};
/** @override */
goog.net.WrapperXmlHttpFactory.prototype.getOptions = function() {
return this.optionsFactory_();
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,124 @@
// Copyright 2013 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.
goog.provide('goog.net.XhrLike');
/**
* Interface for the common parts of XMLHttpRequest.
*
* Mostly copied from externs/w3c_xml.js.
*
* @interface
* @see http://www.w3.org/TR/XMLHttpRequest/
*/
goog.net.XhrLike = function() {};
/**
* Typedef that refers to either native or custom-implemented XHR objects.
* @typedef {!goog.net.XhrLike|!XMLHttpRequest}
*/
goog.net.XhrLike.OrNative;
/**
* @type {function()|null|undefined}
* @see http://www.w3.org/TR/XMLHttpRequest/#handler-xhr-onreadystatechange
*/
goog.net.XhrLike.prototype.onreadystatechange;
/**
* @type {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
*/
goog.net.XhrLike.prototype.responseText;
/**
* @type {Document}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsexml-attribute
*/
goog.net.XhrLike.prototype.responseXML;
/**
* @type {number}
* @see http://www.w3.org/TR/XMLHttpRequest/#readystate
*/
goog.net.XhrLike.prototype.readyState;
/**
* @type {number}
* @see http://www.w3.org/TR/XMLHttpRequest/#status
*/
goog.net.XhrLike.prototype.status;
/**
* @type {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#statustext
*/
goog.net.XhrLike.prototype.statusText;
/**
* @param {string} method
* @param {string} url
* @param {?boolean=} opt_async
* @param {?string=} opt_user
* @param {?string=} opt_password
* @see http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
*/
goog.net.XhrLike.prototype.open = function(
method, url, opt_async, opt_user, opt_password) {};
/**
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=} opt_data
* @see http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
*/
goog.net.XhrLike.prototype.send = function(opt_data) {};
/**
* @see http://www.w3.org/TR/XMLHttpRequest/#the-abort()-method
*/
goog.net.XhrLike.prototype.abort = function() {};
/**
* @param {string} header
* @param {string} value
* @see http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
*/
goog.net.XhrLike.prototype.setRequestHeader = function(header, value) {};
/**
* @param {string} header
* @return {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
*/
goog.net.XhrLike.prototype.getResponseHeader = function(header) {};
/**
* @return {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
*/
goog.net.XhrLike.prototype.getAllResponseHeaders = function() {};

View file

@ -0,0 +1,248 @@
// 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 Low level handling of XMLHttpRequest.
* @author arv@google.com (Erik Arvidsson)
* @author dbk@google.com (David Barrett-Kahn)
*/
goog.provide('goog.net.DefaultXmlHttpFactory');
goog.provide('goog.net.XmlHttp');
goog.provide('goog.net.XmlHttp.OptionType');
goog.provide('goog.net.XmlHttp.ReadyState');
goog.provide('goog.net.XmlHttpDefines');
goog.require('goog.asserts');
goog.require('goog.net.WrapperXmlHttpFactory');
goog.require('goog.net.XmlHttpFactory');
/**
* Static class for creating XMLHttpRequest objects.
* @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.
*/
goog.net.XmlHttp = function() {
return goog.net.XmlHttp.factory_.createInstance();
};
/**
* @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to
* true bypasses the ActiveX probing code.
* NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip
* out the ActiveX probing code from binaries. To achieve this, use
* {@code goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR} instead.
* TODO(ruilopes): Collapse both defines.
*/
goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);
/** @const */
goog.net.XmlHttpDefines = {};
/**
* @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to
* true eliminates the ActiveX probing code.
*/
goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);
/**
* Gets the options to use with the XMLHttpRequest objects obtained using
* the static methods.
* @return {Object} The options.
*/
goog.net.XmlHttp.getOptions = function() {
return goog.net.XmlHttp.factory_.getOptions();
};
/**
* Type of options that an XmlHttp object can have.
* @enum {number}
*/
goog.net.XmlHttp.OptionType = {
/**
* Whether a goog.nullFunction should be used to clear the onreadystatechange
* handler instead of null.
*/
USE_NULL_FUNCTION: 0,
/**
* NOTE(user): In IE if send() errors on a *local* request the readystate
* is still changed to COMPLETE. We need to ignore it and allow the
* try/catch around send() to pick up the error.
*/
LOCAL_REQUEST_ERROR: 1
};
/**
* Status constants for XMLHTTP, matches:
* https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx
* @enum {number}
*/
goog.net.XmlHttp.ReadyState = {
/**
* Constant for when xmlhttprequest.readyState is uninitialized
*/
UNINITIALIZED: 0,
/**
* Constant for when xmlhttprequest.readyState is loading.
*/
LOADING: 1,
/**
* Constant for when xmlhttprequest.readyState is loaded.
*/
LOADED: 2,
/**
* Constant for when xmlhttprequest.readyState is in an interactive state.
*/
INTERACTIVE: 3,
/**
* Constant for when xmlhttprequest.readyState is completed
*/
COMPLETE: 4
};
/**
* The global factory instance for creating XMLHttpRequest objects.
* @type {goog.net.XmlHttpFactory}
* @private
*/
goog.net.XmlHttp.factory_;
/**
* Sets the factories for creating XMLHttpRequest objects and their options.
* @param {Function} factory The factory for XMLHttpRequest objects.
* @param {Function} optionsFactory The factory for options.
* @deprecated Use setGlobalFactory instead.
*/
goog.net.XmlHttp.setFactory = function(factory, optionsFactory) {
goog.net.XmlHttp.setGlobalFactory(
new goog.net.WrapperXmlHttpFactory(
goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));
};
/**
* Sets the global factory object.
* @param {!goog.net.XmlHttpFactory} factory New global factory object.
*/
goog.net.XmlHttp.setGlobalFactory = function(factory) {
goog.net.XmlHttp.factory_ = factory;
};
/**
* Default factory to use when creating xhr objects. You probably shouldn't be
* instantiating this directly, but rather using it via goog.net.XmlHttp.
* @extends {goog.net.XmlHttpFactory}
* @constructor
*/
goog.net.DefaultXmlHttpFactory = function() {
goog.net.XmlHttpFactory.call(this);
};
goog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);
/** @override */
goog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {
var progId = this.getProgId_();
if (progId) {
return new ActiveXObject(progId);
} else {
return new XMLHttpRequest();
}
};
/** @override */
goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {
var progId = this.getProgId_();
var options = {};
if (progId) {
options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;
options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;
}
return options;
};
/**
* The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.
* @type {string|undefined}
* @private
*/
goog.net.DefaultXmlHttpFactory.prototype.ieProgId_;
/**
* Initialize the private state used by other functions.
* @return {string} The ActiveX PROG ID string to use to create xhr's in IE.
* @private
*/
goog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {
if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||
goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {
return '';
}
// The following blog post describes what PROG IDs to use to create the
// XMLHTTP object in Internet Explorer:
// http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
// However we do not (yet) fully trust that this will be OK for old versions
// of IE on Win9x so we therefore keep the last 2.
if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&
typeof ActiveXObject != 'undefined') {
// Candidate Active X types.
var ACTIVE_X_IDENTS = [
'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'
];
for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) {
var candidate = ACTIVE_X_IDENTS[i];
try {
new ActiveXObject(candidate);
// NOTE(user): cannot assign progid and return candidate in one line
// because JSCompiler complaings: BUG 658126
this.ieProgId_ = candidate;
return candidate;
} catch (e) {
// do nothing; try next choice
}
}
// couldn't find any matches
throw Error(
'Could not create ActiveXObject. ActiveX might be disabled,' +
' or MSXML might not be installed');
}
return /** @type {string} */ (this.ieProgId_);
};
// Set the global factory to an instance of the default factory.
goog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());

View file

@ -0,0 +1,66 @@
// Copyright 2010 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 Interface for a factory for creating XMLHttpRequest objects
* and metadata about them.
* @author dbk@google.com (David Barrett-Kahn)
*/
goog.provide('goog.net.XmlHttpFactory');
/** @suppress {extraRequire} Typedef. */
goog.require('goog.net.XhrLike');
/**
* Abstract base class for an XmlHttpRequest factory.
* @constructor
*/
goog.net.XmlHttpFactory = function() {};
/**
* Cache of options - we only actually call internalGetOptions once.
* @type {Object}
* @private
*/
goog.net.XmlHttpFactory.prototype.cachedOptions_ = null;
/**
* @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.
*/
goog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;
/**
* @return {Object} Options describing how xhr objects obtained from this
* factory should be used.
*/
goog.net.XmlHttpFactory.prototype.getOptions = function() {
return this.cachedOptions_ ||
(this.cachedOptions_ = this.internalGetOptions());
};
/**
* Override this method in subclasses to preserve the caching offered by
* getOptions().
* @return {Object} Options describing how xhr objects obtained from this
* factory should be used.
* @protected
*/
goog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;