selenium-webdriver
Version:
The official WebDriver JavaScript bindings from the Selenium project
1,564 lines (1,352 loc) • 72.1 kB
JavaScript
// 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 Bootstrap for the Google JS Library (Closure).
*
* In uncompiled mode base.js will write out Closure's deps file, unless the
* global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to
* include their own deps file(s) from different locations.
*
*
* @provideGoog
*/
/**
* @define {boolean} Overridden to true by the compiler when --closure_pass
* or --mark_as_compiled is specified.
*/
var COMPILED = false;
/**
* Base namespace for the Closure library. Checks to see goog is already
* defined in the current scope before assigning to prevent clobbering if
* base.js is loaded more than once.
*
* @const
*/
var goog = goog || {};
/**
* Reference to the global context. In most cases this will be 'window'.
*/
goog.global = this;
/**
* A hook for overriding the define values in uncompiled mode.
*
* In uncompiled mode, {@code CLOSURE_UNCOMPILED_DEFINES} may be defined before
* loading base.js. If a key is defined in {@code CLOSURE_UNCOMPILED_DEFINES},
* {@code goog.define} will use the value instead of the default value. This
* allows flags to be overwritten without compilation (this is normally
* accomplished with the compiler's "define" flag).
*
* Example:
* <pre>
* var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};
* </pre>
*
* @type {Object.<string, (string|number|boolean)>|undefined}
*/
goog.global.CLOSURE_UNCOMPILED_DEFINES;
/**
* A hook for overriding the define values in uncompiled or compiled mode,
* like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In
* uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.
*
* Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or
* string literals or the compiler will emit an error.
*
* While any @define value may be set, only those set with goog.define will be
* effective for uncompiled code.
*
* Example:
* <pre>
* var CLOSURE_DEFINES = {'goog.DEBUG': false};
* </pre>
*
* @type {Object.<string, (string|number|boolean)>|undefined}
*/
goog.global.CLOSURE_DEFINES;
/**
* Returns true if the specified value is not undefined.
* WARNING: Do not use this to test if an object has a property. Use the in
* operator instead.
*
* @param {?} val Variable to test.
* @return {boolean} Whether variable is defined.
*/
goog.isDef = function(val) {
// void 0 always evaluates to undefined and hence we do not need to depend on
// the definition of the global variable named 'undefined'.
return val !== void 0;
};
/**
* Builds an object structure for the provided namespace path, ensuring that
* names that already exist are not overwritten. For example:
* "a.b.c" -> a = {};a.b={};a.b.c={};
* Used by goog.provide and goog.exportSymbol.
* @param {string} name name of the object that this file defines.
* @param {*=} opt_object the object to expose at the end of the path.
* @param {Object=} opt_objectToExportTo The object to add the path to; default
* is |goog.global|.
* @private
*/
goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
var parts = name.split('.');
var cur = opt_objectToExportTo || goog.global;
// Internet Explorer exhibits strange behavior when throwing errors from
// methods externed in this manner. See the testExportSymbolExceptions in
// base_test.html for an example.
if (!(parts[0] in cur) && cur.execScript) {
cur.execScript('var ' + parts[0]);
}
// Certain browsers cannot parse code in the form for((a in b); c;);
// This pattern is produced by the JSCompiler when it collapses the
// statement above into the conditional loop below. To prevent this from
// happening, use a for-loop and reserve the init logic as below.
// Parentheses added to eliminate strict JS warning in Firefox.
for (var part; parts.length && (part = parts.shift());) {
if (!parts.length && goog.isDef(opt_object)) {
// last part and we have an object; use it
cur[part] = opt_object;
} else if (cur[part]) {
cur = cur[part];
} else {
cur = cur[part] = {};
}
}
};
/**
* Defines a named value. In uncompiled mode, the value is retreived from
* CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and
* has the property specified, and otherwise used the defined defaultValue.
* When compiled, the default can be overridden using compiler command-line
* options.
*
* @param {string} name The distinguished name to provide.
* @param {string|number|boolean} defaultValue
*/
goog.define = function(name, defaultValue) {
var value = defaultValue;
if (!COMPILED) {
if (goog.global.CLOSURE_UNCOMPILED_DEFINES &&
Object.prototype.hasOwnProperty.call(
goog.global.CLOSURE_UNCOMPILED_DEFINES, name)) {
value = goog.global.CLOSURE_UNCOMPILED_DEFINES[name];
} else if (goog.global.CLOSURE_DEFINES &&
Object.prototype.hasOwnProperty.call(
goog.global.CLOSURE_DEFINES, name)) {
value = goog.global.CLOSURE_DEFINES[name];
}
}
goog.exportPath_(name, value);
};
/**
* @define {boolean} DEBUG is provided as a convenience so that debugging code
* that should not be included in a production js_binary can be easily stripped
* by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
* toString() methods should be declared inside an "if (goog.DEBUG)" conditional
* because they are generally used for debugging purposes and it is difficult
* for the JSCompiler to statically determine whether they are used.
*/
goog.DEBUG = true;
/**
* @define {string} LOCALE defines the locale being used for compilation. It is
* used to select locale specific data to be compiled in js binary. BUILD rule
* can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
* option.
*
* Take into account that the locale code format is important. You should use
* the canonical Unicode format with hyphen as a delimiter. Language must be
* lowercase, Language Script - Capitalized, Region - UPPERCASE.
* There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
*
* See more info about locale codes here:
* http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
*
* For language codes you should use values defined by ISO 693-1. See it here
* http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
* this rule: the Hebrew language. For legacy reasons the old code (iw) should
* be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
*/
goog.define('goog.LOCALE', 'en'); // default to en
/**
* @define {boolean} Whether this code is running on trusted sites.
*
* On untrusted sites, several native functions can be defined or overridden by
* external libraries like Prototype, Datejs, and JQuery and setting this flag
* to false forces closure to use its own implementations when possible.
*
* If your JavaScript can be loaded by a third party site and you are wary about
* relying on non-standard implementations, specify
* "--define goog.TRUSTED_SITE=false" to the JSCompiler.
*/
goog.define('goog.TRUSTED_SITE', true);
/**
* @define {boolean} Whether a project is expected to be running in strict mode.
*
* This define can be used to trigger alternate implementations compatible with
* running in EcmaScript Strict mode or warn about unavailable functionality.
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
*/
goog.define('goog.STRICT_MODE_COMPATIBLE', false);
/**
* Creates object stubs for a namespace. The presence of one or more
* goog.provide() calls indicate that the file defines the given
* objects/namespaces. Provided objects must not be null or undefined.
* Build tools also scan for provide/require statements
* to discern dependencies, build dependency files (see deps.js), etc.
* @see goog.require
* @param {string} name Namespace provided by this file in the form
* "goog.package.part".
*/
goog.provide = function(name) {
if (!COMPILED) {
// Ensure that the same namespace isn't provided twice.
// A goog.module/goog.provide maps a goog.require to a specific file
if (goog.isProvided_(name)) {
throw Error('Namespace "' + name + '" already declared.');
}
delete goog.implicitNamespaces_[name];
var namespace = name;
while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
if (goog.getObjectByName(namespace)) {
break;
}
goog.implicitNamespaces_[namespace] = true;
}
}
goog.exportPath_(name);
};
/**
* goog.module serves two purposes:
* - marks a file that must be loaded as a module
* - reserves a namespace (it can not also be goog.provided)
* and has three requirements:
* - goog.module may not be used in the same file as goog.provide.
* - goog.module must be the first statement in the file.
* - only one goog.module is allowed per file.
* When a goog.module annotated file is loaded, it is loaded enclosed in
* a strict function closure. This means that:
* - any variable declared in a goog.module file are private to the file,
* not global. Although the compiler is expected to inline the module.
* - The code must obey all the rules of "strict" JavaScript.
* - the file will be marked as "use strict"
*
* NOTE: unlike goog.provide, goog.module does not declare any symbols by
* itself.
*
* @param {string} name Namespace provided by this file in the form
* "goog.package.part", is expected but not required.
*/
goog.module = function(name) {
if (!goog.isString(name) || !name) {
throw Error('Invalid module identifier');
}
if (!goog.isInModuleLoader_()) {
throw Error('Module ' + name + ' has been loaded incorrectly.');
}
if (goog.moduleLoaderState_.moduleName) {
throw Error('goog.module may only be called once per module.');
}
// Store the module name for the loader.
goog.moduleLoaderState_.moduleName = name;
if (!COMPILED) {
// Ensure that the same namespace isn't provided twice.
// A goog.module/goog.provide maps a goog.require to a specific file
if (goog.isProvided_(name)) {
throw Error('Namespace "' + name + '" already declared.');
}
delete goog.implicitNamespaces_[name];
}
};
/** @private {{
* moduleName:(string|undefined),
* exportTestMethods:boolean}|null}}
*/
goog.moduleLoaderState_ = null;
/**
* @private
* @return {boolean} Whether a goog.module is currently being initialized.
*/
goog.isInModuleLoader_ = function() {
return goog.moduleLoaderState_ != null;
};
/**
* Indicate that a module's exports that are known test methods should
* be copied to the global object. This makes the test methods visible to
* test runners that inspect the global object.
*
* TODO(johnlenz): Make the test framework aware of goog.module so
* that this isn't necessary. Alternately combine this with goog.setTestOnly
* to minimize boiler plate.
*/
goog.module.exportTestMethods = function() {
if (!goog.isInModuleLoader_()) {
throw new Error('goog.module.exportTestMethods must be called from ' +
'within a goog.module');
}
goog.moduleLoaderState_.exportTestMethods = true;
};
/**
* Marks that the current file should only be used for testing, and never for
* live code in production.
*
* In the case of unit tests, the message may optionally be an exact namespace
* for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra
* provide (if not explicitly defined in the code).
*
* @param {string=} opt_message Optional message to add to the error that's
* raised when used in production code.
*/
goog.setTestOnly = function(opt_message) {
if (COMPILED && !goog.DEBUG) {
opt_message = opt_message || '';
throw Error('Importing test-only code into non-debug environment' +
(opt_message ? ': ' + opt_message : '.'));
}
};
/**
* Forward declares a symbol. This is an indication to the compiler that the
* symbol may be used in the source yet is not required and may not be provided
* in compilation.
*
* The most common usage of forward declaration is code that takes a type as a
* function parameter but does not need to require it. By forward declaring
* instead of requiring, no hard dependency is made, and (if not required
* elsewhere) the namespace may never be required and thus, not be pulled
* into the JavaScript binary. If it is required elsewhere, it will be type
* checked as normal.
*
*
* @param {string} name The namespace to forward declare in the form of
* "goog.package.part".
*/
goog.forwardDeclare = function(name) {};
if (!COMPILED) {
/**
* Check if the given name has been goog.provided. This will return false for
* names that are available only as implicit namespaces.
* @param {string} name name of the object to look for.
* @return {boolean} Whether the name has been provided.
* @private
*/
goog.isProvided_ = function(name) {
return (name in goog.loadedModules_) ||
(!goog.implicitNamespaces_[name] &&
goog.isDefAndNotNull(goog.getObjectByName(name)));
};
/**
* Namespaces implicitly defined by goog.provide. For example,
* goog.provide('goog.events.Event') implicitly declares that 'goog' and
* 'goog.events' must be namespaces.
*
* @type {Object.<string, (boolean|undefined)>}
* @private
*/
goog.implicitNamespaces_ = {'goog.module': true};
// NOTE: We add goog.module as an implicit namespace as goog.module is defined
// here and because the existing module package has not been moved yet out of
// the goog.module namespace. This satisifies both the debug loader and
// ahead-of-time dependency management.
}
/**
* Returns an object based on its fully qualified external name. The object
* is not found if null or undefined. If you are using a compilation pass that
* renames property names beware that using this function will not find renamed
* properties.
*
* @param {string} name The fully qualified name.
* @param {Object=} opt_obj The object within which to look; default is
* |goog.global|.
* @return {?} The value (object or primitive) or, if not found, null.
*/
goog.getObjectByName = function(name, opt_obj) {
var parts = name.split('.');
var cur = opt_obj || goog.global;
for (var part; part = parts.shift(); ) {
if (goog.isDefAndNotNull(cur[part])) {
cur = cur[part];
} else {
return null;
}
}
return cur;
};
/**
* Globalizes a whole namespace, such as goog or goog.lang.
*
* @param {Object} obj The namespace to globalize.
* @param {Object=} opt_global The object to add the properties to.
* @deprecated Properties may be explicitly exported to the global scope, but
* this should no longer be done in bulk.
*/
goog.globalize = function(obj, opt_global) {
var global = opt_global || goog.global;
for (var x in obj) {
global[x] = obj[x];
}
};
/**
* Adds a dependency from a file to the files it requires.
* @param {string} relPath The path to the js file.
* @param {Array} provides An array of strings with the names of the objects
* this file provides.
* @param {Array} requires An array of strings with the names of the objects
* this file requires.
* @param {boolean=} opt_isModule Whether this dependency must be loaded as
* a module as declared by goog.module.
*/
goog.addDependency = function(relPath, provides, requires, opt_isModule) {
if (goog.DEPENDENCIES_ENABLED) {
var provide, require;
var path = relPath.replace(/\\/g, '/');
var deps = goog.dependencies_;
for (var i = 0; provide = provides[i]; i++) {
deps.nameToPath[provide] = path;
deps.pathIsModule[path] = !!opt_isModule;
}
for (var j = 0; require = requires[j]; j++) {
if (!(path in deps.requires)) {
deps.requires[path] = {};
}
deps.requires[path][require] = true;
}
}
};
// NOTE(nnaze): The debug DOM loader was included in base.js as an original way
// to do "debug-mode" development. The dependency system can sometimes be
// confusing, as can the debug DOM loader's asynchronous nature.
//
// With the DOM loader, a call to goog.require() is not blocking -- the script
// will not load until some point after the current script. If a namespace is
// needed at runtime, it needs to be defined in a previous script, or loaded via
// require() with its registered dependencies.
// User-defined namespaces may need their own deps file. See http://go/js_deps,
// http://go/genjsdeps, or, externally, DepsWriter.
// https://developers.google.com/closure/library/docs/depswriter
//
// Because of legacy clients, the DOM loader can't be easily removed from
// base.js. Work is being done to make it disableable or replaceable for
// different environments (DOM-less JavaScript interpreters like Rhino or V8,
// for example). See bootstrap/ for more information.
/**
* @define {boolean} Whether to enable the debug loader.
*
* If enabled, a call to goog.require() will attempt to load the namespace by
* appending a script tag to the DOM (if the namespace has been registered).
*
* If disabled, goog.require() will simply assert that the namespace has been
* provided (and depend on the fact that some outside tool correctly ordered
* the script).
*/
goog.define('goog.ENABLE_DEBUG_LOADER', true);
/**
* @param {string} msg
* @private
*/
goog.logToConsole_ = function(msg) {
if (goog.global.console) {
goog.global.console['error'](msg);
}
};
/**
* Implements a system for the dynamic resolution of dependencies that works in
* parallel with the BUILD system. Note that all calls to goog.require will be
* stripped by the JSCompiler when the --closure_pass option is used.
* @see goog.provide
* @param {string} name Namespace to include (as was given in goog.provide()) in
* the form "goog.package.part".
* @return {?} If called within a goog.module file, the associated namespace or
* module otherwise null.
*/
goog.require = function(name) {
// If the object already exists we do not need do do anything.
if (!COMPILED) {
if (goog.isProvided_(name)) {
if (goog.isInModuleLoader_()) {
// goog.require only return a value with-in goog.module files.
return name in goog.loadedModules_ ?
goog.loadedModules_[name] :
goog.getObjectByName(name);
} else {
return null;
}
}
if (goog.ENABLE_DEBUG_LOADER) {
var path = goog.getPathFromDeps_(name);
if (path) {
goog.included_[path] = true;
goog.writeScripts_();
return null;
}
}
var errorMessage = 'goog.require could not find: ' + name;
goog.logToConsole_(errorMessage);
throw Error(errorMessage);
}
};
/**
* Path for included scripts.
* @type {string}
*/
goog.basePath = '';
/**
* A hook for overriding the base path.
* @type {string|undefined}
*/
goog.global.CLOSURE_BASE_PATH;
/**
* Whether to write out Closure's deps file. By default, the deps are written.
* @type {boolean|undefined}
*/
goog.global.CLOSURE_NO_DEPS;
/**
* A function to import a single script. This is meant to be overridden when
* Closure is being run in non-HTML contexts, such as web workers. It's defined
* in the global scope so that it can be set before base.js is loaded, which
* allows deps.js to be imported properly.
*
* The function is passed the script source, which is a relative URI. It should
* return true if the script was imported, false otherwise.
* @type {(function(string): boolean)|undefined}
*/
goog.global.CLOSURE_IMPORT_SCRIPT;
/**
* Null function used for default values of callbacks, etc.
* @return {void} Nothing.
*/
goog.nullFunction = function() {};
/**
* The identity function. Returns its first argument.
*
* @param {*=} opt_returnValue The single value that will be returned.
* @param {...*} var_args Optional trailing arguments. These are ignored.
* @return {?} The first argument. We can't know the type -- just pass it along
* without type.
* @deprecated Use goog.functions.identity instead.
*/
goog.identityFunction = function(opt_returnValue, var_args) {
return opt_returnValue;
};
/**
* When defining a class Foo with an abstract method bar(), you can do:
* Foo.prototype.bar = goog.abstractMethod
*
* Now if a subclass of Foo fails to override bar(), an error will be thrown
* when bar() is invoked.
*
* Note: This does not take the name of the function to override as an argument
* because that would make it more difficult to obfuscate our JavaScript code.
*
* @type {!Function}
* @throws {Error} when invoked to indicate the method should be overridden.
*/
goog.abstractMethod = function() {
throw Error('unimplemented abstract method');
};
/**
* Adds a {@code getInstance} static method that always returns the same
* instance object.
* @param {!Function} ctor The constructor for the class to add the static
* method to.
*/
goog.addSingletonGetter = function(ctor) {
ctor.getInstance = function() {
if (ctor.instance_) {
return ctor.instance_;
}
if (goog.DEBUG) {
// NOTE: JSCompiler can't optimize away Array#push.
goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;
}
return ctor.instance_ = new ctor;
};
};
/**
* All singleton classes that have been instantiated, for testing. Don't read
* it directly, use the {@code goog.testing.singleton} module. The compiler
* removes this variable if unused.
* @type {!Array.<!Function>}
* @private
*/
goog.instantiatedSingletons_ = [];
/**
* @define {boolean} Whether to load goog.modules using {@code eval} when using
* the debug loader. This provides a better debugging experience as the
* source is unmodified and can be edited using Chrome Workspaces or
* similiar. However in some environments the use of {@code eval} is banned
* so we provide an alternative.
*/
goog.define('goog.LOAD_MODULE_USING_EVAL', true);
/**
* The registry of initialized modules:
* the module identifier to module exports map.
* @private @const {Object.<string, ?>}
*/
goog.loadedModules_ = {};
/**
* True if goog.dependencies_ is available.
* @const {boolean}
*/
goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;
if (goog.DEPENDENCIES_ENABLED) {
/**
* Object used to keep track of urls that have already been added. This record
* allows the prevention of circular dependencies.
* @type {Object}
* @private
*/
goog.included_ = {};
/**
* This object is used to keep track of dependencies and other data that is
* used for loading scripts.
* @private
* @type {Object}
*/
goog.dependencies_ = {
pathIsModule: {}, // 1 to 1
nameToPath: {}, // many to 1
requires: {}, // 1 to many
// Used when resolving dependencies to prevent us from visiting file twice.
visited: {},
written: {} // Used to keep track of script files we have written.
};
/**
* Tries to detect whether is in the context of an HTML document.
* @return {boolean} True if it looks like HTML document.
* @private
*/
goog.inHtmlDocument_ = function() {
var doc = goog.global.document;
return typeof doc != 'undefined' &&
'write' in doc; // XULDocument misses write.
};
/**
* Tries to detect the base path of base.js script that bootstraps Closure.
* @private
*/
goog.findBasePath_ = function() {
if (goog.global.CLOSURE_BASE_PATH) {
goog.basePath = goog.global.CLOSURE_BASE_PATH;
return;
} else if (!goog.inHtmlDocument_()) {
return;
}
var doc = goog.global.document;
var scripts = doc.getElementsByTagName('script');
// Search backwards since the current script is in almost all cases the one
// that has base.js.
for (var i = scripts.length - 1; i >= 0; --i) {
var src = scripts[i].src;
var qmark = src.lastIndexOf('?');
var l = qmark == -1 ? src.length : qmark;
if (src.substr(l - 7, 7) == 'base.js') {
goog.basePath = src.substr(0, l - 7);
return;
}
}
};
/**
* Imports a script if, and only if, that script hasn't already been imported.
* (Must be called at execution time)
* @param {string} src Script source.
* @param {string=} opt_sourceText The optionally source text to evaluate
* @private
*/
goog.importScript_ = function(src, opt_sourceText) {
var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
goog.writeScriptTag_;
if (importScript(src, opt_sourceText)) {
goog.dependencies_.written[src] = true;
}
};
/** @const @private {boolean} */
goog.IS_OLD_IE_ = goog.global.document &&
goog.global.document.all && !goog.global.atob;
/**
* Given a URL initiate retrieval and execution of the module.
* @param {string} src Script source URL.
* @private
*/
goog.importModule_ = function(src) {
// In an attempt to keep browsers from timing out loading scripts using
// synchronous XHRs, put each load in its own script block.
var bootstrap = 'goog.retrieveAndExecModule_("' + src + '");';
if (goog.importScript_('', bootstrap)) {
goog.dependencies_.written[src] = true;
}
};
/** @private {Array.<string>} */
goog.queuedModules_ = [];
/**
* Retrieve and execute a module.
* @param {string} src Script source URL.
* @private
*/
goog.retrieveAndExecModule_ = function(src) {
var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
goog.writeScriptTag_;
var scriptText = null;
var xhr = new goog.global['XMLHttpRequest']();
/** @this {Object} */
xhr.onload = function() {
scriptText = this.responseText;
};
xhr.open('get', src, false);
xhr.send();
scriptText = xhr.responseText;
if (scriptText != null) {
var execModuleScript = goog.wrapModule_(src, scriptText);
var isOldIE = goog.IS_OLD_IE_;
if (isOldIE) {
goog.queuedModules_.push(execModuleScript);
} else {
importScript(src, execModuleScript);
}
goog.dependencies_.written[src] = true;
} else {
throw new Error('load of ' + src + 'failed');
}
};
/**
* Return an appropriate module text. Suitable to insert into
* a script tag (that is unescaped).
* @param {string} srcUrl
* @param {string} scriptText
* @return {string}
* @private
*/
goog.wrapModule_ = function(srcUrl, scriptText) {
if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {
return '' +
'goog.loadModule(function(exports) {' +
'"use strict";' +
scriptText +
'\n' + // terminate any trailing single line comment.
';return exports' +
'});' +
'\n//# sourceURL=' + srcUrl + '\n';
} else {
return '' +
'goog.loadModule(' +
goog.global.JSON.stringify(
scriptText + '\n//# sourceURL=' + srcUrl + '\n') +
');';
}
};
/**
* Load any deferred goog.module loads.
* @private
*/
goog.loadQueuedModules_ = function() {
var count = goog.queuedModules_.length;
if (count > 0) {
var queue = goog.queuedModules_;
goog.queuedModules_ = [];
for (var i = 0; i < count; i++) {
var entry = queue[i];
goog.globalEval(entry);
}
}
};
/**
* @param {function(?):?|string} moduleDef The module definition.
*/
goog.loadModule = function(moduleDef) {
// NOTE: we allow function definitions to be either in the from
// of a string to eval (which keeps the original source intact) or
// in a eval forbidden environment (CSP) we allow a function definition
// which in its body must call {@code goog.module}, and return the exports
// of the module.
try {
goog.moduleLoaderState_ = {
moduleName: undefined, exportTestMethods: false};
var exports;
if (goog.isFunction(moduleDef)) {
exports = moduleDef.call(goog.global, {});
} else if (goog.isString(moduleDef)) {
exports = goog.loadModuleFromSource_.call(goog.global, moduleDef);
} else {
throw Error('Invalid module definition');
}
if (Object.seal) {
Object.seal(exports);
}
var moduleName = goog.moduleLoaderState_.moduleName;
if (!goog.isString(moduleName) || !moduleName) {
throw Error('Invalid module name \"' + moduleName + '\"');
}
goog.loadedModules_[moduleName] = exports;
if (goog.moduleLoaderState_.exportTestMethods) {
for (var entry in exports) {
if (entry.indexOf('test', 0) === 0 ||
entry == 'tearDown' ||
entry == 'setup') {
goog.global[entry] = exports[entry];
}
}
}
} finally {
goog.moduleLoaderState_ = null;
}
};
/**
* @private @const {function(string):?}
*/
goog.loadModuleFromSource_ = function() {
// NOTE: we avoid declaring parameters or local variables here to avoid
// masking globals or leaking values into the module definition.
'use strict';
var exports = {};
eval(arguments[0]);
return exports;
};
/**
* The default implementation of the import function. Writes a script tag to
* import the script.
*
* @param {string} src The script url.
* @param {string=} opt_sourceText The optionally source text to evaluate
* @return {boolean} True if the script was imported, false otherwise.
* @private
*/
goog.writeScriptTag_ = function(src, opt_sourceText) {
if (goog.inHtmlDocument_()) {
var doc = goog.global.document;
// If the user tries to require a new symbol after document load,
// something has gone terribly wrong. Doing a document.write would
// wipe out the page.
if (doc.readyState == 'complete') {
// Certain test frameworks load base.js multiple times, which tries
// to write deps.js each time. If that happens, just fail silently.
// These frameworks wipe the page between each load of base.js, so this
// is OK.
var isDeps = /\bdeps.js$/.test(src);
if (isDeps) {
return false;
} else {
throw Error('Cannot write "' + src + '" after document load');
}
}
var isOldIE = goog.IS_OLD_IE_;
if (opt_sourceText === undefined) {
if (!isOldIE) {
doc.write(
'<script type="text/javascript" src="' +
src + '"></' + 'script>');
} else {
var state = " onreadystatechange='goog.onScriptLoad_(this, " +
++goog.lastNonModuleScriptIndex_ + ")' ";
doc.write(
'<script type="text/javascript" src="' +
src + '"' + state + '></' + 'script>');
}
} else {
doc.write(
'<script type="text/javascript">' +
opt_sourceText +
'</' + 'script>');
}
return true;
} else {
return false;
}
};
/** @private {number} */
goog.lastNonModuleScriptIndex_ = 0;
/**
* A readystatechange handler for legacy IE
* @param {HTMLScriptElement} script
* @param {number} scriptIndex
* @return {boolean}
* @private
*/
goog.onScriptLoad_ = function(script, scriptIndex) {
// for now load the modules when we reach the last script,
// later allow more inter-mingling.
if (script.readyState == 'complete' &&
goog.lastNonModuleScriptIndex_ == scriptIndex) {
goog.loadQueuedModules_();
}
return true;
};
/**
* Resolves dependencies based on the dependencies added using addDependency
* and calls importScript_ in the correct order.
* @private
*/
goog.writeScripts_ = function() {
// The scripts we need to write this time.
var scripts = [];
var seenScript = {};
var deps = goog.dependencies_;
function visitNode(path) {
if (path in deps.written) {
return;
}
// We have already visited this one. We can get here if we have cyclic
// dependencies.
if (path in deps.visited) {
if (!(path in seenScript)) {
seenScript[path] = true;
scripts.push(path);
}
return;
}
deps.visited[path] = true;
if (path in deps.requires) {
for (var requireName in deps.requires[path]) {
// If the required name is defined, we assume that it was already
// bootstrapped by other means.
if (!goog.isProvided_(requireName)) {
if (requireName in deps.nameToPath) {
visitNode(deps.nameToPath[requireName]);
} else {
throw Error('Undefined nameToPath for ' + requireName);
}
}
}
}
if (!(path in seenScript)) {
seenScript[path] = true;
scripts.push(path);
}
}
for (var path in goog.included_) {
if (!deps.written[path]) {
visitNode(path);
}
}
// record that we are going to load all these scripts.
for (var i = 0; i < scripts.length; i++) {
var path = scripts[i];
goog.dependencies_.written[path] = true;
}
// If a module is loaded synchronously then we need to
// clear the current inModuleLoader value, and restore it when we are
// done loading the current "requires".
var moduleState = goog.moduleLoaderState_;
goog.moduleLoaderState_ = null;
var loadingModule = false;
for (var i = 0; i < scripts.length; i++) {
var path = scripts[i];
if (path) {
if (!deps.pathIsModule[path]) {
goog.importScript_(goog.basePath + path);
} else {
loadingModule = true;
goog.importModule_(goog.basePath + path);
}
} else {
goog.moduleLoaderState_ = moduleState;
throw Error('Undefined script input');
}
}
// restore the current "module loading state"
goog.moduleLoaderState_ = moduleState;
};
/**
* Looks at the dependency rules and tries to determine the script file that
* fulfills a particular rule.
* @param {string} rule In the form goog.namespace.Class or project.script.
* @return {?string} Url corresponding to the rule, or null.
* @private
*/
goog.getPathFromDeps_ = function(rule) {
if (rule in goog.dependencies_.nameToPath) {
return goog.dependencies_.nameToPath[rule];
} else {
return null;
}
};
goog.findBasePath_();
// Allow projects to manage the deps files themselves.
if (!goog.global.CLOSURE_NO_DEPS) {
goog.importScript_(goog.basePath + 'deps.js');
}
}
//==============================================================================
// Language Enhancements
//==============================================================================
/**
* This is a "fixed" version of the typeof operator. It differs from the typeof
* operator in such a way that null returns 'null' and arrays return 'array'.
* @param {*} value The value to get the type of.
* @return {string} The name of the type.
*/
goog.typeOf = function(value) {
var s = typeof value;
if (s == 'object') {
if (value) {
// Check these first, so we can avoid calling Object.prototype.toString if
// possible.
//
// IE improperly marshals tyepof across execution contexts, but a
// cross-context object will still return false for "instanceof Object".
if (value instanceof Array) {
return 'array';
} else if (value instanceof Object) {
return s;
}
// HACK: In order to use an Object prototype method on the arbitrary
// value, the compiler requires the value be cast to type Object,
// even though the ECMA spec explicitly allows it.
var className = Object.prototype.toString.call(
/** @type {Object} */ (value));
// In Firefox 3.6, attempting to access iframe window objects' length
// property throws an NS_ERROR_FAILURE, so we need to special-case it
// here.
if (className == '[object Window]') {
return 'object';
}
// We cannot always use constructor == Array or instanceof Array because
// different frames have different Array objects. In IE6, if the iframe
// where the array was created is destroyed, the array loses its
// prototype. Then dereferencing val.splice here throws an exception, so
// we can't use goog.isFunction. Calling typeof directly returns 'unknown'
// so that will work. In this case, this function will return false and
// most array functions will still work because the array is still
// array-like (supports length and []) even though it has lost its
// prototype.
// Mark Miller noticed that Object.prototype.toString
// allows access to the unforgeable [[Class]] property.
// 15.2.4.2 Object.prototype.toString ( )
// When the toString method is called, the following steps are taken:
// 1. Get the [[Class]] property of this object.
// 2. Compute a string value by concatenating the three strings
// "[object ", Result(1), and "]".
// 3. Return Result(2).
// and this behavior survives the destruction of the execution context.
if ((className == '[object Array]' ||
// In IE all non value types are wrapped as objects across window
// boundaries (not iframe though) so we have to do object detection
// for this edge case.
typeof value.length == 'number' &&
typeof value.splice != 'undefined' &&
typeof value.propertyIsEnumerable != 'undefined' &&
!value.propertyIsEnumerable('splice')
)) {
return 'array';
}
// HACK: There is still an array case that fails.
// function ArrayImpostor() {}
// ArrayImpostor.prototype = [];
// var impostor = new ArrayImpostor;
// this can be fixed by getting rid of the fast path
// (value instanceof Array) and solely relying on
// (value && Object.prototype.toString.vall(value) === '[object Array]')
// but that would require many more function calls and is not warranted
// unless closure code is receiving objects from untrusted sources.
// IE in cross-window calls does not correctly marshal the function type
// (it appears just as an object) so we cannot use just typeof val ==
// 'function'. However, if the object has a call property, it is a
// function.
if ((className == '[object Function]' ||
typeof value.call != 'undefined' &&
typeof value.propertyIsEnumerable != 'undefined' &&
!value.propertyIsEnumerable('call'))) {
return 'function';
}
} else {
return 'null';
}
} else if (s == 'function' && typeof value.call == 'undefined') {
// In Safari typeof nodeList returns 'function', and on Firefox typeof
// behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We
// would like to return object for those and we can detect an invalid
// function by making sure that the function object has a call method.
return 'object';
}
return s;
};
/**
* Returns true if the specified value is null.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is null.
*/
goog.isNull = function(val) {
return val === null;
};
/**
* Returns true if the specified value is defined and not null.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is defined and not null.
*/
goog.isDefAndNotNull = function(val) {
// Note that undefined == null.
return val != null;
};
/**
* Returns true if the specified value is an array.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is an array.
*/
goog.isArray = function(val) {
return goog.typeOf(val) == 'array';
};
/**
* Returns true if the object looks like an array. To qualify as array like
* the value needs to be either a NodeList or an object with a Number length
* property.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is an array.
*/
goog.isArrayLike = function(val) {
var type = goog.typeOf(val);
return type == 'array' || type == 'object' && typeof val.length == 'number';
};
/**
* Returns true if the object looks like a Date. To qualify as Date-like the
* value needs to be an object and have a getFullYear() function.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is a like a Date.
*/
goog.isDateLike = function(val) {
return goog.isObject(val) && typeof val.getFullYear == 'function';
};
/**
* Returns true if the specified value is a string.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is a string.
*/
goog.isString = function(val) {
return typeof val == 'string';
};
/**
* Returns true if the specified value is a boolean.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is boolean.
*/
goog.isBoolean = function(val) {
return typeof val == 'boolean';
};
/**
* Returns true if the specified value is a number.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is a number.
*/
goog.isNumber = function(val) {
return typeof val == 'number';
};
/**
* Returns true if the specified value is a function.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is a function.
*/
goog.isFunction = function(val) {
return goog.typeOf(val) == 'function';
};
/**
* Returns true if the specified value is an object. This includes arrays and
* functions.
* @param {?} val Variable to test.
* @return {boolean} Whether variable is an object.
*/
goog.isObject = function(val) {
var type = typeof val;
return type == 'object' && val != null || type == 'function';
// return Object(val) === val also works, but is slower, especially if val is
// not an object.
};
/**
* Gets a unique ID for an object. This mutates the object so that further calls
* with the same object as a parameter returns the same value. The unique ID is
* guaranteed to be unique across the current session amongst objects that are
* passed into {@code getUid}. There is no guarantee that the ID is unique or
* consistent across sessions. It is unsafe to generate unique ID for function
* prototypes.
*
* @param {Object} obj The object to get the unique ID for.
* @return {number} The unique ID for the object.
*/
goog.getUid = function(obj) {
// TODO(arv): Make the type stricter, do not accept null.
// In Opera window.hasOwnProperty exists but always returns false so we avoid
// using it. As a consequence the unique ID generated for BaseClass.prototype
// and SubClass.prototype will be the same.
return obj[goog.UID_PROPERTY_] ||
(obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
};
/**
* Whether the given object is alreay assigned a unique ID.
*
* This does not modify the object.
*
* @param {Object} obj The object to check.
* @return {boolean} Whether there an assigned unique id for the object.
*/
goog.hasUid = function(obj) {
return !!obj[goog.UID_PROPERTY_];
};
/**
* Removes the unique ID from an object. This is useful if the object was
* previously mutated using {@code goog.getUid} in which case the mutation is
* undone.
* @param {Object} obj The object to remove the unique ID field from.
*/
goog.removeUid = function(obj) {
// TODO(arv): Make the type stricter, do not accept null.
// In IE, DOM nodes are not instances of Object and throw an exception if we
// try to delete. Instead we try to use removeAttribute.
if ('removeAttribute' in obj) {
obj.removeAttribute(goog.UID_PROPERTY_);
}
/** @preserveTry */
try {
delete obj[goog.UID_PROPERTY_];
} catch (ex) {
}
};
/**
* Name for unique ID property. Initialized in a way to help avoid collisions
* with other closure JavaScript on the same page.
* @type {string}
* @private
*/
goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);
/**
* Counter for UID.
* @type {number}
* @private
*/
goog.uidCounter_ = 0;
/**
* Adds a hash code field to an object. The hash code is unique for the
* given object.
* @param {Object} obj The object to get the hash code for.
* @return {number} The hash code for the object.
* @deprecated Use goog.getUid instead.
*/
goog.getHashCode = goog.getUid;
/**
* Removes the hash code field from an object.
* @param {Object} obj The object to remove the field from.
* @deprecated Use goog.removeUid instead.
*/
goog.removeHashCode = goog.removeUid;
/**
* Clones a value. The input may be an Object, Array, or basic type. Objects and
* arrays will be cloned recursively.
*
* WARNINGS:
* <code>goog.cloneObject</code> does not detect reference loops. Objects that
* refer to themselves will cause infinite recursion.
*
* <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
* UIDs created by <code>getUid</code> into cloned results.
*
* @param {*} obj The value to clone.
* @return {*} A clone of the input value.
* @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
*/
goog.cloneObject = function(obj) {
var type = goog.typeOf(obj);
if (type == 'object' || type == 'array') {
if (obj.clone) {
return obj.clone();
}
var clone = type == 'array' ? [] : {};
for (var key in obj) {
clone[key] = goog.cloneObject(obj[key]);
}
return clone;
}
return obj;
};
/**
* A native implementation of goog.bind.
* @param {Function} fn A function to partially apply.
* @param {Object|undefined} selfObj Specifies the object which this should
* point to when the function is run.
* @param {...*} var_args Additional arguments that are partially applied to the
* function.
* @return {!Function} A partially-applied form of the function bind() was
* invoked as a method of.
* @private
* @suppress {deprecated} The compiler thinks that Function.prototype.bind is
* deprecated because some people have declared a pure-JS version.
* Only the pure-JS version is truly deprecated.
*/
goog.bindNative_ = function(fn, selfObj, var_args) {
return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
};
/**
* A pure-JS implementation of goog.bind.
* @param {Function} fn A function to partially apply.
* @param {Object|undefined} selfObj Specifies the object which this should
* point to when the function is run.
* @param {...*} var_args Additional arguments that are partially applied to the
* function.
* @return {!Function} A partially-applied form of the function bind() was
* invoked as a method of.
* @private
*/
goog.bindJs_ = function(fn, selfObj, var_args) {
if (!fn) {
throw new Error();
}
if (arguments.length > 2) {
var boundArgs = Array.prototype.slice.call(arguments, 2);
return function() {
// Prepend the bound arguments to the current arguments.
var newArgs = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(newArgs, boundArgs);
return fn.apply(selfObj, newArgs);
};
} else {
return function() {
return fn.apply(selfObj, arguments);
};
}
};
/**
* Partially applies this function to a particular 'this object' and zero or
* more arguments. The result is a new function with some arguments of the first
* function pre-filled and the value of this 'pre-specified'.
*
* Remaining arguments specified at call-time are appended to the pre-specified
* ones.
*
* Also see: {@link #partial}.
*
* Usage:
* <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
* barMethBound('arg3', 'arg4');</pre>
*
* @param {?function(this:T, ...)} fn A function to partially apply.
* @param {T} selfObj Specifies the object which this should point to when the
* function is run.
* @param {...*} var_args Additional arguments that are partially applied to the
* function.
* @return {!Function} A partially-applied form of the function bind() was
* invoked as a method of.
* @template T
* @suppress {deprecated} See above.
*/
goog.bind = function(fn, selfObj, var_args) {
// TODO(nicksantos): narrow the type signature.
if (Function.prototype.bind &&
// NOTE(nicksantos): Somebody pulled base.js into the default Chrome
// extension environment. This means that for Chrome extensions, they get
// the implementation of Function.prototype.bind that calls goog.bind
// instead of the native one. Even worse, we don't want to introduce a
// circular dependency between goog.bind and Function.prototype.bind, so
// we have to hack this to make sure it works correctly.
Function.prototype.bind.toString().indexOf('native code') != -1) {
goog.bind = goog.bindNative_;
} else {
goog.bind = goog.bindJs_;
}
return goog.bind.apply(null, arguments);
};
/**
* Like bind(), except that a 'this object' is not required. Useful when the
* target function