1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
16 * @fileoverview Bootstrap for the Google JS Library (Closure).
18 * In uncompiled mode base.js will write out Closure's deps file, unless the
19 * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to
20 * include their own deps file(s) from different locations.
22 * @author arv@google.com (Erik Arvidsson)
29 * @define {boolean} Overridden to true by the compiler when --closure_pass
30 * or --mark_as_compiled is specified.
36 * Base namespace for the Closure library. Checks to see goog is already
37 * defined in the current scope before assigning to prevent clobbering if
38 * base.js is loaded more than once.
42 var goog = goog || {};
46 * Reference to the global context. In most cases this will be 'window'.
52 * A hook for overriding the define values in uncompiled mode.
54 * In uncompiled mode, {@code CLOSURE_UNCOMPILED_DEFINES} may be defined before
55 * loading base.js. If a key is defined in {@code CLOSURE_UNCOMPILED_DEFINES},
56 * {@code goog.define} will use the value instead of the default value. This
57 * allows flags to be overwritten without compilation (this is normally
58 * accomplished with the compiler's "define" flag).
62 * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};
65 * @type {Object<string, (string|number|boolean)>|undefined}
67 goog.global.CLOSURE_UNCOMPILED_DEFINES;
71 * A hook for overriding the define values in uncompiled or compiled mode,
72 * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In
73 * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.
75 * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or
76 * string literals or the compiler will emit an error.
78 * While any @define value may be set, only those set with goog.define will be
79 * effective for uncompiled code.
83 * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;
86 * @type {Object<string, (string|number|boolean)>|undefined}
88 goog.global.CLOSURE_DEFINES;
92 * Returns true if the specified value is not undefined.
93 * WARNING: Do not use this to test if an object has a property. Use the in
96 * @param {?} val Variable to test.
97 * @return {boolean} Whether variable is defined.
99 goog.isDef = function(val) {
100 // void 0 always evaluates to undefined and hence we do not need to depend on
101 // the definition of the global variable named 'undefined'.
102 return val !== void 0;
107 * Builds an object structure for the provided namespace path, ensuring that
108 * names that already exist are not overwritten. For example:
109 * "a.b.c" -> a = {};a.b={};a.b.c={};
110 * Used by goog.provide and goog.exportSymbol.
111 * @param {string} name name of the object that this file defines.
112 * @param {*=} opt_object the object to expose at the end of the path.
113 * @param {Object=} opt_objectToExportTo The object to add the path to; default
117 goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
118 var parts = name.split('.');
119 var cur = opt_objectToExportTo || goog.global;
121 // Internet Explorer exhibits strange behavior when throwing errors from
122 // methods externed in this manner. See the testExportSymbolExceptions in
123 // base_test.html for an example.
124 if (!(parts[0] in cur) && cur.execScript) {
125 cur.execScript('var ' + parts[0]);
128 // Certain browsers cannot parse code in the form for((a in b); c;);
129 // This pattern is produced by the JSCompiler when it collapses the
130 // statement above into the conditional loop below. To prevent this from
131 // happening, use a for-loop and reserve the init logic as below.
133 // Parentheses added to eliminate strict JS warning in Firefox.
134 for (var part; parts.length && (part = parts.shift());) {
135 if (!parts.length && goog.isDef(opt_object)) {
136 // last part and we have an object; use it
137 cur[part] = opt_object;
138 } else if (cur[part]) {
141 cur = cur[part] = {};
148 * Defines a named value. In uncompiled mode, the value is retrieved from
149 * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and
150 * has the property specified, and otherwise used the defined defaultValue.
151 * When compiled the default can be overridden using the compiler
152 * options or the value set in the CLOSURE_DEFINES object.
154 * @param {string} name The distinguished name to provide.
155 * @param {string|number|boolean} defaultValue
157 goog.define = function(name, defaultValue) {
158 var value = defaultValue;
160 if (goog.global.CLOSURE_UNCOMPILED_DEFINES &&
161 Object.prototype.hasOwnProperty.call(
162 goog.global.CLOSURE_UNCOMPILED_DEFINES, name)) {
163 value = goog.global.CLOSURE_UNCOMPILED_DEFINES[name];
164 } else if (goog.global.CLOSURE_DEFINES &&
165 Object.prototype.hasOwnProperty.call(
166 goog.global.CLOSURE_DEFINES, name)) {
167 value = goog.global.CLOSURE_DEFINES[name];
170 goog.exportPath_(name, value);
175 * @define {boolean} DEBUG is provided as a convenience so that debugging code
176 * that should not be included in a production js_binary can be easily stripped
177 * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
178 * toString() methods should be declared inside an "if (goog.DEBUG)" conditional
179 * because they are generally used for debugging purposes and it is difficult
180 * for the JSCompiler to statically determine whether they are used.
182 goog.define('goog.DEBUG', true);
186 * @define {string} LOCALE defines the locale being used for compilation. It is
187 * used to select locale specific data to be compiled in js binary. BUILD rule
188 * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
191 * Take into account that the locale code format is important. You should use
192 * the canonical Unicode format with hyphen as a delimiter. Language must be
193 * lowercase, Language Script - Capitalized, Region - UPPERCASE.
194 * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
196 * See more info about locale codes here:
197 * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
199 * For language codes you should use values defined by ISO 693-1. See it here
200 * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
201 * this rule: the Hebrew language. For legacy reasons the old code (iw) should
202 * be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
204 goog.define('goog.LOCALE', 'en'); // default to en
208 * @define {boolean} Whether this code is running on trusted sites.
210 * On untrusted sites, several native functions can be defined or overridden by
211 * external libraries like Prototype, Datejs, and JQuery and setting this flag
212 * to false forces closure to use its own implementations when possible.
214 * If your JavaScript can be loaded by a third party site and you are wary about
215 * relying on non-standard implementations, specify
216 * "--define goog.TRUSTED_SITE=false" to the JSCompiler.
218 goog.define('goog.TRUSTED_SITE', true);
222 * @define {boolean} Whether a project is expected to be running in strict mode.
224 * This define can be used to trigger alternate implementations compatible with
225 * running in EcmaScript Strict mode or warn about unavailable functionality.
226 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
229 goog.define('goog.STRICT_MODE_COMPATIBLE', false);
233 * @define {boolean} Whether code that calls {@link goog.setTestOnly} should
234 * be disallowed in the compilation unit.
236 goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);
240 * Defines a namespace in Closure.
242 * A namespace may only be defined once in a codebase. It may be defined using
243 * goog.provide() or goog.module().
245 * The presence of one or more goog.provide() calls in a file indicates
246 * that the file defines the given objects/namespaces.
247 * Provided symbols must not be null or undefined.
249 * In addition, goog.provide() creates the object stubs for a namespace
250 * (for example, goog.provide("goog.foo.bar") will create the object
251 * goog.foo.bar if it does not already exist).
253 * Build tools also scan for provide/require/module statements
254 * to discern dependencies, build dependency files (see deps.js), etc.
258 * @param {string} name Namespace provided by this file in the form
259 * "goog.package.part".
261 goog.provide = function(name) {
263 // Ensure that the same namespace isn't provided twice.
264 // A goog.module/goog.provide maps a goog.require to a specific file
265 if (goog.isProvided_(name)) {
266 throw Error('Namespace "' + name + '" already declared.');
270 goog.constructNamespace_(name);
275 * @param {string} name Namespace provided by this file in the form
276 * "goog.package.part".
277 * @param {Object=} opt_obj The object to embed in the namespace.
280 goog.constructNamespace_ = function(name, opt_obj) {
282 delete goog.implicitNamespaces_[name];
284 var namespace = name;
285 while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
286 if (goog.getObjectByName(namespace)) {
289 goog.implicitNamespaces_[namespace] = true;
293 goog.exportPath_(name, opt_obj);
298 * Module identifier validation regexp.
299 * Note: This is a conservative check, it is very possible to be more lenient,
300 * the primary exclusion here is "/" and "\" and a leading ".", these
301 * restrictions are intended to leave the door open for using goog.require
302 * with relative file paths rather than module identifiers.
305 goog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
309 * Defines a module in Closure.
311 * Marks that this file must be loaded as a module and claims the namespace.
313 * A namespace may only be defined once in a codebase. It may be defined using
314 * goog.provide() or goog.module().
316 * goog.module() has three requirements:
317 * - goog.module may not be used in the same file as goog.provide.
318 * - goog.module must be the first statement in the file.
319 * - only one goog.module is allowed per file.
321 * When a goog.module annotated file is loaded, it is enclosed in
322 * a strict function closure. This means that:
323 * - any variables declared in a goog.module file are private to the file
324 * (not global), though the compiler is expected to inline the module.
325 * - The code must obey all the rules of "strict" JavaScript.
326 * - the file will be marked as "use strict"
328 * NOTE: unlike goog.provide, goog.module does not declare any symbols by
329 * itself. If declared symbols are desired, use
330 * goog.module.declareLegacyNamespace().
333 * See the public goog.module proposal: http://goo.gl/Va1hin
335 * @param {string} name Namespace provided by this file in the form
336 * "goog.package.part", is expected but not required.
338 goog.module = function(name) {
339 if (!goog.isString(name) ||
341 name.search(goog.VALID_MODULE_RE_) == -1) {
342 throw Error('Invalid module identifier');
344 if (!goog.isInModuleLoader_()) {
345 throw Error('Module ' + name + ' has been loaded incorrectly.');
347 if (goog.moduleLoaderState_.moduleName) {
348 throw Error('goog.module may only be called once per module.');
351 // Store the module name for the loader.
352 goog.moduleLoaderState_.moduleName = name;
354 // Ensure that the same namespace isn't provided twice.
355 // A goog.module/goog.provide maps a goog.require to a specific file
356 if (goog.isProvided_(name)) {
357 throw Error('Namespace "' + name + '" already declared.');
359 delete goog.implicitNamespaces_[name];
365 * @param {string} name The module identifier.
366 * @return {?} The module exports for an already loaded module or null.
368 * Note: This is not an alternative to goog.require, it does not
369 * indicate a hard dependency, instead it is used to indicate
370 * an optional dependency or to access the exports of a module
371 * that has already been loaded.
372 * @suppress {missingProvide}
374 goog.module.get = function(name) {
375 return goog.module.getInternal_(name);
380 * @param {string} name The module identifier.
381 * @return {?} The module exports for an already loaded module or null.
384 goog.module.getInternal_ = function(name) {
386 if (goog.isProvided_(name)) {
387 // goog.require only return a value with-in goog.module files.
388 return name in goog.loadedModules_ ?
389 goog.loadedModules_[name] :
390 goog.getObjectByName(name);
400 * moduleName: (string|undefined),
401 * declareTestMethods: boolean
404 goog.moduleLoaderState_ = null;
409 * @return {boolean} Whether a goog.module is currently being initialized.
411 goog.isInModuleLoader_ = function() {
412 return goog.moduleLoaderState_ != null;
417 * Indicate that a module's exports that are known test methods should
418 * be copied to the global object. This makes the test methods visible to
419 * test runners that inspect the global object.
421 * TODO(johnlenz): Make the test framework aware of goog.module so
422 * that this isn't necessary. Alternately combine this with goog.setTestOnly
423 * to minimize boiler plate.
424 * @suppress {missingProvide}
426 goog.module.declareTestMethods = function() {
427 if (!goog.isInModuleLoader_()) {
428 throw new Error('goog.module.declareTestMethods must be called from ' +
429 'within a goog.module');
431 goog.moduleLoaderState_.declareTestMethods = true;
436 * Provide the module's exports as a globally accessible object under the
437 * module's declared name. This is intended to ease migration to goog.module
438 * for files that have existing usages.
439 * @suppress {missingProvide}
441 goog.module.declareLegacyNamespace = function() {
442 if (!COMPILED && !goog.isInModuleLoader_()) {
443 throw new Error('goog.module.declareLegacyNamespace must be called from ' +
444 'within a goog.module');
446 if (!COMPILED && !goog.moduleLoaderState_.moduleName) {
447 throw Error('goog.module must be called prior to ' +
448 'goog.module.declareLegacyNamespace.');
450 goog.moduleLoaderState_.declareLegacyNamespace = true;
455 * Marks that the current file should only be used for testing, and never for
456 * live code in production.
458 * In the case of unit tests, the message may optionally be an exact namespace
459 * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra
460 * provide (if not explicitly defined in the code).
462 * @param {string=} opt_message Optional message to add to the error that's
463 * raised when used in production code.
465 goog.setTestOnly = function(opt_message) {
466 if (goog.DISALLOW_TEST_ONLY_CODE) {
467 opt_message = opt_message || '';
468 throw Error('Importing test-only code into non-debug environment' +
469 (opt_message ? ': ' + opt_message : '.'));
475 * Forward declares a symbol. This is an indication to the compiler that the
476 * symbol may be used in the source yet is not required and may not be provided
479 * The most common usage of forward declaration is code that takes a type as a
480 * function parameter but does not need to require it. By forward declaring
481 * instead of requiring, no hard dependency is made, and (if not required
482 * elsewhere) the namespace may never be required and thus, not be pulled
483 * into the JavaScript binary. If it is required elsewhere, it will be type
487 * @param {string} name The namespace to forward declare in the form of
488 * "goog.package.part".
490 goog.forwardDeclare = function(name) {};
496 * Check if the given name has been goog.provided. This will return false for
497 * names that are available only as implicit namespaces.
498 * @param {string} name name of the object to look for.
499 * @return {boolean} Whether the name has been provided.
502 goog.isProvided_ = function(name) {
503 return (name in goog.loadedModules_) ||
504 (!goog.implicitNamespaces_[name] &&
505 goog.isDefAndNotNull(goog.getObjectByName(name)));
509 * Namespaces implicitly defined by goog.provide. For example,
510 * goog.provide('goog.events.Event') implicitly declares that 'goog' and
511 * 'goog.events' must be namespaces.
513 * @type {!Object<string, (boolean|undefined)>}
516 goog.implicitNamespaces_ = {'goog.module': true};
518 // NOTE: We add goog.module as an implicit namespace as goog.module is defined
519 // here and because the existing module package has not been moved yet out of
520 // the goog.module namespace. This satisifies both the debug loader and
521 // ahead-of-time dependency management.
526 * Returns an object based on its fully qualified external name. The object
527 * is not found if null or undefined. If you are using a compilation pass that
528 * renames property names beware that using this function will not find renamed
531 * @param {string} name The fully qualified name.
532 * @param {Object=} opt_obj The object within which to look; default is
534 * @return {?} The value (object or primitive) or, if not found, null.
536 goog.getObjectByName = function(name, opt_obj) {
537 var parts = name.split('.');
538 var cur = opt_obj || goog.global;
539 for (var part; part = parts.shift(); ) {
540 if (goog.isDefAndNotNull(cur[part])) {
551 * Globalizes a whole namespace, such as goog or goog.lang.
553 * @param {!Object} obj The namespace to globalize.
554 * @param {Object=} opt_global The object to add the properties to.
555 * @deprecated Properties may be explicitly exported to the global scope, but
556 * this should no longer be done in bulk.
558 goog.globalize = function(obj, opt_global) {
559 var global = opt_global || goog.global;
567 * Adds a dependency from a file to the files it requires.
568 * @param {string} relPath The path to the js file.
569 * @param {!Array<string>} provides An array of strings with
570 * the names of the objects this file provides.
571 * @param {!Array<string>} requires An array of strings with
572 * the names of the objects this file requires.
573 * @param {boolean=} opt_isModule Whether this dependency must be loaded as
574 * a module as declared by goog.module.
576 goog.addDependency = function(relPath, provides, requires, opt_isModule) {
577 if (goog.DEPENDENCIES_ENABLED) {
578 var provide, require;
579 var path = relPath.replace(/\\/g, '/');
580 var deps = goog.dependencies_;
581 for (var i = 0; provide = provides[i]; i++) {
582 deps.nameToPath[provide] = path;
583 deps.pathIsModule[path] = !!opt_isModule;
585 for (var j = 0; require = requires[j]; j++) {
586 if (!(path in deps.requires)) {
587 deps.requires[path] = {};
589 deps.requires[path][require] = true;
597 // NOTE(nnaze): The debug DOM loader was included in base.js as an original way
598 // to do "debug-mode" development. The dependency system can sometimes be
599 // confusing, as can the debug DOM loader's asynchronous nature.
601 // With the DOM loader, a call to goog.require() is not blocking -- the script
602 // will not load until some point after the current script. If a namespace is
603 // needed at runtime, it needs to be defined in a previous script, or loaded via
604 // require() with its registered dependencies.
605 // User-defined namespaces may need their own deps file. See http://go/js_deps,
606 // http://go/genjsdeps, or, externally, DepsWriter.
607 // https://developers.google.com/closure/library/docs/depswriter
609 // Because of legacy clients, the DOM loader can't be easily removed from
610 // base.js. Work is being done to make it disableable or replaceable for
611 // different environments (DOM-less JavaScript interpreters like Rhino or V8,
612 // for example). See bootstrap/ for more information.
616 * @define {boolean} Whether to enable the debug loader.
618 * If enabled, a call to goog.require() will attempt to load the namespace by
619 * appending a script tag to the DOM (if the namespace has been registered).
621 * If disabled, goog.require() will simply assert that the namespace has been
622 * provided (and depend on the fact that some outside tool correctly ordered
625 goog.define('goog.ENABLE_DEBUG_LOADER', true);
629 * @param {string} msg
632 goog.logToConsole_ = function(msg) {
633 if (goog.global.console) {
634 goog.global.console['error'](msg);
640 * Implements a system for the dynamic resolution of dependencies that works in
641 * parallel with the BUILD system. Note that all calls to goog.require will be
642 * stripped by the JSCompiler when the --closure_pass option is used.
644 * @param {string} name Namespace to include (as was given in goog.provide()) in
645 * the form "goog.package.part".
646 * @return {?} If called within a goog.module file, the associated namespace or
647 * module otherwise null.
649 goog.require = function(name) {
651 // If the object already exists we do not need do do anything.
653 if (goog.ENABLE_DEBUG_LOADER && goog.IS_OLD_IE_) {
654 goog.maybeProcessDeferredDep_(name);
657 if (goog.isProvided_(name)) {
658 if (goog.isInModuleLoader_()) {
659 return goog.module.getInternal_(name);
665 if (goog.ENABLE_DEBUG_LOADER) {
666 var path = goog.getPathFromDeps_(name);
668 goog.included_[path] = true;
669 goog.writeScripts_();
674 var errorMessage = 'goog.require could not find: ' + name;
675 goog.logToConsole_(errorMessage);
677 throw Error(errorMessage);
683 * Path for included scripts.
690 * A hook for overriding the base path.
691 * @type {string|undefined}
693 goog.global.CLOSURE_BASE_PATH;
697 * Whether to write out Closure's deps file. By default, the deps are written.
698 * @type {boolean|undefined}
700 goog.global.CLOSURE_NO_DEPS;
704 * A function to import a single script. This is meant to be overridden when
705 * Closure is being run in non-HTML contexts, such as web workers. It's defined
706 * in the global scope so that it can be set before base.js is loaded, which
707 * allows deps.js to be imported properly.
709 * The function is passed the script source, which is a relative URI. It should
710 * return true if the script was imported, false otherwise.
711 * @type {(function(string): boolean)|undefined}
713 goog.global.CLOSURE_IMPORT_SCRIPT;
717 * Null function used for default values of callbacks, etc.
718 * @return {void} Nothing.
720 goog.nullFunction = function() {};
724 * The identity function. Returns its first argument.
726 * @param {*=} opt_returnValue The single value that will be returned.
727 * @param {...*} var_args Optional trailing arguments. These are ignored.
728 * @return {?} The first argument. We can't know the type -- just pass it along
730 * @deprecated Use goog.functions.identity instead.
732 goog.identityFunction = function(opt_returnValue, var_args) {
733 return opt_returnValue;
738 * When defining a class Foo with an abstract method bar(), you can do:
739 * Foo.prototype.bar = goog.abstractMethod
741 * Now if a subclass of Foo fails to override bar(), an error will be thrown
742 * when bar() is invoked.
744 * Note: This does not take the name of the function to override as an argument
745 * because that would make it more difficult to obfuscate our JavaScript code.
748 * @throws {Error} when invoked to indicate the method should be overridden.
750 goog.abstractMethod = function() {
751 throw Error('unimplemented abstract method');
756 * Adds a {@code getInstance} static method that always returns the same
758 * @param {!Function} ctor The constructor for the class to add the static
761 goog.addSingletonGetter = function(ctor) {
762 ctor.getInstance = function() {
763 if (ctor.instance_) {
764 return ctor.instance_;
767 // NOTE: JSCompiler can't optimize away Array#push.
768 goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;
770 return ctor.instance_ = new ctor;
776 * All singleton classes that have been instantiated, for testing. Don't read
777 * it directly, use the {@code goog.testing.singleton} module. The compiler
778 * removes this variable if unused.
779 * @type {!Array<!Function>}
782 goog.instantiatedSingletons_ = [];
786 * @define {boolean} Whether to load goog.modules using {@code eval} when using
787 * the debug loader. This provides a better debugging experience as the
788 * source is unmodified and can be edited using Chrome Workspaces or similar.
789 * However in some environments the use of {@code eval} is banned
790 * so we provide an alternative.
792 goog.define('goog.LOAD_MODULE_USING_EVAL', true);
796 * @define {boolean} Whether the exports of goog.modules should be sealed when
799 goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);
803 * The registry of initialized modules:
804 * the module identifier to module exports map.
805 * @private @const {!Object<string, ?>}
807 goog.loadedModules_ = {};
811 * True if goog.dependencies_ is available.
814 goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;
817 if (goog.DEPENDENCIES_ENABLED) {
819 * Object used to keep track of urls that have already been added. This record
820 * allows the prevention of circular dependencies.
821 * @private {!Object<string, boolean>}
827 * This object is used to keep track of dependencies and other data that is
828 * used for loading scripts.
831 * pathIsModule: !Object<string, boolean>,
832 * nameToPath: !Object<string, string>,
833 * requires: !Object<string, !Object<string, boolean>>,
834 * visited: !Object<string, boolean>,
835 * written: !Object<string, boolean>,
836 * deferred: !Object<string, string>
839 goog.dependencies_ = {
840 pathIsModule: {}, // 1 to 1
842 nameToPath: {}, // 1 to 1
844 requires: {}, // 1 to many
846 // Used when resolving dependencies to prevent us from visiting file twice.
849 written: {}, // Used to keep track of script files we have written.
851 deferred: {} // Used to track deferred module evaluations in old IEs
856 * Tries to detect whether is in the context of an HTML document.
857 * @return {boolean} True if it looks like HTML document.
860 goog.inHtmlDocument_ = function() {
861 var doc = goog.global.document;
862 return typeof doc != 'undefined' &&
863 'write' in doc; // XULDocument misses write.
868 * Tries to detect the base path of base.js script that bootstraps Closure.
871 goog.findBasePath_ = function() {
872 if (goog.isDef(goog.global.CLOSURE_BASE_PATH)) {
873 goog.basePath = goog.global.CLOSURE_BASE_PATH;
875 } else if (!goog.inHtmlDocument_()) {
878 var doc = goog.global.document;
879 var scripts = doc.getElementsByTagName('SCRIPT');
880 // Search backwards since the current script is in almost all cases the one
882 for (var i = scripts.length - 1; i >= 0; --i) {
883 var script = /** @type {!HTMLScriptElement} */ (scripts[i]);
884 var src = script.src;
885 var qmark = src.lastIndexOf('?');
886 var l = qmark == -1 ? src.length : qmark;
887 if (src.substr(l - 7, 7) == 'base.js') {
888 goog.basePath = src.substr(0, l - 7);
896 * Imports a script if, and only if, that script hasn't already been imported.
897 * (Must be called at execution time)
898 * @param {string} src Script source.
899 * @param {string=} opt_sourceText The optionally source text to evaluate
902 goog.importScript_ = function(src, opt_sourceText) {
903 var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
904 goog.writeScriptTag_;
905 if (importScript(src, opt_sourceText)) {
906 goog.dependencies_.written[src] = true;
911 /** @const @private {boolean} */
912 goog.IS_OLD_IE_ = !!(!goog.global.atob && goog.global.document &&
913 goog.global.document.all);
917 * Given a URL initiate retrieval and execution of the module.
918 * @param {string} src Script source URL.
921 goog.importModule_ = function(src) {
922 // In an attempt to keep browsers from timing out loading scripts using
923 // synchronous XHRs, put each load in its own script block.
924 var bootstrap = 'goog.retrieveAndExecModule_("' + src + '");';
926 if (goog.importScript_('', bootstrap)) {
927 goog.dependencies_.written[src] = true;
932 /** @private {!Array<string>} */
933 goog.queuedModules_ = [];
937 * Return an appropriate module text. Suitable to insert into
938 * a script tag (that is unescaped).
939 * @param {string} srcUrl
940 * @param {string} scriptText
944 goog.wrapModule_ = function(srcUrl, scriptText) {
945 if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {
947 'goog.loadModule(function(exports) {' +
950 '\n' + // terminate any trailing single line comment.
953 '\n//# sourceURL=' + srcUrl + '\n';
957 goog.global.JSON.stringify(
958 scriptText + '\n//# sourceURL=' + srcUrl + '\n') +
963 // On IE9 and earlier, it is necessary to handle
964 // deferred module loads. In later browsers, the
965 // code to be evaluated is simply inserted as a script
966 // block in the correct order. To eval deferred
967 // code at the right time, we piggy back on goog.require to call
968 // goog.maybeProcessDeferredDep_.
970 // The goog.requires are used both to bootstrap
971 // the loading process (when no deps are available) and
972 // declare that they should be available.
974 // Here we eval the sources, if all the deps are available
975 // either already eval'd or goog.require'd. This will
976 // be the case when all the dependencies have already
977 // been loaded, and the dependent module is loaded.
979 // But this alone isn't sufficient because it is also
980 // necessary to handle the case where there is no root
981 // that is not deferred. For that there we register for an event
982 // and trigger goog.loadQueuedModules_ handle any remaining deferred
986 * Handle any remaining deferred goog.module evals.
989 goog.loadQueuedModules_ = function() {
990 var count = goog.queuedModules_.length;
992 var queue = goog.queuedModules_;
993 goog.queuedModules_ = [];
994 for (var i = 0; i < count; i++) {
996 goog.maybeProcessDeferredPath_(path);
1003 * Eval the named module if its dependencies are
1005 * @param {string} name The module to load.
1008 goog.maybeProcessDeferredDep_ = function(name) {
1009 if (goog.isDeferredModule_(name) &&
1010 goog.allDepsAreAvailable_(name)) {
1011 var path = goog.getPathFromDeps_(name);
1012 goog.maybeProcessDeferredPath_(goog.basePath + path);
1017 * @param {string} name The module to check.
1018 * @return {boolean} Whether the name represents a
1019 * module whose evaluation has been deferred.
1022 goog.isDeferredModule_ = function(name) {
1023 var path = goog.getPathFromDeps_(name);
1024 if (path && goog.dependencies_.pathIsModule[path]) {
1025 var abspath = goog.basePath + path;
1026 return (abspath) in goog.dependencies_.deferred;
1032 * @param {string} name The module to check.
1033 * @return {boolean} Whether the name represents a
1034 * module whose declared dependencies have all been loaded
1035 * (eval'd or a deferred module load)
1038 goog.allDepsAreAvailable_ = function(name) {
1039 var path = goog.getPathFromDeps_(name);
1040 if (path && (path in goog.dependencies_.requires)) {
1041 for (var requireName in goog.dependencies_.requires[path]) {
1042 if (!goog.isProvided_(requireName) &&
1043 !goog.isDeferredModule_(requireName)) {
1053 * @param {string} abspath
1056 goog.maybeProcessDeferredPath_ = function(abspath) {
1057 if (abspath in goog.dependencies_.deferred) {
1058 var src = goog.dependencies_.deferred[abspath];
1059 delete goog.dependencies_.deferred[abspath];
1060 goog.globalEval(src);
1066 * @param {function(?):?|string} moduleDef The module definition.
1068 goog.loadModule = function(moduleDef) {
1069 // NOTE: we allow function definitions to be either in the from
1070 // of a string to eval (which keeps the original source intact) or
1071 // in a eval forbidden environment (CSP) we allow a function definition
1072 // which in its body must call {@code goog.module}, and return the exports
1074 var previousState = goog.moduleLoaderState_;
1076 goog.moduleLoaderState_ = {
1077 moduleName: undefined, declareTestMethods: false};
1079 if (goog.isFunction(moduleDef)) {
1080 exports = moduleDef.call(goog.global, {});
1081 } else if (goog.isString(moduleDef)) {
1082 exports = goog.loadModuleFromSource_.call(goog.global, moduleDef);
1084 throw Error('Invalid module definition');
1087 var moduleName = goog.moduleLoaderState_.moduleName;
1088 if (!goog.isString(moduleName) || !moduleName) {
1089 throw Error('Invalid module name \"' + moduleName + '\"');
1092 // Don't seal legacy namespaces as they may be uses as a parent of
1093 // another namespace
1094 if (goog.moduleLoaderState_.declareLegacyNamespace) {
1095 goog.constructNamespace_(moduleName, exports);
1096 } else if (goog.SEAL_MODULE_EXPORTS && Object.seal) {
1097 Object.seal(exports);
1100 goog.loadedModules_[moduleName] = exports;
1101 if (goog.moduleLoaderState_.declareTestMethods) {
1102 for (var entry in exports) {
1103 if (entry.indexOf('test', 0) === 0 ||
1104 entry == 'tearDown' ||
1106 entry == 'setUpPage' ||
1107 entry == 'tearDownPage') {
1108 goog.global[entry] = exports[entry];
1113 goog.moduleLoaderState_ = previousState;
1119 * @param {string} source
1123 goog.loadModuleFromSource_ = function(source) {
1124 // NOTE: we avoid declaring parameters or local variables here to avoid
1125 // masking globals or leaking values into the module definition.
1134 * The default implementation of the import function. Writes a script tag to
1135 * import the script.
1137 * @param {string} src The script url.
1138 * @param {string=} opt_sourceText The optionally source text to evaluate
1139 * @return {boolean} True if the script was imported, false otherwise.
1142 goog.writeScriptTag_ = function(src, opt_sourceText) {
1143 if (goog.inHtmlDocument_()) {
1144 var doc = goog.global.document;
1146 // If the user tries to require a new symbol after document load,
1147 // something has gone terribly wrong. Doing a document.write would
1148 // wipe out the page.
1149 if (doc.readyState == 'complete') {
1150 // Certain test frameworks load base.js multiple times, which tries
1151 // to write deps.js each time. If that happens, just fail silently.
1152 // These frameworks wipe the page between each load of base.js, so this
1154 var isDeps = /\bdeps.js$/.test(src);
1158 throw Error('Cannot write "' + src + '" after document load');
1162 var isOldIE = goog.IS_OLD_IE_;
1164 if (opt_sourceText === undefined) {
1167 '<script type="application/javascript" src="' +
1168 src + '"></' + 'script>');
1170 var state = " onreadystatechange='goog.onScriptLoad_(this, " +
1171 ++goog.lastNonModuleScriptIndex_ + ")' ";
1173 '<script type="application/javascript" src="' +
1174 src + '"' + state + '></' + 'script>');
1178 '<script type="application/javascript">' +
1189 /** @private {number} */
1190 goog.lastNonModuleScriptIndex_ = 0;
1194 * A readystatechange handler for legacy IE
1195 * @param {!HTMLScriptElement} script
1196 * @param {number} scriptIndex
1200 goog.onScriptLoad_ = function(script, scriptIndex) {
1201 // for now load the modules when we reach the last script,
1202 // later allow more inter-mingling.
1203 if (script.readyState == 'complete' &&
1204 goog.lastNonModuleScriptIndex_ == scriptIndex) {
1205 goog.loadQueuedModules_();
1211 * Resolves dependencies based on the dependencies added using addDependency
1212 * and calls importScript_ in the correct order.
1215 goog.writeScripts_ = function() {
1216 /** @type {!Array<string>} The scripts we need to write this time. */
1218 var seenScript = {};
1219 var deps = goog.dependencies_;
1221 /** @param {string} path */
1222 function visitNode(path) {
1223 if (path in deps.written) {
1227 // We have already visited this one. We can get here if we have cyclic
1229 if (path in deps.visited) {
1230 if (!(path in seenScript)) {
1231 seenScript[path] = true;
1237 deps.visited[path] = true;
1239 if (path in deps.requires) {
1240 for (var requireName in deps.requires[path]) {
1241 // If the required name is defined, we assume that it was already
1242 // bootstrapped by other means.
1243 if (!goog.isProvided_(requireName)) {
1244 if (requireName in deps.nameToPath) {
1245 visitNode(deps.nameToPath[requireName]);
1247 throw Error('Undefined nameToPath for ' + requireName);
1253 if (!(path in seenScript)) {
1254 seenScript[path] = true;
1259 for (var path in goog.included_) {
1260 if (!deps.written[path]) {
1265 // record that we are going to load all these scripts.
1266 for (var i = 0; i < scripts.length; i++) {
1267 var path = scripts[i];
1268 goog.dependencies_.written[path] = true;
1271 // If a module is loaded synchronously then we need to
1272 // clear the current inModuleLoader value, and restore it when we are
1273 // done loading the current "requires".
1274 var moduleState = goog.moduleLoaderState_;
1275 goog.moduleLoaderState_ = null;
1277 var loadingModule = false;
1278 for (var i = 0; i < scripts.length; i++) {
1279 var path = scripts[i];
1281 if (!deps.pathIsModule[path]) {
1282 goog.importScript_(goog.basePath + path);
1284 loadingModule = true;
1285 goog.importModule_(goog.basePath + path);
1288 goog.moduleLoaderState_ = moduleState;
1289 throw Error('Undefined script input');
1293 // restore the current "module loading state"
1294 goog.moduleLoaderState_ = moduleState;
1299 * Looks at the dependency rules and tries to determine the script file that
1300 * fulfills a particular rule.
1301 * @param {string} rule In the form goog.namespace.Class or project.script.
1302 * @return {?string} Url corresponding to the rule, or null.
1305 goog.getPathFromDeps_ = function(rule) {
1306 if (rule in goog.dependencies_.nameToPath) {
1307 return goog.dependencies_.nameToPath[rule];
1313 goog.findBasePath_();
1315 // Allow projects to manage the deps files themselves.
1316 if (!goog.global.CLOSURE_NO_DEPS) {
1317 goog.importScript_(goog.basePath + 'deps.js');
1323 * Normalize a file path by removing redundant ".." and extraneous "." file
1325 * @param {string} path
1329 goog.normalizePath_ = function(path) {
1330 var components = path.split('/');
1332 while (i < components.length) {
1333 if (components[i] == '.') {
1334 components.splice(i, 1);
1335 } else if (i && components[i] == '..' &&
1336 components[i - 1] && components[i - 1] != '..') {
1337 components.splice(--i, 2);
1342 return components.join('/');
1347 * Retrieve and execute a module.
1348 * @param {string} src Script source URL.
1351 goog.retrieveAndExecModule_ = function(src) {
1353 // The full but non-canonicalized URL for later use.
1354 var originalPath = src;
1355 // Canonicalize the path, removing any /./ or /../ since Chrome's debugging
1356 // console doesn't auto-canonicalize XHR loads as it does <script> srcs.
1357 src = goog.normalizePath_(src);
1359 var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
1360 goog.writeScriptTag_;
1362 var scriptText = null;
1364 var xhr = new goog.global['XMLHttpRequest']();
1366 /** @this {Object} */
1367 xhr.onload = function() {
1368 scriptText = this.responseText;
1370 xhr.open('get', src, false);
1373 scriptText = xhr.responseText;
1375 if (scriptText != null) {
1376 var execModuleScript = goog.wrapModule_(src, scriptText);
1377 var isOldIE = goog.IS_OLD_IE_;
1379 goog.dependencies_.deferred[originalPath] = execModuleScript;
1380 goog.queuedModules_.push(originalPath);
1382 importScript(src, execModuleScript);
1385 throw new Error('load of ' + src + 'failed');
1391 //==============================================================================
1392 // Language Enhancements
1393 //==============================================================================
1397 * This is a "fixed" version of the typeof operator. It differs from the typeof
1398 * operator in such a way that null returns 'null' and arrays return 'array'.
1399 * @param {*} value The value to get the type of.
1400 * @return {string} The name of the type.
1402 goog.typeOf = function(value) {
1403 var s = typeof value;
1404 if (s == 'object') {
1406 // Check these first, so we can avoid calling Object.prototype.toString if
1409 // IE improperly marshals tyepof across execution contexts, but a
1410 // cross-context object will still return false for "instanceof Object".
1411 if (value instanceof Array) {
1413 } else if (value instanceof Object) {
1417 // HACK: In order to use an Object prototype method on the arbitrary
1418 // value, the compiler requires the value be cast to type Object,
1419 // even though the ECMA spec explicitly allows it.
1420 var className = Object.prototype.toString.call(
1421 /** @type {Object} */ (value));
1422 // In Firefox 3.6, attempting to access iframe window objects' length
1423 // property throws an NS_ERROR_FAILURE, so we need to special-case it
1425 if (className == '[object Window]') {
1429 // We cannot always use constructor == Array or instanceof Array because
1430 // different frames have different Array objects. In IE6, if the iframe
1431 // where the array was created is destroyed, the array loses its
1432 // prototype. Then dereferencing val.splice here throws an exception, so
1433 // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
1434 // so that will work. In this case, this function will return false and
1435 // most array functions will still work because the array is still
1436 // array-like (supports length and []) even though it has lost its
1438 // Mark Miller noticed that Object.prototype.toString
1439 // allows access to the unforgeable [[Class]] property.
1440 // 15.2.4.2 Object.prototype.toString ( )
1441 // When the toString method is called, the following steps are taken:
1442 // 1. Get the [[Class]] property of this object.
1443 // 2. Compute a string value by concatenating the three strings
1444 // "[object ", Result(1), and "]".
1445 // 3. Return Result(2).
1446 // and this behavior survives the destruction of the execution context.
1447 if ((className == '[object Array]' ||
1448 // In IE all non value types are wrapped as objects across window
1449 // boundaries (not iframe though) so we have to do object detection
1450 // for this edge case.
1451 typeof value.length == 'number' &&
1452 typeof value.splice != 'undefined' &&
1453 typeof value.propertyIsEnumerable != 'undefined' &&
1454 !value.propertyIsEnumerable('splice')
1459 // HACK: There is still an array case that fails.
1460 // function ArrayImpostor() {}
1461 // ArrayImpostor.prototype = [];
1462 // var impostor = new ArrayImpostor;
1463 // this can be fixed by getting rid of the fast path
1464 // (value instanceof Array) and solely relying on
1465 // (value && Object.prototype.toString.vall(value) === '[object Array]')
1466 // but that would require many more function calls and is not warranted
1467 // unless closure code is receiving objects from untrusted sources.
1469 // IE in cross-window calls does not correctly marshal the function type
1470 // (it appears just as an object) so we cannot use just typeof val ==
1471 // 'function'. However, if the object has a call property, it is a
1473 if ((className == '[object Function]' ||
1474 typeof value.call != 'undefined' &&
1475 typeof value.propertyIsEnumerable != 'undefined' &&
1476 !value.propertyIsEnumerable('call'))) {
1484 } else if (s == 'function' && typeof value.call == 'undefined') {
1485 // In Safari typeof nodeList returns 'function', and on Firefox typeof
1486 // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We
1487 // would like to return object for those and we can detect an invalid
1488 // function by making sure that the function object has a call method.
1496 * Returns true if the specified value is null.
1497 * @param {?} val Variable to test.
1498 * @return {boolean} Whether variable is null.
1500 goog.isNull = function(val) {
1501 return val === null;
1506 * Returns true if the specified value is defined and not null.
1507 * @param {?} val Variable to test.
1508 * @return {boolean} Whether variable is defined and not null.
1510 goog.isDefAndNotNull = function(val) {
1511 // Note that undefined == null.
1517 * Returns true if the specified value is an array.
1518 * @param {?} val Variable to test.
1519 * @return {boolean} Whether variable is an array.
1521 goog.isArray = function(val) {
1522 return goog.typeOf(val) == 'array';
1527 * Returns true if the object looks like an array. To qualify as array like
1528 * the value needs to be either a NodeList or an object with a Number length
1529 * property. As a special case, a function value is not array like, because its
1530 * length property is fixed to correspond to the number of expected arguments.
1531 * @param {?} val Variable to test.
1532 * @return {boolean} Whether variable is an array.
1534 goog.isArrayLike = function(val) {
1535 var type = goog.typeOf(val);
1536 // We do not use goog.isObject here in order to exclude function values.
1537 return type == 'array' || type == 'object' && typeof val.length == 'number';
1542 * Returns true if the object looks like a Date. To qualify as Date-like the
1543 * value needs to be an object and have a getFullYear() function.
1544 * @param {?} val Variable to test.
1545 * @return {boolean} Whether variable is a like a Date.
1547 goog.isDateLike = function(val) {
1548 return goog.isObject(val) && typeof val.getFullYear == 'function';
1553 * Returns true if the specified value is a string.
1554 * @param {?} val Variable to test.
1555 * @return {boolean} Whether variable is a string.
1557 goog.isString = function(val) {
1558 return typeof val == 'string';
1563 * Returns true if the specified value is a boolean.
1564 * @param {?} val Variable to test.
1565 * @return {boolean} Whether variable is boolean.
1567 goog.isBoolean = function(val) {
1568 return typeof val == 'boolean';
1573 * Returns true if the specified value is a number.
1574 * @param {?} val Variable to test.
1575 * @return {boolean} Whether variable is a number.
1577 goog.isNumber = function(val) {
1578 return typeof val == 'number';
1583 * Returns true if the specified value is a function.
1584 * @param {?} val Variable to test.
1585 * @return {boolean} Whether variable is a function.
1587 goog.isFunction = function(val) {
1588 return goog.typeOf(val) == 'function';
1593 * Returns true if the specified value is an object. This includes arrays and
1595 * @param {?} val Variable to test.
1596 * @return {boolean} Whether variable is an object.
1598 goog.isObject = function(val) {
1599 var type = typeof val;
1600 return type == 'object' && val != null || type == 'function';
1601 // return Object(val) === val also works, but is slower, especially if val is
1607 * Gets a unique ID for an object. This mutates the object so that further calls
1608 * with the same object as a parameter returns the same value. The unique ID is
1609 * guaranteed to be unique across the current session amongst objects that are
1610 * passed into {@code getUid}. There is no guarantee that the ID is unique or
1611 * consistent across sessions. It is unsafe to generate unique ID for function
1614 * @param {Object} obj The object to get the unique ID for.
1615 * @return {number} The unique ID for the object.
1617 goog.getUid = function(obj) {
1618 // TODO(arv): Make the type stricter, do not accept null.
1620 // In Opera window.hasOwnProperty exists but always returns false so we avoid
1621 // using it. As a consequence the unique ID generated for BaseClass.prototype
1622 // and SubClass.prototype will be the same.
1623 return obj[goog.UID_PROPERTY_] ||
1624 (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
1629 * Whether the given object is already assigned a unique ID.
1631 * This does not modify the object.
1633 * @param {!Object} obj The object to check.
1634 * @return {boolean} Whether there is an assigned unique id for the object.
1636 goog.hasUid = function(obj) {
1637 return !!obj[goog.UID_PROPERTY_];
1642 * Removes the unique ID from an object. This is useful if the object was
1643 * previously mutated using {@code goog.getUid} in which case the mutation is
1645 * @param {Object} obj The object to remove the unique ID field from.
1647 goog.removeUid = function(obj) {
1648 // TODO(arv): Make the type stricter, do not accept null.
1650 // In IE, DOM nodes are not instances of Object and throw an exception if we
1651 // try to delete. Instead we try to use removeAttribute.
1652 if ('removeAttribute' in obj) {
1653 obj.removeAttribute(goog.UID_PROPERTY_);
1657 delete obj[goog.UID_PROPERTY_];
1664 * Name for unique ID property. Initialized in a way to help avoid collisions
1665 * with other closure JavaScript on the same page.
1669 goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);
1677 goog.uidCounter_ = 0;
1681 * Adds a hash code field to an object. The hash code is unique for the
1683 * @param {Object} obj The object to get the hash code for.
1684 * @return {number} The hash code for the object.
1685 * @deprecated Use goog.getUid instead.
1687 goog.getHashCode = goog.getUid;
1691 * Removes the hash code field from an object.
1692 * @param {Object} obj The object to remove the field from.
1693 * @deprecated Use goog.removeUid instead.
1695 goog.removeHashCode = goog.removeUid;
1699 * Clones a value. The input may be an Object, Array, or basic type. Objects and
1700 * arrays will be cloned recursively.
1703 * <code>goog.cloneObject</code> does not detect reference loops. Objects that
1704 * refer to themselves will cause infinite recursion.
1706 * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
1707 * UIDs created by <code>getUid</code> into cloned results.
1709 * @param {*} obj The value to clone.
1710 * @return {*} A clone of the input value.
1711 * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
1713 goog.cloneObject = function(obj) {
1714 var type = goog.typeOf(obj);
1715 if (type == 'object' || type == 'array') {
1719 var clone = type == 'array' ? [] : {};
1720 for (var key in obj) {
1721 clone[key] = goog.cloneObject(obj[key]);
1731 * A native implementation of goog.bind.
1732 * @param {Function} fn A function to partially apply.
1733 * @param {Object|undefined} selfObj Specifies the object which this should
1734 * point to when the function is run.
1735 * @param {...*} var_args Additional arguments that are partially applied to the
1737 * @return {!Function} A partially-applied form of the function bind() was
1738 * invoked as a method of.
1740 * @suppress {deprecated} The compiler thinks that Function.prototype.bind is
1741 * deprecated because some people have declared a pure-JS version.
1742 * Only the pure-JS version is truly deprecated.
1744 goog.bindNative_ = function(fn, selfObj, var_args) {
1745 return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
1750 * A pure-JS implementation of goog.bind.
1751 * @param {Function} fn A function to partially apply.
1752 * @param {Object|undefined} selfObj Specifies the object which this should
1753 * point to when the function is run.
1754 * @param {...*} var_args Additional arguments that are partially applied to the
1756 * @return {!Function} A partially-applied form of the function bind() was
1757 * invoked as a method of.
1760 goog.bindJs_ = function(fn, selfObj, var_args) {
1765 if (arguments.length > 2) {
1766 var boundArgs = Array.prototype.slice.call(arguments, 2);
1768 // Prepend the bound arguments to the current arguments.
1769 var newArgs = Array.prototype.slice.call(arguments);
1770 Array.prototype.unshift.apply(newArgs, boundArgs);
1771 return fn.apply(selfObj, newArgs);
1776 return fn.apply(selfObj, arguments);
1783 * Partially applies this function to a particular 'this object' and zero or
1784 * more arguments. The result is a new function with some arguments of the first
1785 * function pre-filled and the value of this 'pre-specified'.
1787 * Remaining arguments specified at call-time are appended to the pre-specified
1790 * Also see: {@link #partial}.
1793 * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
1794 * barMethBound('arg3', 'arg4');</pre>
1796 * @param {?function(this:T, ...)} fn A function to partially apply.
1797 * @param {T} selfObj Specifies the object which this should point to when the
1799 * @param {...*} var_args Additional arguments that are partially applied to the
1801 * @return {!Function} A partially-applied form of the function bind() was
1802 * invoked as a method of.
1804 * @suppress {deprecated} See above.
1806 goog.bind = function(fn, selfObj, var_args) {
1807 // TODO(nicksantos): narrow the type signature.
1808 if (Function.prototype.bind &&
1809 // NOTE(nicksantos): Somebody pulled base.js into the default Chrome
1810 // extension environment. This means that for Chrome extensions, they get
1811 // the implementation of Function.prototype.bind that calls goog.bind
1812 // instead of the native one. Even worse, we don't want to introduce a
1813 // circular dependency between goog.bind and Function.prototype.bind, so
1814 // we have to hack this to make sure it works correctly.
1815 Function.prototype.bind.toString().indexOf('native code') != -1) {
1816 goog.bind = goog.bindNative_;
1818 goog.bind = goog.bindJs_;
1820 return goog.bind.apply(null, arguments);
1825 * Like bind(), except that a 'this object' is not required. Useful when the
1826 * target function is already bound.
1829 * var g = partial(f, arg1, arg2);
1832 * @param {Function} fn A function to partially apply.
1833 * @param {...*} var_args Additional arguments that are partially applied to fn.
1834 * @return {!Function} A partially-applied form of the function bind() was
1835 * invoked as a method of.
1837 goog.partial = function(fn, var_args) {
1838 var args = Array.prototype.slice.call(arguments, 1);
1840 // Clone the array (with slice()) and append additional arguments
1841 // to the existing arguments.
1842 var newArgs = args.slice();
1843 newArgs.push.apply(newArgs, arguments);
1844 return fn.apply(this, newArgs);
1850 * Copies all the members of a source object to a target object. This method
1851 * does not work on all browsers for all objects that contain keys such as
1852 * toString or hasOwnProperty. Use goog.object.extend for this purpose.
1853 * @param {Object} target Target.
1854 * @param {Object} source Source.
1856 goog.mixin = function(target, source) {
1857 for (var x in source) {
1858 target[x] = source[x];
1861 // For IE7 or lower, the for-in-loop does not contain any properties that are
1862 // not enumerable on the prototype object (for example, isPrototypeOf from
1863 // Object.prototype) but also it will not include 'replace' on objects that
1864 // extend String and change 'replace' (not that it is common for anyone to
1865 // extend anything except Object).
1870 * @return {number} An integer value representing the number of milliseconds
1871 * between midnight, January 1, 1970 and the current time.
1873 goog.now = (goog.TRUSTED_SITE && Date.now) || (function() {
1874 // Unary plus operator converts its operand to a number which in the case of
1875 // a date is done by calling getTime().
1881 * Evals JavaScript in the global scope. In IE this uses execScript, other
1882 * browsers use goog.global.eval. If goog.global.eval does not evaluate in the
1883 * global scope (for example, in Safari), appends a script tag instead.
1884 * Throws an exception if neither execScript or eval is defined.
1885 * @param {string} script JavaScript string.
1887 goog.globalEval = function(script) {
1888 if (goog.global.execScript) {
1889 goog.global.execScript(script, 'JavaScript');
1890 } else if (goog.global.eval) {
1891 // Test to see if eval works
1892 if (goog.evalWorksForGlobals_ == null) {
1893 goog.global.eval('var _et_ = 1;');
1894 if (typeof goog.global['_et_'] != 'undefined') {
1895 delete goog.global['_et_'];
1896 goog.evalWorksForGlobals_ = true;
1898 goog.evalWorksForGlobals_ = false;
1902 if (goog.evalWorksForGlobals_) {
1903 goog.global.eval(script);
1905 var doc = goog.global.document;
1906 var scriptElt = doc.createElement('SCRIPT');
1907 scriptElt.type = 'application/javascript';
1908 scriptElt.defer = false;
1909 // Note(user): can't use .innerHTML since "t('<test>')" will fail and
1910 // .text doesn't work in Safari 2. Therefore we append a text node.
1911 scriptElt.appendChild(doc.createTextNode(script));
1912 doc.body.appendChild(scriptElt);
1913 doc.body.removeChild(scriptElt);
1916 throw Error('goog.globalEval not available');
1922 * Indicates whether or not we can call 'eval' directly to eval code in the
1923 * global scope. Set to a Boolean by the first call to goog.globalEval (which
1924 * empirically tests whether eval works for globals). @see goog.globalEval
1928 goog.evalWorksForGlobals_ = null;
1932 * Optional map of CSS class names to obfuscated names used with
1933 * goog.getCssName().
1934 * @private {!Object<string, string>|undefined}
1935 * @see goog.setCssNameMapping
1937 goog.cssNameMapping_;
1941 * Optional obfuscation style for CSS class names. Should be set to either
1942 * 'BY_WHOLE' or 'BY_PART' if defined.
1943 * @type {string|undefined}
1945 * @see goog.setCssNameMapping
1947 goog.cssNameMappingStyle_;
1951 * Handles strings that are intended to be used as CSS class names.
1953 * This function works in tandem with @see goog.setCssNameMapping.
1955 * Without any mapping set, the arguments are simple joined with a hyphen and
1956 * passed through unaltered.
1958 * When there is a mapping, there are two possible styles in which these
1959 * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)
1960 * of the passed in css name is rewritten according to the map. In the BY_WHOLE
1961 * style, the full css name is looked up in the map directly. If a rewrite is
1962 * not specified by the map, the compiler will output a warning.
1964 * When the mapping is passed to the compiler, it will replace calls to
1965 * goog.getCssName with the strings from the mapping, e.g.
1966 * var x = goog.getCssName('foo');
1967 * var y = goog.getCssName(this.baseClass, 'active');
1970 * var y = this.baseClass + '-active';
1972 * If one argument is passed it will be processed, if two are passed only the
1973 * modifier will be processed, as it is assumed the first argument was generated
1974 * as a result of calling goog.getCssName.
1976 * @param {string} className The class name.
1977 * @param {string=} opt_modifier A modifier to be appended to the class name.
1978 * @return {string} The class name or the concatenation of the class name and
1981 goog.getCssName = function(className, opt_modifier) {
1982 var getMapping = function(cssName) {
1983 return goog.cssNameMapping_[cssName] || cssName;
1986 var renameByParts = function(cssName) {
1987 // Remap all the parts individually.
1988 var parts = cssName.split('-');
1990 for (var i = 0; i < parts.length; i++) {
1991 mapped.push(getMapping(parts[i]));
1993 return mapped.join('-');
1997 if (goog.cssNameMapping_) {
1998 rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ?
1999 getMapping : renameByParts;
2001 rename = function(a) {
2007 return className + '-' + rename(opt_modifier);
2009 return rename(className);
2015 * Sets the map to check when returning a value from goog.getCssName(). Example:
2017 * goog.setCssNameMapping({
2022 * var x = goog.getCssName('goog');
2023 * // The following evaluates to: "a a-b".
2024 * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')
2026 * When declared as a map of string literals to string literals, the JSCompiler
2027 * will replace all calls to goog.getCssName() using the supplied map if the
2028 * --closure_pass flag is set.
2030 * @param {!Object} mapping A map of strings to strings where keys are possible
2031 * arguments to goog.getCssName() and values are the corresponding values
2032 * that should be returned.
2033 * @param {string=} opt_style The style of css name mapping. There are two valid
2034 * options: 'BY_PART', and 'BY_WHOLE'.
2035 * @see goog.getCssName for a description.
2037 goog.setCssNameMapping = function(mapping, opt_style) {
2038 goog.cssNameMapping_ = mapping;
2039 goog.cssNameMappingStyle_ = opt_style;
2044 * To use CSS renaming in compiled mode, one of the input files should have a
2045 * call to goog.setCssNameMapping() with an object literal that the JSCompiler
2046 * can extract and use to replace all calls to goog.getCssName(). In uncompiled
2047 * mode, JavaScript code should be loaded before this base.js file that declares
2048 * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is
2049 * to ensure that the mapping is loaded before any calls to goog.getCssName()
2050 * are made in uncompiled mode.
2052 * A hook for overriding the CSS name mapping.
2053 * @type {!Object<string, string>|undefined}
2055 goog.global.CLOSURE_CSS_NAME_MAPPING;
2058 if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {
2059 // This does not call goog.setCssNameMapping() because the JSCompiler
2060 // requires that goog.setCssNameMapping() be called with an object literal.
2061 goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;
2066 * Gets a localized message.
2068 * This function is a compiler primitive. If you give the compiler a localized
2069 * message bundle, it will replace the string at compile-time with a localized
2070 * version, and expand goog.getMsg call to a concatenated string.
2072 * Messages must be initialized in the form:
2074 * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});
2077 * @param {string} str Translatable string, places holders in the form {$foo}.
2078 * @param {Object<string, string>=} opt_values Maps place holder name to value.
2079 * @return {string} message with placeholders filled.
2081 goog.getMsg = function(str, opt_values) {
2083 str = str.replace(/\{\$([^}]+)}/g, function(match, key) {
2084 return key in opt_values ? opt_values[key] : match;
2092 * Gets a localized message. If the message does not have a translation, gives a
2095 * This is useful when introducing a new message that has not yet been
2096 * translated into all languages.
2098 * This function is a compiler primitive. Must be used in the form:
2099 * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>
2100 * where MSG_A and MSG_B were initialized with goog.getMsg.
2102 * @param {string} a The preferred message.
2103 * @param {string} b The fallback message.
2104 * @return {string} The best translated message.
2106 goog.getMsgWithFallback = function(a, b) {
2112 * Exposes an unobfuscated global namespace path for the given object.
2113 * Note that fields of the exported object *will* be obfuscated, unless they are
2114 * exported in turn via this function or goog.exportProperty.
2116 * Also handy for making public items that are defined in anonymous closures.
2118 * ex. goog.exportSymbol('public.path.Foo', Foo);
2120 * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);
2121 * public.path.Foo.staticFunction();
2123 * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',
2124 * Foo.prototype.myMethod);
2125 * new public.path.Foo().myMethod();
2127 * @param {string} publicPath Unobfuscated name to export.
2128 * @param {*} object Object the name should point to.
2129 * @param {Object=} opt_objectToExportTo The object to add the path to; default
2132 goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
2133 goog.exportPath_(publicPath, object, opt_objectToExportTo);
2138 * Exports a property unobfuscated into the object's namespace.
2139 * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);
2140 * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);
2141 * @param {Object} object Object whose static property is being exported.
2142 * @param {string} publicName Unobfuscated name to export.
2143 * @param {*} symbol Object the name should point to.
2145 goog.exportProperty = function(object, publicName, symbol) {
2146 object[publicName] = symbol;
2151 * Inherit the prototype methods from one constructor into another.
2155 * function ParentClass(a, b) { }
2156 * ParentClass.prototype.foo = function(a) { };
2158 * function ChildClass(a, b, c) {
2159 * ChildClass.base(this, 'constructor', a, b);
2161 * goog.inherits(ChildClass, ParentClass);
2163 * var child = new ChildClass('a', 'b', 'see');
2164 * child.foo(); // This works.
2167 * @param {Function} childCtor Child class.
2168 * @param {Function} parentCtor Parent class.
2170 goog.inherits = function(childCtor, parentCtor) {
2172 function tempCtor() {};
2173 tempCtor.prototype = parentCtor.prototype;
2174 childCtor.superClass_ = parentCtor.prototype;
2175 childCtor.prototype = new tempCtor();
2177 childCtor.prototype.constructor = childCtor;
2180 * Calls superclass constructor/method.
2182 * This function is only available if you use goog.inherits to
2183 * express inheritance relationships between classes.
2185 * NOTE: This is a replacement for goog.base and for superClass_
2186 * property defined in childCtor.
2188 * @param {!Object} me Should always be "this".
2189 * @param {string} methodName The method name to call. Calling
2190 * superclass constructor can be done with the special string
2192 * @param {...*} var_args The arguments to pass to superclass
2193 * method/constructor.
2194 * @return {*} The return value of the superclass method/constructor.
2196 childCtor.base = function(me, methodName, var_args) {
2197 // Copying using loop to avoid deop due to passing arguments object to
2198 // function. This is faster in many JS engines as of late 2014.
2199 var args = new Array(arguments.length - 2);
2200 for (var i = 2; i < arguments.length; i++) {
2201 args[i - 2] = arguments[i];
2203 return parentCtor.prototype[methodName].apply(me, args);
2209 * Call up to the superclass.
2211 * If this is called from a constructor, then this calls the superclass
2212 * constructor with arguments 1-N.
2214 * If this is called from a prototype method, then you must pass the name of the
2215 * method as the second argument to this function. If you do not, you will get a
2216 * runtime error. This calls the superclass' method with arguments 2-N.
2218 * This function only works if you use goog.inherits to express inheritance
2219 * relationships between your classes.
2221 * This function is a compiler primitive. At compile-time, the compiler will do
2222 * macro expansion to remove a lot of the extra overhead that this function
2223 * introduces. The compiler will also enforce a lot of the assumptions that this
2224 * function makes, and treat it as a compiler error if you break them.
2226 * @param {!Object} me Should always be "this".
2227 * @param {*=} opt_methodName The method name if calling a super method.
2228 * @param {...*} var_args The rest of the arguments.
2229 * @return {*} The return value of the superclass method.
2230 * @suppress {es5Strict} This method can not be used in strict mode, but
2231 * all Closure Library consumers must depend on this file.
2233 goog.base = function(me, opt_methodName, var_args) {
2234 var caller = arguments.callee.caller;
2236 if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {
2237 throw Error('arguments.caller not defined. goog.base() cannot be used ' +
2238 'with strict mode code. See ' +
2239 'http://www.ecma-international.org/ecma-262/5.1/#sec-C');
2242 if (caller.superClass_) {
2243 // Copying using loop to avoid deop due to passing arguments object to
2244 // function. This is faster in many JS engines as of late 2014.
2245 var ctorArgs = new Array(arguments.length - 1);
2246 for (var i = 1; i < arguments.length; i++) {
2247 ctorArgs[i - 1] = arguments[i];
2249 // This is a constructor. Call the superclass constructor.
2250 return caller.superClass_.constructor.apply(me, ctorArgs);
2253 // Copying using loop to avoid deop due to passing arguments object to
2254 // function. This is faster in many JS engines as of late 2014.
2255 var args = new Array(arguments.length - 2);
2256 for (var i = 2; i < arguments.length; i++) {
2257 args[i - 2] = arguments[i];
2259 var foundCaller = false;
2260 for (var ctor = me.constructor;
2261 ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
2262 if (ctor.prototype[opt_methodName] === caller) {
2264 } else if (foundCaller) {
2265 return ctor.prototype[opt_methodName].apply(me, args);
2269 // If we did not find the caller in the prototype chain, then one of two
2271 // 1) The caller is an instance method.
2272 // 2) This method was not called by the right caller.
2273 if (me[opt_methodName] === caller) {
2274 return me.constructor.prototype[opt_methodName].apply(me, args);
2277 'goog.base called from a method of one name ' +
2278 'to a method of a different name');
2284 * Allow for aliasing within scope functions. This function exists for
2285 * uncompiled code - in compiled code the calls will be inlined and the aliases
2286 * applied. In uncompiled code the function is simply run since the aliases as
2287 * written are valid JavaScript.
2290 * @param {function()} fn Function to call. This function can contain aliases
2291 * to namespaces (e.g. "var dom = goog.dom") or classes
2292 * (e.g. "var Timer = goog.Timer").
2294 goog.scope = function(fn) {
2295 fn.call(goog.global);
2300 * To support uncompiled, strict mode bundles that use eval to divide source
2302 * eval('someSource;//# sourceUrl sourcefile.js');
2303 * We need to export the globally defined symbols "goog" and "COMPILED".
2304 * Exporting "goog" breaks the compiler optimizations, so we required that
2305 * be defined externally.
2306 * NOTE: We don't use goog.exportSymbol here because we don't want to trigger
2307 * extern generation when that compiler option is enabled.
2310 goog.global['COMPILED'] = COMPILED;
2315 //==============================================================================
2316 // goog.defineClass implementation
2317 //==============================================================================
2321 * Creates a restricted form of a Closure "class":
2322 * - from the compiler's perspective, the instance returned from the
2323 * constructor is sealed (no new properties may be added). This enables
2325 * - the compiler will rewrite this definition to a form that is optimal
2326 * for type checking and optimization (initially this will be a more
2327 * traditional form).
2329 * @param {Function} superClass The superclass, Object or null.
2330 * @param {goog.defineClass.ClassDescriptor} def
2331 * An object literal describing
2332 * the class. It may have the following properties:
2333 * "constructor": the constructor function
2334 * "statics": an object literal containing methods to add to the constructor
2335 * as "static" methods or a function that will receive the constructor
2336 * function as its only parameter to which static properties can
2338 * all other properties are added to the prototype.
2339 * @return {!Function} The class constructor.
2341 goog.defineClass = function(superClass, def) {
2342 // TODO(johnlenz): consider making the superClass an optional parameter.
2343 var constructor = def.constructor;
2344 var statics = def.statics;
2345 // Wrap the constructor prior to setting up the prototype and static methods.
2346 if (!constructor || constructor == Object.prototype.constructor) {
2347 constructor = function() {
2348 throw Error('cannot instantiate an interface (no constructor defined).');
2352 var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);
2354 goog.inherits(cls, superClass);
2357 // Remove all the properties that should not be copied to the prototype.
2358 delete def.constructor;
2361 goog.defineClass.applyProperties_(cls.prototype, def);
2362 if (statics != null) {
2363 if (statics instanceof Function) {
2366 goog.defineClass.applyProperties_(cls, statics);
2377 * {constructor:!Function}|
2378 * {constructor:!Function, statics:(Object|function(Function):void)}}
2379 * @suppress {missingProvide}
2381 goog.defineClass.ClassDescriptor;
2385 * @define {boolean} Whether the instances returned by
2386 * goog.defineClass should be sealed when possible.
2388 goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);
2392 * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is
2393 * defined, this function will wrap the constructor in a function that seals the
2394 * results of the provided constructor function.
2396 * @param {!Function} ctr The constructor whose results maybe be sealed.
2397 * @param {Function} superClass The superclass constructor.
2398 * @return {!Function} The replacement constructor.
2401 goog.defineClass.createSealingConstructor_ = function(ctr, superClass) {
2402 if (goog.defineClass.SEAL_CLASS_INSTANCES &&
2403 Object.seal instanceof Function) {
2404 // Don't seal subclasses of unsealable-tagged legacy classes.
2405 if (superClass && superClass.prototype &&
2406 superClass.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]) {
2413 var wrappedCtr = function() {
2414 // Don't seal an instance of a subclass when it calls the constructor of
2415 // its super class as there is most likely still setup to do.
2416 var instance = ctr.apply(this, arguments) || this;
2417 instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];
2418 if (this.constructor === wrappedCtr) {
2419 Object.seal(instance);
2429 // TODO(johnlenz): share these values with the goog.object
2431 * The names of the fields that are defined on Object.prototype.
2432 * @type {!Array<string>}
2436 goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [
2440 'propertyIsEnumerable',
2447 // TODO(johnlenz): share this function with the goog.object
2449 * @param {!Object} target The object to add properties to.
2450 * @param {!Object} source The object to copy properties from.
2453 goog.defineClass.applyProperties_ = function(target, source) {
2454 // TODO(johnlenz): update this to support ES5 getters/setters
2457 for (key in source) {
2458 if (Object.prototype.hasOwnProperty.call(source, key)) {
2459 target[key] = source[key];
2463 // For IE the for-in-loop does not contain any properties that are not
2464 // enumerable on the prototype object (for example isPrototypeOf from
2465 // Object.prototype) and it will also not include 'replace' on objects that
2466 // extend String and change 'replace' (not that it is common for anyone to
2467 // extend anything except Object).
2468 for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {
2469 key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];
2470 if (Object.prototype.hasOwnProperty.call(source, key)) {
2471 target[key] = source[key];
2478 * Sealing classes breaks the older idiom of assigning properties on the
2479 * prototype rather than in the constructor. As such, goog.defineClass
2480 * must not seal subclasses of these old-style classes until they are fixed.
2481 * Until then, this marks a class as "broken", instructing defineClass
2482 * not to seal subclasses.
2483 * @param {!Function} ctr The legacy constructor to tag as unsealable.
2485 goog.tagUnsealableClass = function(ctr) {
2486 if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {
2487 ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;
2493 * Name for unsealable tag property.
2494 * @const @private {string}
2496 goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';