text: /******/ (function(modules) { // webpackBootstrap
  /******/ 	// The module cache
  /******/ 	var installedModules = {};
  /******/
  /******/ 	// The require function
  /******/ 	function __webpack_require__(moduleId) {
  /******/
  /******/ 		// Check if module is in cache
  /******/ 		if(installedModules[moduleId]) {
  /******/ 			return installedModules[moduleId].exports;
  /******/ 		}
  /******/ 		// Create a new module (and put it into the cache)
  /******/ 		var module = installedModules[moduleId] = {
  /******/ 			i: moduleId,
  /******/ 			l: false,
  /******/ 			exports: {}
  /******/ 		};
  /******/
  /******/ 		// Execute the module function
  /******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  /******/
  /******/ 		// Flag the module as loaded
  /******/ 		module.l = true;
  /******/
  /******/ 		// Return the exports of the module
  /******/ 		return module.exports;
  /******/ 	}
  /******/
  /******/
  /******/ 	// expose the modules object (__webpack_modules__)
  /******/ 	__webpack_require__.m = modules;
  /******/
  /******/ 	// expose the module cache
  /******/ 	__webpack_require__.c = installedModules;
  /******/
  /******/ 	// define getter function for harmony exports
  /******/ 	__webpack_require__.d = function(exports, name, getter) {
  /******/ 		if(!__webpack_require__.o(exports, name)) {
  /******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
  /******/ 		}
  /******/ 	};
  /******/
  /******/ 	// define __esModule on exports
  /******/ 	__webpack_require__.r = function(exports) {
  /******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  /******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  /******/ 		}
  /******/ 		Object.defineProperty(exports, '__esModule', { value: true });
  /******/ 	};
  /******/
  /******/ 	// create a fake namespace object
  /******/ 	// mode & 1: value is a module id, require it
  /******/ 	// mode & 2: merge all properties of value into the ns
  /******/ 	// mode & 4: return value when already ns object
  /******/ 	// mode & 8|1: behave like require
  /******/ 	__webpack_require__.t = function(value, mode) {
  /******/ 		if(mode & 1) value = __webpack_require__(value);
  /******/ 		if(mode & 8) return value;
  /******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  /******/ 		var ns = Object.create(null);
  /******/ 		__webpack_require__.r(ns);
  /******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  /******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  /******/ 		return ns;
  /******/ 	};
  /******/
  /******/ 	// getDefaultExport function for compatibility with non-harmony modules
  /******/ 	__webpack_require__.n = function(module) {
  /******/ 		var getter = module && module.__esModule ?
  /******/ 			function getDefault() { return module['default']; } :
  /******/ 			function getModuleExports() { return module; };
  /******/ 		__webpack_require__.d(getter, 'a', getter);
  /******/ 		return getter;
  /******/ 	};
  /******/
  /******/ 	// Object.prototype.hasOwnProperty.call
  /******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  /******/
  /******/ 	// __webpack_public_path__
  /******/ 	__webpack_require__.p = "/";
  /******/
  /******/
  /******/ 	// Load entry module and return exports
  /******/ 	return __webpack_require__(__webpack_require__.s = 4);
  /******/ })
  /************************************************************************/
  /******/ ({
  
  /***/ "./node_modules/@firebase/app/dist/index.cjs.js":
  /*!******************************************************!*\
    !*** ./node_modules/@firebase/app/dist/index.cjs.js ***!
    \******************************************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  "use strict";
  
  
  Object.defineProperty(exports, '__esModule', { value: true });
  
  var tslib_1 = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
  var util = __webpack_require__(/*! @firebase/util */ "./node_modules/@firebase/util/dist/index.cjs.js");
  var logger$1 = __webpack_require__(/*! @firebase/logger */ "./node_modules/@firebase/logger/dist/index.esm.js");
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  var _a;
  var ERRORS = (_a = {},
      _a["no-app" /* NO_APP */] = "No Firebase App '{$appName}' has been created - " +
          'call Firebase App.initializeApp()',
      _a["bad-app-name" /* BAD_APP_NAME */] = "Illegal App name: '{$appName}",
      _a["duplicate-app" /* DUPLICATE_APP */] = "Firebase App named '{$appName}' already exists",
      _a["app-deleted" /* APP_DELETED */] = "Firebase App named '{$appName}' already deleted",
      _a["invalid-app-argument" /* INVALID_APP_ARGUMENT */] = 'firebase.{$appName}() takes either no argument or a ' +
          'Firebase App instance.',
      _a);
  var ERROR_FACTORY = new util.ErrorFactory('app', 'Firebase', ERRORS);
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  var DEFAULT_ENTRY_NAME = '[DEFAULT]';
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  // An array to capture listeners before the true auth functions
  // exist
  var tokenListeners = [];
  /**
   * Global context object for a collection of services using
   * a shared authentication state.
   */
  var FirebaseAppImpl = /** @class */ (function () {
      function FirebaseAppImpl(options, config, firebase_) {
          this.firebase_ = firebase_;
          this.isDeleted_ = false;
          this.services_ = {};
          this.name_ = config.name;
          this.automaticDataCollectionEnabled_ =
              config.automaticDataCollectionEnabled || false;
          this.options_ = util.deepCopy(options);
          this.INTERNAL = {
              getUid: function () { return null; },
              getToken: function () { return Promise.resolve(null); },
              addAuthTokenListener: function (callback) {
                  tokenListeners.push(callback);
                  // Make sure callback is called, asynchronously, in the absence of the auth module
                  setTimeout(function () { return callback(null); }, 0);
              },
              removeAuthTokenListener: function (callback) {
                  tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; });
              }
          };
      }
      Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", {
          get: function () {
              this.checkDestroyed_();
              return this.automaticDataCollectionEnabled_;
          },
          set: function (val) {
              this.checkDestroyed_();
              this.automaticDataCollectionEnabled_ = val;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(FirebaseAppImpl.prototype, "name", {
          get: function () {
              this.checkDestroyed_();
              return this.name_;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(FirebaseAppImpl.prototype, "options", {
          get: function () {
              this.checkDestroyed_();
              return this.options_;
          },
          enumerable: true,
          configurable: true
      });
      FirebaseAppImpl.prototype.delete = function () {
          var _this = this;
          return new Promise(function (resolve) {
              _this.checkDestroyed_();
              resolve();
          })
              .then(function () {
              _this.firebase_.INTERNAL.removeApp(_this.name_);
              var services = [];
              for (var _i = 0, _a = Object.keys(_this.services_); _i < _a.length; _i++) {
                  var serviceKey = _a[_i];
                  for (var _b = 0, _c = Object.keys(_this.services_[serviceKey]); _b < _c.length; _b++) {
                      var instanceKey = _c[_b];
                      services.push(_this.services_[serviceKey][instanceKey]);
                  }
              }
              return Promise.all(services
                  .filter(function (service) { return 'INTERNAL' in service; })
                  .map(function (service) { return service.INTERNAL.delete(); }));
          })
              .then(function () {
              _this.isDeleted_ = true;
              _this.services_ = {};
          });
      };
      /**
       * Return a service instance associated with this app (creating it
       * on demand), identified by the passed instanceIdentifier.
       *
       * NOTE: Currently storage and functions are the only ones that are leveraging this
       * functionality. They invoke it by calling:
       *
       * ```javascript
       * firebase.app().storage('STORAGE BUCKET ID')
       * ```
       *
       * The service name is passed to this already
       * @internal
       */
      FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) {
          if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; }
          this.checkDestroyed_();
          if (!this.services_[name]) {
              this.services_[name] = {};
          }
          if (!this.services_[name][instanceIdentifier]) {
              /**
               * If a custom instance has been defined (i.e. not '[DEFAULT]')
               * then we will pass that instance on, otherwise we pass `null`
               */
              var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME
                  ? instanceIdentifier
                  : undefined;
              var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier);
              this.services_[name][instanceIdentifier] = service;
          }
          return this.services_[name][instanceIdentifier];
      };
      /**
       * Remove a service instance from the cache, so we will create a new instance for this service
       * when people try to get this service again.
       *
       * NOTE: currently only firestore is using this functionality to support firestore shutdown.
       *
       * @param name The service name
       * @param instanceIdentifier instance identifier in case multiple instances are allowed
       * @internal
       */
      FirebaseAppImpl.prototype._removeServiceInstance = function (name, instanceIdentifier) {
          if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; }
          if (this.services_[name] && this.services_[name][instanceIdentifier]) {
              delete this.services_[name][instanceIdentifier];
          }
      };
      /**
       * Callback function used to extend an App instance at the time
       * of service instance creation.
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      FirebaseAppImpl.prototype.extendApp = function (props) {
          var _this = this;
          // Copy the object onto the FirebaseAppImpl prototype
          util.deepExtend(this, props);
          /**
           * If the app has overwritten the addAuthTokenListener stub, forward
           * the active token listeners on to the true fxn.
           *
           * TODO: This function is required due to our current module
           * structure. Once we are able to rely strictly upon a single module
           * implementation, this code should be refactored and Auth should
           * provide these stubs and the upgrade logic
           */
          if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) {
              tokenListeners.forEach(function (listener) {
                  _this.INTERNAL.addAuthTokenListener(listener);
              });
              tokenListeners = [];
          }
      };
      /**
       * This function will throw an Error if the App has already been deleted -
       * use before performing API actions on the App.
       */
      FirebaseAppImpl.prototype.checkDestroyed_ = function () {
          if (this.isDeleted_) {
              throw ERROR_FACTORY.create("app-deleted" /* APP_DELETED */, { appName: this.name_ });
          }
      };
      return FirebaseAppImpl;
  }());
  // Prevent dead-code elimination of these methods w/o invalid property
  // copying.
  (FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) ||
      FirebaseAppImpl.prototype.delete ||
      console.log('dc');
  
  var version = "6.6.0";
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  var logger = new logger$1.Logger('@firebase/app');
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  /**
   * Because auth can't share code with other components, we attach the utility functions
   * in an internal namespace to share code.
   * This function return a firebase namespace object without
   * any utility functions, so it can be shared between the regular firebaseNamespace and
   * the lite version.
   */
  function createFirebaseNamespaceCore(firebaseAppImpl) {
      var apps = {};
      var factories = {};
      var appHooks = {};
      // A namespace is a plain JavaScript Object.
      var namespace = {
          // Hack to prevent Babel from modifying the object returned
          // as the firebase namespace.
          // @ts-ignore
          __esModule: true,
          initializeApp: initializeApp,
          // @ts-ignore
          app: app,
          // @ts-ignore
          apps: null,
          SDK_VERSION: version,
          INTERNAL: {
              registerService: registerService,
              removeApp: removeApp,
              factories: factories,
              useAsService: useAsService
          }
      };
      // Inject a circular default export to allow Babel users who were previously
      // using:
      //
      //   import firebase from 'firebase';
      //   which becomes: var firebase = require('firebase').default;
      //
      // instead of
      //
      //   import * as firebase from 'firebase';
      //   which becomes: var firebase = require('firebase');
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      namespace['default'] = namespace;
      // firebase.apps is a read-only getter.
      Object.defineProperty(namespace, 'apps', {
          get: getApps
      });
      /**
       * Called by App.delete() - but before any services associated with the App
       * are deleted.
       */
      function removeApp(name) {
          var app = apps[name];
          callAppHooks(app, 'delete');
          delete apps[name];
      }
      /**
       * Get the App object for a given name (or DEFAULT).
       */
      function app(name) {
          name = name || DEFAULT_ENTRY_NAME;
          if (!util.contains(apps, name)) {
              throw ERROR_FACTORY.create("no-app" /* NO_APP */, { appName: name });
          }
          return apps[name];
      }
      // @ts-ignore
      app['App'] = firebaseAppImpl;
      function initializeApp(options, rawConfig) {
          if (rawConfig === void 0) { rawConfig = {}; }
          if (typeof rawConfig !== 'object' || rawConfig === null) {
              var name_1 = rawConfig;
              rawConfig = { name: name_1 };
          }
          var config = rawConfig;
          if (config.name === undefined) {
              config.name = DEFAULT_ENTRY_NAME;
          }
          var name = config.name;
          if (typeof name !== 'string' || !name) {
              throw ERROR_FACTORY.create("bad-app-name" /* BAD_APP_NAME */, {
                  appName: String(name)
              });
          }
          if (util.contains(apps, name)) {
              throw ERROR_FACTORY.create("duplicate-app" /* DUPLICATE_APP */, { appName: name });
          }
          var app = new firebaseAppImpl(options, config, namespace);
          apps[name] = app;
          callAppHooks(app, 'create');
          return app;
      }
      /*
       * Return an array of all the non-deleted FirebaseApps.
       */
      function getApps() {
          // Make a copy so caller cannot mutate the apps list.
          return Object.keys(apps).map(function (name) { return apps[name]; });
      }
      /*
       * Register a Firebase Service.
       *
       * firebase.INTERNAL.registerService()
       *
       * TODO: Implement serviceProperties.
       */
      function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) {
          if (allowMultipleInstances === void 0) { allowMultipleInstances = false; }
          // If re-registering a service that already exists, return existing service
          if (factories[name]) {
              logger.debug("There were multiple attempts to register service " + name + ".");
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              return namespace[name];
          }
          // Capture the service factory for later service instantiation
          factories[name] = createService;
          // Capture the appHook, if passed
          if (appHook) {
              appHooks[name] = appHook;
              // Run the **new** app hook on all existing apps
              getApps().forEach(function (app) {
                  appHook('create', app);
              });
          }
          // The Service namespace is an accessor function ...
          function serviceNamespace(appArg) {
              if (appArg === void 0) { appArg = app(); }
              // @ts-ignore
              if (typeof appArg[name] !== 'function') {
                  // Invalid argument.
                  // This happens in the following case: firebase.storage('gs:/')
                  throw ERROR_FACTORY.create("invalid-app-argument" /* INVALID_APP_ARGUMENT */, {
                      appName: name
                  });
              }
              // Forward service instance lookup to the FirebaseApp.
              // @ts-ignore
              return appArg[name]();
          }
          // ... and a container for service-level properties.
          if (serviceProperties !== undefined) {
              util.deepExtend(serviceNamespace, serviceProperties);
          }
          // Monkey-patch the serviceNamespace onto the firebase namespace
          // @ts-ignore
          namespace[name] = serviceNamespace;
          // Patch the FirebaseAppImpl prototype
          // @ts-ignore
          firebaseAppImpl.prototype[name] =
              // TODO: The eslint disable can be removed and the 'ignoreRestArgs'
              // option added to the no-explicit-any rule when ESlint releases it.
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              function () {
                  var args = [];
                  for (var _i = 0; _i < arguments.length; _i++) {
                      args[_i] = arguments[_i];
                  }
                  var serviceFxn = this._getService.bind(this, name);
                  return serviceFxn.apply(this, allowMultipleInstances ? args : []);
              };
          return serviceNamespace;
      }
      function callAppHooks(app, eventName) {
          for (var _i = 0, _a = Object.keys(factories); _i < _a.length; _i++) {
              var serviceName = _a[_i];
              // Ignore virtual services
              var factoryName = useAsService(app, serviceName);
              if (factoryName === null) {
                  return;
              }
              if (appHooks[factoryName]) {
                  appHooks[factoryName](eventName, app);
              }
          }
      }
      // Map the requested service to a registered service name
      // (used to map auth to serverAuth service when needed).
      function useAsService(app, name) {
          if (name === 'serverAuth') {
              return null;
          }
          var useService = name;
          return useService;
      }
      return namespace;
  }
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  /**
   * Return a firebase namespace object.
   *
   * In production, this will be called exactly once and the result
   * assigned to the 'firebase' global.  It may be called multiple times
   * in unit tests.
   */
  function createFirebaseNamespace() {
      var namespace = createFirebaseNamespaceCore(FirebaseAppImpl);
      namespace.INTERNAL = tslib_1.__assign({}, namespace.INTERNAL, { createFirebaseNamespace: createFirebaseNamespace,
          extendNamespace: extendNamespace,
          createSubscribe: util.createSubscribe,
          ErrorFactory: util.ErrorFactory,
          deepExtend: util.deepExtend });
      /**
       * Patch the top-level firebase namespace with additional properties.
       *
       * firebase.INTERNAL.extendNamespace()
       */
      function extendNamespace(props) {
          util.deepExtend(namespace, props);
      }
      return namespace;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  // Firebase Lite detection
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  if (util.isBrowser() && self.firebase !== undefined) {
      logger.warn("\n    Warning: Firebase is already defined in the global scope. Please make sure\n    Firebase library is only loaded once.\n  ");
      // eslint-disable-next-line
      var sdkVersion = self.firebase.SDK_VERSION;
      if (sdkVersion && sdkVersion.indexOf('LITE') >= 0) {
          logger.warn("\n    Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n    You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n    ");
      }
  }
  var firebaseNamespace = createFirebaseNamespace();
  var initializeApp = firebaseNamespace.initializeApp;
  // TODO: This disable can be removed and the 'ignoreRestArgs' option added to
  // the no-explicit-any rule when ESlint releases it.
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  firebaseNamespace.initializeApp = function () {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
      }
      // Environment check before initializing app
      // Do the check in initializeApp, so people have a chance to disable it by setting logLevel
      // in @firebase/logger
      if (util.isNode()) {
          logger.warn("\n      Warning: This is a browser-targeted Firebase bundle but it appears it is being\n      run in a Node environment.  If running in a Node environment, make sure you\n      are using the bundle specified by the \"main\" field in package.json.\n      \n      If you are using Webpack, you can specify \"main\" as the first item in\n      \"resolve.mainFields\":\n      https://webpack.js.org/configuration/resolve/#resolvemainfields\n      \n      If using Rollup, use the rollup-plugin-node-resolve plugin and specify \"main\"\n      as the first item in \"mainFields\", e.g. ['main', 'module'].\n      https://github.com/rollup/rollup-plugin-node-resolve\n      ");
      }
      return initializeApp.apply(undefined, args);
  };
  var firebase = firebaseNamespace;
  
  exports.default = firebase;
  exports.firebase = firebase;
  //# sourceMappingURL=index.cjs.js.map
  
  
  /***/ }),
  
  /***/ "./node_modules/@firebase/logger/dist/index.esm.js":
  /*!*********************************************************!*\
    !*** ./node_modules/@firebase/logger/dist/index.esm.js ***!
    \*********************************************************/
  /*! exports provided: LogLevel, Logger, setLogLevel */
  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  
  "use strict";
  __webpack_require__.r(__webpack_exports__);
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return LogLevel; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return Logger; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setLogLevel", function() { return setLogLevel; });
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * A container for all of the Logger instances
   */
  var instances = [];
  /**
   * The JS SDK supports 5 log levels and also allows a user the ability to
   * silence the logs altogether.
   *
   * The order is a follows:
   * DEBUG < VERBOSE < INFO < WARN < ERROR
   *
   * All of the log types above the current log level will be captured (i.e. if
   * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and
   * `VERBOSE` logs will not)
   */
  var LogLevel;
  (function (LogLevel) {
      LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
      LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE";
      LogLevel[LogLevel["INFO"] = 2] = "INFO";
      LogLevel[LogLevel["WARN"] = 3] = "WARN";
      LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
      LogLevel[LogLevel["SILENT"] = 5] = "SILENT";
  })(LogLevel || (LogLevel = {}));
  /**
   * The default log level
   */
  var defaultLogLevel = LogLevel.INFO;
  /**
   * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR
   * messages on to their corresponding console counterparts (if the log method
   * is supported by the current log level)
   */
  var defaultLogHandler = function (instance, logType) {
      var args = [];
      for (var _i = 2; _i < arguments.length; _i++) {
          args[_i - 2] = arguments[_i];
      }
      if (logType < instance.logLevel) {
          return;
      }
      var now = new Date().toISOString();
      switch (logType) {
          /**
           * By default, `console.debug` is not displayed in the developer console (in
           * chrome). To avoid forcing users to have to opt-in to these logs twice
           * (i.e. once for firebase, and once in the console), we are sending `DEBUG`
           * logs to the `console.log` function.
           */
          case LogLevel.DEBUG:
              console.log.apply(console, ["[" + now + "]  " + instance.name + ":"].concat(args));
              break;
          case LogLevel.VERBOSE:
              console.log.apply(console, ["[" + now + "]  " + instance.name + ":"].concat(args));
              break;
          case LogLevel.INFO:
              console.info.apply(console, ["[" + now + "]  " + instance.name + ":"].concat(args));
              break;
          case LogLevel.WARN:
              console.warn.apply(console, ["[" + now + "]  " + instance.name + ":"].concat(args));
              break;
          case LogLevel.ERROR:
              console.error.apply(console, ["[" + now + "]  " + instance.name + ":"].concat(args));
              break;
          default:
              throw new Error("Attempted to log a message with an invalid logType (value: " + logType + ")");
      }
  };
  var Logger = /** @class */ (function () {
      /**
       * Gives you an instance of a Logger to capture messages according to
       * Firebase's logging scheme.
       *
       * @param name The name that the logs will be associated with
       */
      function Logger(name) {
          this.name = name;
          /**
           * The log level of the given Logger instance.
           */
          this._logLevel = defaultLogLevel;
          /**
           * The log handler for the Logger instance.
           */
          this._logHandler = defaultLogHandler;
          /**
           * Capture the current instance for later use
           */
          instances.push(this);
      }
      Object.defineProperty(Logger.prototype, "logLevel", {
          get: function () {
              return this._logLevel;
          },
          set: function (val) {
              if (!(val in LogLevel)) {
                  throw new TypeError('Invalid value assigned to `logLevel`');
              }
              this._logLevel = val;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Logger.prototype, "logHandler", {
          get: function () {
              return this._logHandler;
          },
          set: function (val) {
              if (typeof val !== 'function') {
                  throw new TypeError('Value assigned to `logHandler` must be a function');
              }
              this._logHandler = val;
          },
          enumerable: true,
          configurable: true
      });
      /**
       * The functions below are all based on the `console` interface
       */
      Logger.prototype.debug = function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args));
      };
      Logger.prototype.log = function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args));
      };
      Logger.prototype.info = function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          this._logHandler.apply(this, [this, LogLevel.INFO].concat(args));
      };
      Logger.prototype.warn = function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          this._logHandler.apply(this, [this, LogLevel.WARN].concat(args));
      };
      Logger.prototype.error = function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args));
      };
      return Logger;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  function setLogLevel(level) {
      instances.forEach(function (inst) {
          inst.logLevel = level;
      });
  }
  
  
  //# sourceMappingURL=index.esm.js.map
  
  
  /***/ }),
  
  /***/ "./node_modules/@firebase/storage/dist/index.esm.js":
  /*!**********************************************************!*\
    !*** ./node_modules/@firebase/storage/dist/index.esm.js ***!
    \**********************************************************/
  /*! exports provided: registerStorage */
  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  
  "use strict";
  __webpack_require__.r(__webpack_exports__);
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerStorage", function() { return registerStorage; });
  /* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/app */ "./node_modules/@firebase/app/dist/index.cjs.js");
  /* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_firebase_app__WEBPACK_IMPORTED_MODULE_0__);
  /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
  
  
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  /**
   * @fileoverview Constants used in the Firebase Storage library.
   */
  /**
   * Domain name for firebase storage.
   */
  var DEFAULT_HOST = 'firebasestorage.googleapis.com';
  /**
   * The key in Firebase config json for the storage bucket.
   */
  var CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';
  /**
   * 2 minutes
   *
   * The timeout for all operations except upload.
   */
  var DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;
  /**
   * 10 minutes
   *
   * The timeout for upload.
   */
  var DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 100;
  /**
   * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported
   * enough for us to use it directly.
   */
  var MIN_SAFE_INTEGER = -9007199254740991;
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  var FirebaseStorageError = /** @class */ (function () {
      function FirebaseStorageError(code, message) {
          this.code_ = prependCode(code);
          this.message_ = 'Firebase Storage: ' + message;
          this.serverResponse_ = null;
          this.name_ = 'FirebaseError';
      }
      FirebaseStorageError.prototype.codeProp = function () {
          return this.code;
      };
      FirebaseStorageError.prototype.codeEquals = function (code) {
          return prependCode(code) === this.codeProp();
      };
      FirebaseStorageError.prototype.serverResponseProp = function () {
          return this.serverResponse_;
      };
      FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {
          this.serverResponse_ = serverResponse;
      };
      Object.defineProperty(FirebaseStorageError.prototype, "name", {
          get: function () {
              return this.name_;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(FirebaseStorageError.prototype, "code", {
          get: function () {
              return this.code_;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(FirebaseStorageError.prototype, "message", {
          get: function () {
              return this.message_;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(FirebaseStorageError.prototype, "serverResponse", {
          get: function () {
              return this.serverResponse_;
          },
          enumerable: true,
          configurable: true
      });
      return FirebaseStorageError;
  }());
  var Code = {
      // Shared between all platforms
      UNKNOWN: 'unknown',
      OBJECT_NOT_FOUND: 'object-not-found',
      BUCKET_NOT_FOUND: 'bucket-not-found',
      PROJECT_NOT_FOUND: 'project-not-found',
      QUOTA_EXCEEDED: 'quota-exceeded',
      UNAUTHENTICATED: 'unauthenticated',
      UNAUTHORIZED: 'unauthorized',
      RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',
      INVALID_CHECKSUM: 'invalid-checksum',
      CANCELED: 'canceled',
      // JS specific
      INVALID_EVENT_NAME: 'invalid-event-name',
      INVALID_URL: 'invalid-url',
      INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',
      NO_DEFAULT_BUCKET: 'no-default-bucket',
      CANNOT_SLICE_BLOB: 'cannot-slice-blob',
      SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',
      NO_DOWNLOAD_URL: 'no-download-url',
      INVALID_ARGUMENT: 'invalid-argument',
      INVALID_ARGUMENT_COUNT: 'invalid-argument-count',
      APP_DELETED: 'app-deleted',
      INVALID_ROOT_OPERATION: 'invalid-root-operation',
      INVALID_FORMAT: 'invalid-format',
      INTERNAL_ERROR: 'internal-error'
  };
  function prependCode(code) {
      return 'storage/' + code;
  }
  function unknown() {
      var message = 'An unknown error occurred, please check the error payload for ' +
          'server response.';
      return new FirebaseStorageError(Code.UNKNOWN, message);
  }
  function objectNotFound(path) {
      return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, "Object '" + path + "' does not exist.");
  }
  function quotaExceeded(bucket) {
      return new FirebaseStorageError(Code.QUOTA_EXCEEDED, "Quota for bucket '" +
          bucket +
          "' exceeded, please view quota on " +
          'https://firebase.google.com/pricing/.');
  }
  function unauthenticated() {
      var message = 'User is not authenticated, please authenticate using Firebase ' +
          'Authentication and try again.';
      return new FirebaseStorageError(Code.UNAUTHENTICATED, message);
  }
  function unauthorized(path) {
      return new FirebaseStorageError(Code.UNAUTHORIZED, "User does not have permission to access '" + path + "'.");
  }
  function retryLimitExceeded() {
      return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');
  }
  function canceled() {
      return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');
  }
  function invalidUrl(url) {
      return new FirebaseStorageError(Code.INVALID_URL, "Invalid URL '" + url + "'.");
  }
  function invalidDefaultBucket(bucket) {
      return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
  }
  function noDefaultBucket() {
      return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' +
          "found. Did you set the '" +
          CONFIG_STORAGE_BUCKET_KEY +
          "' property when initializing the app?");
  }
  function cannotSliceBlob() {
      return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');
  }
  function serverFileWrongSize() {
      return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');
  }
  function noDownloadURL() {
      return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');
  }
  function invalidArgument(index, fnName, message) {
      return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);
  }
  function invalidArgumentCount(argMin, argMax, fnName, real) {
      var countPart;
      var plural;
      if (argMin === argMax) {
          countPart = argMin;
          plural = argMin === 1 ? 'argument' : 'arguments';
      }
      else {
          countPart = 'between ' + argMin + ' and ' + argMax;
          plural = 'arguments';
      }
      return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' +
          fnName +
          '`: Expected ' +
          countPart +
          ' ' +
          plural +
          ', received ' +
          real +
          '.');
  }
  function appDeleted() {
      return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');
  }
  /**
   * @param name The name of the operation that was invalid.
   */
  function invalidRootOperation(name) {
      return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, "The operation '" +
          name +
          "' cannot be performed on a root reference, create a non-root " +
          "reference using child, such as .child('file.png').");
  }
  /**
   * @param format The format that was not valid.
   * @param message A message describing the format violation.
   */
  function invalidFormat(format, message) {
      return new FirebaseStorageError(Code.INVALID_FORMAT, "String does not match format '" + format + "': " + message);
  }
  /**
   * @param message A message describing the internal error.
   */
  function internalError(message) {
      throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  var StringFormat = {
      RAW: 'raw',
      BASE64: 'base64',
      BASE64URL: 'base64url',
      DATA_URL: 'data_url'
  };
  function formatValidator(stringFormat) {
      switch (stringFormat) {
          case StringFormat.RAW:
          case StringFormat.BASE64:
          case StringFormat.BASE64URL:
          case StringFormat.DATA_URL:
              return;
          default:
              throw 'Expected one of the event types: [' +
                  StringFormat.RAW +
                  ', ' +
                  StringFormat.BASE64 +
                  ', ' +
                  StringFormat.BASE64URL +
                  ', ' +
                  StringFormat.DATA_URL +
                  '].';
      }
  }
  /**
   * @struct
   */
  var StringData = /** @class */ (function () {
      function StringData(data, contentType) {
          this.data = data;
          this.contentType = contentType || null;
      }
      return StringData;
  }());
  function dataFromString(format, stringData) {
      switch (format) {
          case StringFormat.RAW:
              return new StringData(utf8Bytes_(stringData));
          case StringFormat.BASE64:
          case StringFormat.BASE64URL:
              return new StringData(base64Bytes_(format, stringData));
          case StringFormat.DATA_URL:
              return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));
          default:
          // do nothing
      }
      // assert(false);
      throw unknown();
  }
  function utf8Bytes_(value) {
      var b = [];
      for (var i = 0; i < value.length; i++) {
          var c = value.charCodeAt(i);
          if (c <= 127) {
              b.push(c);
          }
          else {
              if (c <= 2047) {
                  b.push(192 | (c >> 6), 128 | (c & 63));
              }
              else {
                  if ((c & 64512) === 55296) {
                      // The start of a surrogate pair.
                      var valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;
                      if (!valid) {
                          // The second surrogate wasn't there.
                          b.push(239, 191, 189);
                      }
                      else {
                          var hi = c;
                          var lo = value.charCodeAt(++i);
                          c = 65536 | ((hi & 1023) << 10) | (lo & 1023);
                          b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));
                      }
                  }
                  else {
                      if ((c & 64512) === 56320) {
                          // Invalid low surrogate.
                          b.push(239, 191, 189);
                      }
                      else {
                          b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));
                      }
                  }
              }
          }
      }
      return new Uint8Array(b);
  }
  function percentEncodedBytes_(value) {
      var decoded;
      try {
          decoded = decodeURIComponent(value);
      }
      catch (e) {
          throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');
      }
      return utf8Bytes_(decoded);
  }
  function base64Bytes_(format, value) {
      switch (format) {
          case StringFormat.BASE64: {
              var hasMinus = value.indexOf('-') !== -1;
              var hasUnder = value.indexOf('_') !== -1;
              if (hasMinus || hasUnder) {
                  var invalidChar = hasMinus ? '-' : '_';
                  throw invalidFormat(format, "Invalid character '" +
                      invalidChar +
                      "' found: is it base64url encoded?");
              }
              break;
          }
          case StringFormat.BASE64URL: {
              var hasPlus = value.indexOf('+') !== -1;
              var hasSlash = value.indexOf('/') !== -1;
              if (hasPlus || hasSlash) {
                  var invalidChar = hasPlus ? '+' : '/';
                  throw invalidFormat(format, "Invalid character '" + invalidChar + "' found: is it base64 encoded?");
              }
              value = value.replace(/-/g, '+').replace(/_/g, '/');
              break;
          }
          default:
          // do nothing
      }
      var bytes;
      try {
          bytes = atob(value);
      }
      catch (e) {
          throw invalidFormat(format, 'Invalid character found');
      }
      var array = new Uint8Array(bytes.length);
      for (var i = 0; i < bytes.length; i++) {
          array[i] = bytes.charCodeAt(i);
      }
      return array;
  }
  /**
   * @struct
   */
  var DataURLParts = /** @class */ (function () {
      function DataURLParts(dataURL) {
          this.base64 = false;
          this.contentType = null;
          var matches = dataURL.match(/^data:([^,]+)?,/);
          if (matches === null) {
              throw invalidFormat(StringFormat.DATA_URL, "Must be formatted 'data:[<mediatype>][;base64],<data>");
          }
          var middle = matches[1] || null;
          if (middle != null) {
              this.base64 = endsWith(middle, ';base64');
              this.contentType = this.base64
                  ? middle.substring(0, middle.length - ';base64'.length)
                  : middle;
          }
          this.rest = dataURL.substring(dataURL.indexOf(',') + 1);
      }
      return DataURLParts;
  }());
  function dataURLBytes_(dataUrl) {
      var parts = new DataURLParts(dataUrl);
      if (parts.base64) {
          return base64Bytes_(StringFormat.BASE64, parts.rest);
      }
      else {
          return percentEncodedBytes_(parts.rest);
      }
  }
  function dataURLContentType_(dataUrl) {
      var parts = new DataURLParts(dataUrl);
      return parts.contentType;
  }
  function endsWith(s, end) {
      var longEnough = s.length >= end.length;
      if (!longEnough) {
          return false;
      }
      return s.substring(s.length - end.length) === end;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  var TaskEvent = {
      /** Triggered whenever the task changes or progress is updated. */
      STATE_CHANGED: 'state_changed'
  };
  var InternalTaskState = {
      RUNNING: 'running',
      PAUSING: 'pausing',
      PAUSED: 'paused',
      SUCCESS: 'success',
      CANCELING: 'canceling',
      CANCELED: 'canceled',
      ERROR: 'error'
  };
  var TaskState = {
      /** The task is currently transferring data. */
      RUNNING: 'running',
      /** The task was paused by the user. */
      PAUSED: 'paused',
      /** The task completed successfully. */
      SUCCESS: 'success',
      /** The task was canceled. */
      CANCELED: 'canceled',
      /** The task failed with an error. */
      ERROR: 'error'
  };
  function taskStateFromInternalTaskState(state) {
      switch (state) {
          case InternalTaskState.RUNNING:
          case InternalTaskState.PAUSING:
          case InternalTaskState.CANCELING:
              return TaskState.RUNNING;
          case InternalTaskState.PAUSED:
              return TaskState.PAUSED;
          case InternalTaskState.SUCCESS:
              return TaskState.SUCCESS;
          case InternalTaskState.CANCELED:
              return TaskState.CANCELED;
          case InternalTaskState.ERROR:
              return TaskState.ERROR;
          default:
              // TODO(andysoto): assert(false);
              return TaskState.ERROR;
      }
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @return False if the object is undefined or null, true otherwise.
   */
  function isDef(p) {
      return p != null;
  }
  function isJustDef(p) {
      return p !== void 0;
  }
  function isFunction(p) {
      return typeof p === 'function';
  }
  function isObject(p) {
      return typeof p === 'object';
  }
  function isNonNullObject(p) {
      return isObject(p) && p !== null;
  }
  function isNonArrayObject(p) {
      return isObject(p) && !Array.isArray(p);
  }
  function isString(p) {
      return typeof p === 'string' || p instanceof String;
  }
  function isInteger(p) {
      return isNumber(p) && Number.isInteger(p);
  }
  function isNumber(p) {
      return typeof p === 'number' || p instanceof Number;
  }
  function isNativeBlob(p) {
      return isNativeBlobDefined() && p instanceof Blob;
  }
  function isNativeBlobDefined() {
      return typeof Blob !== 'undefined';
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @enum{number}
   */
  var ErrorCode;
  (function (ErrorCode) {
      ErrorCode[ErrorCode["NO_ERROR"] = 0] = "NO_ERROR";
      ErrorCode[ErrorCode["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
      ErrorCode[ErrorCode["ABORT"] = 2] = "ABORT";
  })(ErrorCode || (ErrorCode = {}));
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and
   * doesn't work in React Native on Android.
   */
  var NetworkXhrIo = /** @class */ (function () {
      function NetworkXhrIo() {
          var _this = this;
          this.sent_ = false;
          this.xhr_ = new XMLHttpRequest();
          this.errorCode_ = ErrorCode.NO_ERROR;
          this.sendPromise_ = new Promise(function (resolve) {
              _this.xhr_.addEventListener('abort', function () {
                  _this.errorCode_ = ErrorCode.ABORT;
                  resolve(_this);
              });
              _this.xhr_.addEventListener('error', function () {
                  _this.errorCode_ = ErrorCode.NETWORK_ERROR;
                  resolve(_this);
              });
              _this.xhr_.addEventListener('load', function () {
                  resolve(_this);
              });
          });
      }
      /**
       * @override
       */
      NetworkXhrIo.prototype.send = function (url, method, body, headers) {
          if (this.sent_) {
              throw internalError('cannot .send() more than once');
          }
          this.sent_ = true;
          this.xhr_.open(method, url, true);
          if (isDef(headers)) {
              for (var key in headers) {
                  if (headers.hasOwnProperty(key)) {
                      this.xhr_.setRequestHeader(key, headers[key].toString());
                  }
              }
          }
          if (isDef(body)) {
              this.xhr_.send(body);
          }
          else {
              this.xhr_.send();
          }
          return this.sendPromise_;
      };
      /**
       * @override
       */
      NetworkXhrIo.prototype.getErrorCode = function () {
          if (!this.sent_) {
              throw internalError('cannot .getErrorCode() before sending');
          }
          return this.errorCode_;
      };
      /**
       * @override
       */
      NetworkXhrIo.prototype.getStatus = function () {
          if (!this.sent_) {
              throw internalError('cannot .getStatus() before sending');
          }
          try {
              return this.xhr_.status;
          }
          catch (e) {
              return -1;
          }
      };
      /**
       * @override
       */
      NetworkXhrIo.prototype.getResponseText = function () {
          if (!this.sent_) {
              throw internalError('cannot .getResponseText() before sending');
          }
          return this.xhr_.responseText;
      };
      /**
       * Aborts the request.
       * @override
       */
      NetworkXhrIo.prototype.abort = function () {
          this.xhr_.abort();
      };
      /**
       * @override
       */
      NetworkXhrIo.prototype.getResponseHeader = function (header) {
          return this.xhr_.getResponseHeader(header);
      };
      /**
       * @override
       */
      NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {
          if (isDef(this.xhr_.upload)) {
              this.xhr_.upload.addEventListener('progress', listener);
          }
      };
      /**
       * @override
       */
      NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {
          if (isDef(this.xhr_.upload)) {
              this.xhr_.upload.removeEventListener('progress', listener);
          }
      };
      return NetworkXhrIo;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Factory-like class for creating XhrIo instances.
   */
  var XhrIoPool = /** @class */ (function () {
      function XhrIoPool() {
      }
      XhrIoPool.prototype.createXhrIo = function () {
          return new NetworkXhrIo();
      };
      return XhrIoPool;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  function getBlobBuilder() {
      if (typeof BlobBuilder !== 'undefined') {
          return BlobBuilder;
      }
      else if (typeof WebKitBlobBuilder !== 'undefined') {
          return WebKitBlobBuilder;
      }
      else {
          return undefined;
      }
  }
  /**
   * Concatenates one or more values together and converts them to a Blob.
   *
   * @param args The values that will make up the resulting blob.
   * @return The blob.
   */
  function getBlob() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
      }
      var BlobBuilder = getBlobBuilder();
      if (BlobBuilder !== undefined) {
          var bb = new BlobBuilder();
          for (var i = 0; i < args.length; i++) {
              bb.append(args[i]);
          }
          return bb.getBlob();
      }
      else {
          if (isNativeBlobDefined()) {
              return new Blob(args);
          }
          else {
              throw Error("This browser doesn't seem to support creating Blobs");
          }
      }
  }
  /**
   * Slices the blob. The returned blob contains data from the start byte
   * (inclusive) till the end byte (exclusive). Negative indices cannot be used.
   *
   * @param blob The blob to be sliced.
   * @param start Index of the starting byte.
   * @param end Index of the ending byte.
   * @return The blob slice or null if not supported.
   */
  function sliceBlob(blob, start, end) {
      if (blob.webkitSlice) {
          return blob.webkitSlice(start, end);
      }
      else if (blob.mozSlice) {
          return blob.mozSlice(start, end);
      }
      else if (blob.slice) {
          return blob.slice(start, end);
      }
      return null;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @param opt_elideCopy If true, doesn't copy mutable input data
   *     (e.g. Uint8Arrays). Pass true only if you know the objects will not be
   *     modified after this blob's construction.
   */
  var FbsBlob = /** @class */ (function () {
      function FbsBlob(data, elideCopy) {
          var size = 0;
          var blobType = '';
          if (isNativeBlob(data)) {
              this.data_ = data;
              size = data.size;
              blobType = data.type;
          }
          else if (data instanceof ArrayBuffer) {
              if (elideCopy) {
                  this.data_ = new Uint8Array(data);
              }
              else {
                  this.data_ = new Uint8Array(data.byteLength);
                  this.data_.set(new Uint8Array(data));
              }
              size = this.data_.length;
          }
          else if (data instanceof Uint8Array) {
              if (elideCopy) {
                  this.data_ = data;
              }
              else {
                  this.data_ = new Uint8Array(data.length);
                  this.data_.set(data);
              }
              size = data.length;
          }
          this.size_ = size;
          this.type_ = blobType;
      }
      FbsBlob.prototype.size = function () {
          return this.size_;
      };
      FbsBlob.prototype.type = function () {
          return this.type_;
      };
      FbsBlob.prototype.slice = function (startByte, endByte) {
          if (isNativeBlob(this.data_)) {
              var realBlob = this.data_;
              var sliced = sliceBlob(realBlob, startByte, endByte);
              if (sliced === null) {
                  return null;
              }
              return new FbsBlob(sliced);
          }
          else {
              var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);
              return new FbsBlob(slice, true);
          }
      };
      FbsBlob.getBlob = function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          if (isNativeBlobDefined()) {
              var blobby = args.map(function (val) {
                  if (val instanceof FbsBlob) {
                      return val.data_;
                  }
                  else {
                      return val;
                  }
              });
              return new FbsBlob(getBlob.apply(null, blobby));
          }
          else {
              var uint8Arrays = args.map(function (val) {
                  if (isString(val)) {
                      return dataFromString(StringFormat.RAW, val).data;
                  }
                  else {
                      // Blobs don't exist, so this has to be a Uint8Array.
                      return val.data_;
                  }
              });
              var finalLength_1 = 0;
              uint8Arrays.forEach(function (array) {
                  finalLength_1 += array.byteLength;
              });
              var merged_1 = new Uint8Array(finalLength_1);
              var index_1 = 0;
              uint8Arrays.forEach(function (array) {
                  for (var i = 0; i < array.length; i++) {
                      merged_1[index_1++] = array[i];
                  }
              });
              return new FbsBlob(merged_1, true);
          }
      };
      FbsBlob.prototype.uploadData = function () {
          return this.data_;
      };
      return FbsBlob;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @struct
   */
  var Location = /** @class */ (function () {
      function Location(bucket, path) {
          this.bucket = bucket;
          this.path_ = path;
      }
      Object.defineProperty(Location.prototype, "path", {
          get: function () {
              return this.path_;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Location.prototype, "isRoot", {
          get: function () {
              return this.path.length === 0;
          },
          enumerable: true,
          configurable: true
      });
      Location.prototype.fullServerUrl = function () {
          var encode = encodeURIComponent;
          return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);
      };
      Location.prototype.bucketOnlyServerUrl = function () {
          var encode = encodeURIComponent;
          return '/b/' + encode(this.bucket) + '/o';
      };
      Location.makeFromBucketSpec = function (bucketString) {
          var bucketLocation;
          try {
              bucketLocation = Location.makeFromUrl(bucketString);
          }
          catch (e) {
              // Not valid URL, use as-is. This lets you put bare bucket names in
              // config.
              return new Location(bucketString, '');
          }
          if (bucketLocation.path === '') {
              return bucketLocation;
          }
          else {
              throw invalidDefaultBucket(bucketString);
          }
      };
      Location.makeFromUrl = function (url) {
          var location = null;
          var bucketDomain = '([A-Za-z0-9.\\-_]+)';
          function gsModify(loc) {
              if (loc.path.charAt(loc.path.length - 1) === '/') {
                  loc.path_ = loc.path_.slice(0, -1);
              }
          }
          var gsPath = '(/(.*))?$';
          var path = '(/([^?#]*).*)?$';
          var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');
          var gsIndices = { bucket: 1, path: 3 };
          function httpModify(loc) {
              loc.path_ = decodeURIComponent(loc.path);
          }
          var version = 'v[A-Za-z0-9_]+';
          var hostRegex = DEFAULT_HOST.replace(/[.]/g, '\\.');
          var httpRegex = new RegExp("^https?://" + hostRegex + "/" + version + "/b/" + bucketDomain + "/o" + path, 'i');
          var httpIndices = { bucket: 1, path: 3 };
          var groups = [
              { regex: gsRegex, indices: gsIndices, postModify: gsModify },
              { regex: httpRegex, indices: httpIndices, postModify: httpModify }
          ];
          for (var i = 0; i < groups.length; i++) {
              var group = groups[i];
              var captures = group.regex.exec(url);
              if (captures) {
                  var bucketValue = captures[group.indices.bucket];
                  var pathValue = captures[group.indices.path];
                  if (!pathValue) {
                      pathValue = '';
                  }
                  location = new Location(bucketValue, pathValue);
                  group.postModify(location);
                  break;
              }
          }
          if (location == null) {
              throw invalidUrl(url);
          }
          return location;
      };
      return Location;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Returns the Object resulting from parsing the given JSON, or null if the
   * given string does not represent a JSON object.
   */
  function jsonObjectOrNull(s) {
      var obj;
      try {
          obj = JSON.parse(s);
      }
      catch (e) {
          return null;
      }
      if (isNonArrayObject(obj)) {
          return obj;
      }
      else {
          return null;
      }
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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 Contains helper methods for manipulating paths.
   */
  /**
   * @return Null if the path is already at the root.
   */
  function parent(path) {
      if (path.length === 0) {
          return null;
      }
      var index = path.lastIndexOf('/');
      if (index === -1) {
          return '';
      }
      var newPath = path.slice(0, index);
      return newPath;
  }
  function child(path, childPath) {
      var canonicalChildPath = childPath
          .split('/')
          .filter(function (component) { return component.length > 0; })
          .join('/');
      if (path.length === 0) {
          return canonicalChildPath;
      }
      else {
          return path + '/' + canonicalChildPath;
      }
  }
  /**
   * Returns the last component of a path.
   * '/foo/bar' -> 'bar'
   * '/foo/bar/baz/' -> 'baz/'
   * '/a' -> 'a'
   */
  function lastComponent(path) {
      var index = path.lastIndexOf('/', path.length - 2);
      if (index === -1) {
          return path;
      }
      else {
          return path.slice(index + 1);
      }
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  function makeUrl(urlPart) {
      return "https://" + DEFAULT_HOST + "/v0" + urlPart;
  }
  function makeQueryString(params) {
      var encode = encodeURIComponent;
      var queryPart = '?';
      for (var key in params) {
          if (params.hasOwnProperty(key)) {
              // @ts-ignore TODO: remove once typescript is upgraded to 3.5.x
              var nextPart = encode(key) + '=' + encode(params[key]);
              queryPart = queryPart + nextPart + '&';
          }
      }
      // Chop off the extra '&' or '?' on the end
      queryPart = queryPart.slice(0, -1);
      return queryPart;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  function noXform_(metadata, value) {
      return value;
  }
  /**
   * @struct
   */
  var Mapping = /** @class */ (function () {
      function Mapping(server, local, writable, xform) {
          this.server = server;
          this.local = local || server;
          this.writable = !!writable;
          this.xform = xform || noXform_;
      }
      return Mapping;
  }());
  var mappings_ = null;
  function xformPath(fullPath) {
      if (!isString(fullPath) || fullPath.length < 2) {
          return fullPath;
      }
      else {
          return lastComponent(fullPath);
      }
  }
  function getMappings() {
      if (mappings_) {
          return mappings_;
      }
      var mappings = [];
      mappings.push(new Mapping('bucket'));
      mappings.push(new Mapping('generation'));
      mappings.push(new Mapping('metageneration'));
      mappings.push(new Mapping('name', 'fullPath', true));
      function mappingsXformPath(_metadata, fullPath) {
          return xformPath(fullPath);
      }
      var nameMapping = new Mapping('name');
      nameMapping.xform = mappingsXformPath;
      mappings.push(nameMapping);
      /**
       * Coerces the second param to a number, if it is defined.
       */
      function xformSize(_metadata, size) {
          if (isDef(size)) {
              return Number(size);
          }
          else {
              return size;
          }
      }
      var sizeMapping = new Mapping('size');
      sizeMapping.xform = xformSize;
      mappings.push(sizeMapping);
      mappings.push(new Mapping('timeCreated'));
      mappings.push(new Mapping('updated'));
      mappings.push(new Mapping('md5Hash', null, true));
      mappings.push(new Mapping('cacheControl', null, true));
      mappings.push(new Mapping('contentDisposition', null, true));
      mappings.push(new Mapping('contentEncoding', null, true));
      mappings.push(new Mapping('contentLanguage', null, true));
      mappings.push(new Mapping('contentType', null, true));
      mappings.push(new Mapping('metadata', 'customMetadata', true));
      mappings_ = mappings;
      return mappings_;
  }
  function addRef(metadata, authWrapper) {
      function generateRef() {
          var bucket = metadata['bucket'];
          var path = metadata['fullPath'];
          var loc = new Location(bucket, path);
          return authWrapper.makeStorageReference(loc);
      }
      Object.defineProperty(metadata, 'ref', { get: generateRef });
  }
  function fromResource(authWrapper, resource, mappings) {
      var metadata = {};
      metadata['type'] = 'file';
      var len = mappings.length;
      for (var i = 0; i < len; i++) {
          var mapping = mappings[i];
          metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);
      }
      addRef(metadata, authWrapper);
      return metadata;
  }
  function fromResourceString(authWrapper, resourceString, mappings) {
      var obj = jsonObjectOrNull(resourceString);
      if (obj === null) {
          return null;
      }
      var resource = obj;
      return fromResource(authWrapper, resource, mappings);
  }
  function downloadUrlFromResourceString(metadata, resourceString) {
      var obj = jsonObjectOrNull(resourceString);
      if (obj === null) {
          return null;
      }
      if (!isString(obj['downloadTokens'])) {
          // This can happen if objects are uploaded through GCS and retrieved
          // through list, so we don't want to throw an Error.
          return null;
      }
      var tokens = obj['downloadTokens'];
      if (tokens.length === 0) {
          return null;
      }
      var encode = encodeURIComponent;
      var tokensList = tokens.split(',');
      var urls = tokensList.map(function (token) {
          var bucket = metadata['bucket'];
          var path = metadata['fullPath'];
          var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);
          var base = makeUrl(urlPart);
          var queryString = makeQueryString({
              alt: 'media',
              token: token
          });
          return base + queryString;
      });
      return urls[0];
  }
  function toResourceString(metadata, mappings) {
      var resource = {};
      var len = mappings.length;
      for (var i = 0; i < len; i++) {
          var mapping = mappings[i];
          if (mapping.writable) {
              resource[mapping.server] = metadata[mapping.local];
          }
      }
      return JSON.stringify(resource);
  }
  function metadataValidator(p) {
      if (!isObject(p) || !p) {
          throw 'Expected Metadata object.';
      }
      for (var key in p) {
          if (p.hasOwnProperty(key)) {
              var val = p[key];
              if (key === 'customMetadata') {
                  if (!isObject(val)) {
                      throw 'Expected object for \'customMetadata\' mapping.';
                  }
              }
              else {
                  if (isNonNullObject(val)) {
                      throw "Mapping for '" + key + "' cannot be an object.";
                  }
              }
          }
      }
  }
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  var MAX_RESULTS_KEY = 'maxResults';
  var MAX_MAX_RESULTS = 1000;
  var PAGE_TOKEN_KEY = 'pageToken';
  var PREFIXES_KEY = 'prefixes';
  var ITEMS_KEY = 'items';
  function fromBackendResponse(authWrapper, resource) {
      var listResult = {
          prefixes: [],
          items: [],
          nextPageToken: resource['nextPageToken']
      };
      var bucket = authWrapper.bucket();
      if (bucket === null) {
          throw noDefaultBucket();
      }
      if (resource[PREFIXES_KEY]) {
          for (var _i = 0, _a = resource[PREFIXES_KEY]; _i < _a.length; _i++) {
              var path = _a[_i];
              var pathWithoutTrailingSlash = path.replace(/\/$/, '');
              var reference = authWrapper.makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));
              listResult.prefixes.push(reference);
          }
      }
      if (resource[ITEMS_KEY]) {
          for (var _b = 0, _c = resource[ITEMS_KEY]; _b < _c.length; _b++) {
              var item = _c[_b];
              var reference = authWrapper.makeStorageReference(new Location(bucket, item['name']));
              listResult.items.push(reference);
          }
      }
      return listResult;
  }
  function fromResponseString(authWrapper, resourceString) {
      var obj = jsonObjectOrNull(resourceString);
      if (obj === null) {
          return null;
      }
      var resource = obj;
      return fromBackendResponse(authWrapper, resource);
  }
  function listOptionsValidator(p) {
      if (!isObject(p) || !p) {
          throw 'Expected ListOptions object.';
      }
      for (var key in p) {
          if (key === MAX_RESULTS_KEY) {
              if (!isInteger(p[MAX_RESULTS_KEY]) ||
                  p[MAX_RESULTS_KEY] <= 0) {
                  throw 'Expected maxResults to be a positive number.';
              }
              if (p[MAX_RESULTS_KEY] > 1000) {
                  throw "Expected maxResults to be less than or equal to " + MAX_MAX_RESULTS + ".";
              }
          }
          else if (key === PAGE_TOKEN_KEY) {
              if (p[PAGE_TOKEN_KEY] && !isString(p[PAGE_TOKEN_KEY])) {
                  throw 'Expected pageToken to be string.';
              }
          }
          else {
              throw 'Unknown option: ' + key;
          }
      }
  }
  
  var RequestInfo = /** @class */ (function () {
      function RequestInfo(url, method, 
      /**
       * Returns the value with which to resolve the request's promise. Only called
       * if the request is successful. Throw from this function to reject the
       * returned Request's promise with the thrown error.
       * Note: The XhrIo passed to this function may be reused after this callback
       * returns. Do not keep a reference to it in any way.
       */
      handler, timeout) {
          this.url = url;
          this.method = method;
          this.handler = handler;
          this.timeout = timeout;
          this.urlParams = {};
          this.headers = {};
          this.body = null;
          this.errorHandler = null;
          /**
           * Called with the current number of bytes uploaded and total size (-1 if not
           * computable) of the request body (i.e. used to report upload progress).
           */
          this.progressCallback = null;
          this.successCodes = [200];
          this.additionalRetryCodes = [];
      }
      return RequestInfo;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Throws the UNKNOWN FirebaseStorageError if cndn is false.
   */
  function handlerCheck(cndn) {
      if (!cndn) {
          throw unknown();
      }
  }
  function metadataHandler(authWrapper, mappings) {
      function handler(xhr, text) {
          var metadata = fromResourceString(authWrapper, text, mappings);
          handlerCheck(metadata !== null);
          return metadata;
      }
      return handler;
  }
  function listHandler(authWrapper) {
      function handler(xhr, text) {
          var listResult = fromResponseString(authWrapper, text);
          handlerCheck(listResult !== null);
          return listResult;
      }
      return handler;
  }
  function downloadUrlHandler(authWrapper, mappings) {
      function handler(xhr, text) {
          var metadata = fromResourceString(authWrapper, text, mappings);
          handlerCheck(metadata !== null);
          return downloadUrlFromResourceString(metadata, text);
      }
      return handler;
  }
  function sharedErrorHandler(location) {
      function errorHandler(xhr, err) {
          var newErr;
          if (xhr.getStatus() === 401) {
              newErr = unauthenticated();
          }
          else {
              if (xhr.getStatus() === 402) {
                  newErr = quotaExceeded(location.bucket);
              }
              else {
                  if (xhr.getStatus() === 403) {
                      newErr = unauthorized(location.path);
                  }
                  else {
                      newErr = err;
                  }
              }
          }
          newErr.setServerResponseProp(err.serverResponseProp());
          return newErr;
      }
      return errorHandler;
  }
  function objectErrorHandler(location) {
      var shared = sharedErrorHandler(location);
      function errorHandler(xhr, err) {
          var newErr = shared(xhr, err);
          if (xhr.getStatus() === 404) {
              newErr = objectNotFound(location.path);
          }
          newErr.setServerResponseProp(err.serverResponseProp());
          return newErr;
      }
      return errorHandler;
  }
  function getMetadata(authWrapper, location, mappings) {
      var urlPart = location.fullServerUrl();
      var url = makeUrl(urlPart);
      var method = 'GET';
      var timeout = authWrapper.maxOperationRetryTime();
      var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);
      requestInfo.errorHandler = objectErrorHandler(location);
      return requestInfo;
  }
  function list(authWrapper, location, delimiter, pageToken, maxResults) {
      var urlParams = {};
      if (location.isRoot) {
          urlParams['prefix'] = '';
      }
      else {
          urlParams['prefix'] = location.path + '/';
      }
      if (delimiter && delimiter.length > 0) {
          urlParams['delimiter'] = delimiter;
      }
      if (pageToken) {
          urlParams['pageToken'] = pageToken;
      }
      if (maxResults) {
          urlParams['maxResults'] = maxResults;
      }
      var urlPart = location.bucketOnlyServerUrl();
      var url = makeUrl(urlPart);
      var method = 'GET';
      var timeout = authWrapper.maxOperationRetryTime();
      var requestInfo = new RequestInfo(url, method, listHandler(authWrapper), timeout);
      requestInfo.urlParams = urlParams;
      requestInfo.errorHandler = sharedErrorHandler(location);
      return requestInfo;
  }
  function getDownloadUrl(authWrapper, location, mappings) {
      var urlPart = location.fullServerUrl();
      var url = makeUrl(urlPart);
      var method = 'GET';
      var timeout = authWrapper.maxOperationRetryTime();
      var requestInfo = new RequestInfo(url, method, downloadUrlHandler(authWrapper, mappings), timeout);
      requestInfo.errorHandler = objectErrorHandler(location);
      return requestInfo;
  }
  function updateMetadata(authWrapper, location, metadata, mappings) {
      var urlPart = location.fullServerUrl();
      var url = makeUrl(urlPart);
      var method = 'PATCH';
      var body = toResourceString(metadata, mappings);
      var headers = { 'Content-Type': 'application/json; charset=utf-8' };
      var timeout = authWrapper.maxOperationRetryTime();
      var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);
      requestInfo.headers = headers;
      requestInfo.body = body;
      requestInfo.errorHandler = objectErrorHandler(location);
      return requestInfo;
  }
  function deleteObject(authWrapper, location) {
      var urlPart = location.fullServerUrl();
      var url = makeUrl(urlPart);
      var method = 'DELETE';
      var timeout = authWrapper.maxOperationRetryTime();
      function handler(_xhr, _text) { }
      var requestInfo = new RequestInfo(url, method, handler, timeout);
      requestInfo.successCodes = [200, 204];
      requestInfo.errorHandler = objectErrorHandler(location);
      return requestInfo;
  }
  function determineContentType_(metadata, blob) {
      return ((metadata && metadata['contentType']) ||
          (blob && blob.type()) ||
          'application/octet-stream');
  }
  function metadataForUpload_(location, blob, metadata) {
      var metadataClone = Object.assign({}, metadata);
      metadataClone['fullPath'] = location.path;
      metadataClone['size'] = blob.size();
      if (!metadataClone['contentType']) {
          metadataClone['contentType'] = determineContentType_(null, blob);
      }
      return metadataClone;
  }
  function multipartUpload(authWrapper, location, mappings, blob, metadata) {
      var urlPart = location.bucketOnlyServerUrl();
      var headers = {
          'X-Goog-Upload-Protocol': 'multipart'
      };
      function genBoundary() {
          var str = '';
          for (var i = 0; i < 2; i++) {
              str =
                  str +
                      Math.random()
                          .toString()
                          .slice(2);
          }
          return str;
      }
      var boundary = genBoundary();
      headers['Content-Type'] = 'multipart/related; boundary=' + boundary;
      var metadata_ = metadataForUpload_(location, blob, metadata);
      var metadataString = toResourceString(metadata_, mappings);
      var preBlobPart = '--' +
          boundary +
          '\r\n' +
          'Content-Type: application/json; charset=utf-8\r\n\r\n' +
          metadataString +
          '\r\n--' +
          boundary +
          '\r\n' +
          'Content-Type: ' +
          metadata_['contentType'] +
          '\r\n\r\n';
      var postBlobPart = '\r\n--' + boundary + '--';
      var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);
      if (body === null) {
          throw cannotSliceBlob();
      }
      var urlParams = { name: metadata_['fullPath'] };
      var url = makeUrl(urlPart);
      var method = 'POST';
      var timeout = authWrapper.maxUploadRetryTime();
      var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);
      requestInfo.urlParams = urlParams;
      requestInfo.headers = headers;
      requestInfo.body = body.uploadData();
      requestInfo.errorHandler = sharedErrorHandler(location);
      return requestInfo;
  }
  /**
   * @param current The number of bytes that have been uploaded so far.
   * @param total The total number of bytes in the upload.
   * @param opt_finalized True if the server has finished the upload.
   * @param opt_metadata The upload metadata, should
   *     only be passed if opt_finalized is true.
   * @struct
   */
  var ResumableUploadStatus = /** @class */ (function () {
      function ResumableUploadStatus(current, total, finalized, metadata) {
          this.current = current;
          this.total = total;
          this.finalized = !!finalized;
          this.metadata = metadata || null;
      }
      return ResumableUploadStatus;
  }());
  function checkResumeHeader_(xhr, allowed) {
      var status = null;
      try {
          status = xhr.getResponseHeader('X-Goog-Upload-Status');
      }
      catch (e) {
          handlerCheck(false);
      }
      var allowedStatus = allowed || ['active'];
      handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);
      return status;
  }
  function createResumableUpload(authWrapper, location, mappings, blob, metadata) {
      var urlPart = location.bucketOnlyServerUrl();
      var metadataForUpload = metadataForUpload_(location, blob, metadata);
      var urlParams = { name: metadataForUpload['fullPath'] };
      var url = makeUrl(urlPart);
      var method = 'POST';
      var headers = {
          'X-Goog-Upload-Protocol': 'resumable',
          'X-Goog-Upload-Command': 'start',
          'X-Goog-Upload-Header-Content-Length': blob.size(),
          'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType'],
          'Content-Type': 'application/json; charset=utf-8'
      };
      var body = toResourceString(metadataForUpload, mappings);
      var timeout = authWrapper.maxUploadRetryTime();
      function handler(xhr) {
          checkResumeHeader_(xhr);
          var url;
          try {
              url = xhr.getResponseHeader('X-Goog-Upload-URL');
          }
          catch (e) {
              handlerCheck(false);
          }
          handlerCheck(isString(url));
          return url;
      }
      var requestInfo = new RequestInfo(url, method, handler, timeout);
      requestInfo.urlParams = urlParams;
      requestInfo.headers = headers;
      requestInfo.body = body;
      requestInfo.errorHandler = sharedErrorHandler(location);
      return requestInfo;
  }
  /**
   * @param url From a call to fbs.requests.createResumableUpload.
   */
  function getResumableUploadStatus(authWrapper, location, url, blob) {
      var headers = { 'X-Goog-Upload-Command': 'query' };
      function handler(xhr) {
          var status = checkResumeHeader_(xhr, ['active', 'final']);
          var sizeString = null;
          try {
              sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');
          }
          catch (e) {
              handlerCheck(false);
          }
          if (!sizeString) {
              // null or empty string
              handlerCheck(false);
          }
          var size = Number(sizeString);
          handlerCheck(!isNaN(size));
          return new ResumableUploadStatus(size, blob.size(), status === 'final');
      }
      var method = 'POST';
      var timeout = authWrapper.maxUploadRetryTime();
      var requestInfo = new RequestInfo(url, method, handler, timeout);
      requestInfo.headers = headers;
      requestInfo.errorHandler = sharedErrorHandler(location);
      return requestInfo;
  }
  /**
   * Any uploads via the resumable upload API must transfer a number of bytes
   * that is a multiple of this number.
   */
  var resumableUploadChunkSize = 256 * 1024;
  /**
   * @param url From a call to fbs.requests.createResumableUpload.
   * @param chunkSize Number of bytes to upload.
   * @param status The previous status.
   *     If not passed or null, we start from the beginning.
   * @throws fbs.Error If the upload is already complete, the passed in status
   *     has a final size inconsistent with the blob, or the blob cannot be sliced
   *     for upload.
   */
  function continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, status, progressCallback) {
      // TODO(andysoto): standardize on internal asserts
      // assert(!(opt_status && opt_status.finalized));
      var status_ = new ResumableUploadStatus(0, 0);
      if (status) {
          status_.current = status.current;
          status_.total = status.total;
      }
      else {
          status_.current = 0;
          status_.total = blob.size();
      }
      if (blob.size() !== status_.total) {
          throw serverFileWrongSize();
      }
      var bytesLeft = status_.total - status_.current;
      var bytesToUpload = bytesLeft;
      if (chunkSize > 0) {
          bytesToUpload = Math.min(bytesToUpload, chunkSize);
      }
      var startByte = status_.current;
      var endByte = startByte + bytesToUpload;
      var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';
      var headers = {
          'X-Goog-Upload-Command': uploadCommand,
          'X-Goog-Upload-Offset': status_.current
      };
      var body = blob.slice(startByte, endByte);
      if (body === null) {
          throw cannotSliceBlob();
      }
      function handler(xhr, text) {
          // TODO(andysoto): Verify the MD5 of each uploaded range:
          // the 'x-range-md5' header comes back with status code 308 responses.
          // We'll only be able to bail out though, because you can't re-upload a
          // range that you previously uploaded.
          var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);
          var newCurrent = status_.current + bytesToUpload;
          var size = blob.size();
          var metadata;
          if (uploadStatus === 'final') {
              metadata = metadataHandler(authWrapper, mappings)(xhr, text);
          }
          else {
              metadata = null;
          }
          return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);
      }
      var method = 'POST';
      var timeout = authWrapper.maxUploadRetryTime();
      var requestInfo = new RequestInfo(url, method, handler, timeout);
      requestInfo.headers = headers;
      requestInfo.body = body.uploadData();
      requestInfo.progressCallback = progressCallback || null;
      requestInfo.errorHandler = sharedErrorHandler(location);
      return requestInfo;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @struct
   */
  var Observer = /** @class */ (function () {
      function Observer(nextOrObserver, error, complete) {
          var asFunctions = isFunction(nextOrObserver) ||
              isDef(error) ||
              isDef(complete);
          if (asFunctions) {
              this.next = nextOrObserver;
              this.error = error || null;
              this.complete = complete || null;
          }
          else {
              var observer = nextOrObserver;
              this.next = observer.next || null;
              this.error = observer.error || null;
              this.complete = observer.complete || null;
          }
      }
      return Observer;
  }());
  
  var UploadTaskSnapshot = /** @class */ (function () {
      function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {
          this.bytesTransferred = bytesTransferred;
          this.totalBytes = totalBytes;
          this.state = state;
          this.metadata = metadata;
          this.task = task;
          this.ref = ref;
      }
      return UploadTaskSnapshot;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @param name Name of the function.
   * @param specs Argument specs.
   * @param passed The actual arguments passed to the function.
   * @throws {fbs.Error} If the arguments are invalid.
   */
  function validate(name, specs, passed) {
      var minArgs = specs.length;
      var maxArgs = specs.length;
      for (var i = 0; i < specs.length; i++) {
          if (specs[i].optional) {
              minArgs = i;
              break;
          }
      }
      var validLength = minArgs <= passed.length && passed.length <= maxArgs;
      if (!validLength) {
          throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);
      }
      for (var i = 0; i < passed.length; i++) {
          try {
              specs[i].validator(passed[i]);
          }
          catch (e) {
              if (e instanceof Error) {
                  throw invalidArgument(i, name, e.message);
              }
              else {
                  throw invalidArgument(i, name, e);
              }
          }
      }
  }
  /**
   * @struct
   */
  var ArgSpec = /** @class */ (function () {
      function ArgSpec(validator, optional) {
          var self = this;
          this.validator = function (p) {
              if (self.optional && !isJustDef(p)) {
                  return;
              }
              validator(p);
          };
          this.optional = !!optional;
      }
      return ArgSpec;
  }());
  function and_(v1, v2) {
      return function (p) {
          v1(p);
          v2(p);
      };
  }
  function stringSpec(validator, optional) {
      function stringValidator(p) {
          if (!isString(p)) {
              throw 'Expected string.';
          }
      }
      var chainedValidator;
      if (validator) {
          chainedValidator = and_(stringValidator, validator);
      }
      else {
          chainedValidator = stringValidator;
      }
      return new ArgSpec(chainedValidator, optional);
  }
  function uploadDataSpec() {
      function validator(p) {
          var valid = p instanceof Uint8Array ||
              p instanceof ArrayBuffer ||
              (isNativeBlobDefined() && p instanceof Blob);
          if (!valid) {
              throw 'Expected Blob or File.';
          }
      }
      return new ArgSpec(validator);
  }
  function metadataSpec(optional) {
      return new ArgSpec(metadataValidator, optional);
  }
  function listOptionSpec(optional) {
      return new ArgSpec(listOptionsValidator, optional);
  }
  function nonNegativeNumberSpec() {
      function validator(p) {
          var valid = isNumber(p) && p >= 0;
          if (!valid) {
              throw 'Expected a number 0 or greater.';
          }
      }
      return new ArgSpec(validator);
  }
  function looseObjectSpec(validator, optional) {
      function isLooseObjectValidator(p) {
          var isLooseObject = p === null || (isDef(p) && p instanceof Object);
          if (!isLooseObject) {
              throw 'Expected an Object.';
          }
          if (validator !== undefined && validator !== null) {
              validator(p);
          }
      }
      return new ArgSpec(isLooseObjectValidator, optional);
  }
  function nullFunctionSpec(optional) {
      function validator(p) {
          var valid = p === null || isFunction(p);
          if (!valid) {
              throw 'Expected a Function.';
          }
      }
      return new ArgSpec(validator, optional);
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Returns a function that invokes f with its arguments asynchronously as a
   * microtask, i.e. as soon as possible after the current script returns back
   * into browser code.
   */
  function async(f) {
      return function () {
          var argsToForward = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              argsToForward[_i] = arguments[_i];
          }
          // tslint:disable-next-line:no-floating-promises
          Promise.resolve().then(function () { return f.apply(void 0, argsToForward); });
      };
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Represents a blob being uploaded. Can be used to pause/resume/cancel the
   * upload and manage callbacks for various events.
   */
  var UploadTask = /** @class */ (function () {
      /**
       * @param ref The firebaseStorage.Reference object this task came
       *     from, untyped to avoid cyclic dependencies.
       * @param blob The blob to upload.
       */
      function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {
          var _this = this;
          if (metadata === void 0) { metadata = null; }
          this.transferred_ = 0;
          this.needToFetchStatus_ = false;
          this.needToFetchMetadata_ = false;
          this.observers_ = [];
          this.error_ = null;
          this.uploadUrl_ = null;
          this.request_ = null;
          this.chunkMultiplier_ = 1;
          this.resolve_ = null;
          this.reject_ = null;
          this.ref_ = ref;
          this.authWrapper_ = authWrapper;
          this.location_ = location;
          this.blob_ = blob;
          this.metadata_ = metadata;
          this.mappings_ = mappings;
          this.resumable_ = this.shouldDoResumable_(this.blob_);
          this.state_ = InternalTaskState.RUNNING;
          this.errorHandler_ = function (error) {
              _this.request_ = null;
              _this.chunkMultiplier_ = 1;
              if (error.codeEquals(Code.CANCELED)) {
                  _this.needToFetchStatus_ = true;
                  _this.completeTransitions_();
              }
              else {
                  _this.error_ = error;
                  _this.transition_(InternalTaskState.ERROR);
              }
          };
          this.metadataErrorHandler_ = function (error) {
              _this.request_ = null;
              if (error.codeEquals(Code.CANCELED)) {
                  _this.completeTransitions_();
              }
              else {
                  _this.error_ = error;
                  _this.transition_(InternalTaskState.ERROR);
              }
          };
          this.promise_ = new Promise(function (resolve, reject) {
              _this.resolve_ = resolve;
              _this.reject_ = reject;
              _this.start_();
          });
          // Prevent uncaught rejections on the internal promise from bubbling out
          // to the top level with a dummy handler.
          this.promise_.then(null, function () { });
      }
      UploadTask.prototype.makeProgressCallback_ = function () {
          var _this = this;
          var sizeBefore = this.transferred_;
          return function (loaded) { return _this.updateProgress_(sizeBefore + loaded); };
      };
      UploadTask.prototype.shouldDoResumable_ = function (blob) {
          return blob.size() > 256 * 1024;
      };
      UploadTask.prototype.start_ = function () {
          if (this.state_ !== InternalTaskState.RUNNING) {
              // This can happen if someone pauses us in a resume callback, for example.
              return;
          }
          if (this.request_ !== null) {
              return;
          }
          if (this.resumable_) {
              if (this.uploadUrl_ === null) {
                  this.createResumable_();
              }
              else {
                  if (this.needToFetchStatus_) {
                      this.fetchStatus_();
                  }
                  else {
                      if (this.needToFetchMetadata_) {
                          // Happens if we miss the metadata on upload completion.
                          this.fetchMetadata_();
                      }
                      else {
                          this.continueUpload_();
                      }
                  }
              }
          }
          else {
              this.oneShotUpload_();
          }
      };
      UploadTask.prototype.resolveToken_ = function (callback) {
          var _this = this;
          // tslint:disable-next-line:no-floating-promises
          this.authWrapper_.getAuthToken().then(function (authToken) {
              switch (_this.state_) {
                  case InternalTaskState.RUNNING:
                      callback(authToken);
                      break;
                  case InternalTaskState.CANCELING:
                      _this.transition_(InternalTaskState.CANCELED);
                      break;
                  case InternalTaskState.PAUSING:
                      _this.transition_(InternalTaskState.PAUSED);
                      break;
                  default:
              }
          });
      };
      // TODO(andysoto): assert false
      UploadTask.prototype.createResumable_ = function () {
          var _this = this;
          this.resolveToken_(function (authToken) {
              var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);
              var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
              _this.request_ = createRequest;
              createRequest.getPromise().then(function (url) {
                  _this.request_ = null;
                  _this.uploadUrl_ = url;
                  _this.needToFetchStatus_ = false;
                  _this.completeTransitions_();
              }, _this.errorHandler_);
          });
      };
      UploadTask.prototype.fetchStatus_ = function () {
          var _this = this;
          // TODO(andysoto): assert(this.uploadUrl_ !== null);
          var url = this.uploadUrl_;
          this.resolveToken_(function (authToken) {
              var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);
              var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
              _this.request_ = statusRequest;
              statusRequest.getPromise().then(function (status) {
                  status = status;
                  _this.request_ = null;
                  _this.updateProgress_(status.current);
                  _this.needToFetchStatus_ = false;
                  if (status.finalized) {
                      _this.needToFetchMetadata_ = true;
                  }
                  _this.completeTransitions_();
              }, _this.errorHandler_);
          });
      };
      UploadTask.prototype.continueUpload_ = function () {
          var _this = this;
          var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;
          var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());
          // TODO(andysoto): assert(this.uploadUrl_ !== null);
          var url = this.uploadUrl_;
          this.resolveToken_(function (authToken) {
              var requestInfo;
              try {
                  requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());
              }
              catch (e) {
                  _this.error_ = e;
                  _this.transition_(InternalTaskState.ERROR);
                  return;
              }
              var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
              _this.request_ = uploadRequest;
              uploadRequest
                  .getPromise()
                  .then(function (newStatus) {
                  _this.increaseMultiplier_();
                  _this.request_ = null;
                  _this.updateProgress_(newStatus.current);
                  if (newStatus.finalized) {
                      _this.metadata_ = newStatus.metadata;
                      _this.transition_(InternalTaskState.SUCCESS);
                  }
                  else {
                      _this.completeTransitions_();
                  }
              }, _this.errorHandler_);
          });
      };
      UploadTask.prototype.increaseMultiplier_ = function () {
          var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;
          // Max chunk size is 32M.
          if (currentSize < 32 * 1024 * 1024) {
              this.chunkMultiplier_ *= 2;
          }
      };
      UploadTask.prototype.fetchMetadata_ = function () {
          var _this = this;
          this.resolveToken_(function (authToken) {
              var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);
              var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
              _this.request_ = metadataRequest;
              metadataRequest.getPromise().then(function (metadata) {
                  _this.request_ = null;
                  _this.metadata_ = metadata;
                  _this.transition_(InternalTaskState.SUCCESS);
              }, _this.metadataErrorHandler_);
          });
      };
      UploadTask.prototype.oneShotUpload_ = function () {
          var _this = this;
          this.resolveToken_(function (authToken) {
              var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);
              var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
              _this.request_ = multipartRequest;
              multipartRequest.getPromise().then(function (metadata) {
                  _this.request_ = null;
                  _this.metadata_ = metadata;
                  _this.updateProgress_(_this.blob_.size());
                  _this.transition_(InternalTaskState.SUCCESS);
              }, _this.errorHandler_);
          });
      };
      UploadTask.prototype.updateProgress_ = function (transferred) {
          var old = this.transferred_;
          this.transferred_ = transferred;
          // A progress update can make the "transferred" value smaller (e.g. a
          // partial upload not completed by server, after which the "transferred"
          // value may reset to the value at the beginning of the request).
          if (this.transferred_ !== old) {
              this.notifyObservers_();
          }
      };
      UploadTask.prototype.transition_ = function (state) {
          if (this.state_ === state) {
              return;
          }
          switch (state) {
              case InternalTaskState.CANCELING:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.RUNNING ||
                  //        this.state_ === InternalTaskState.PAUSING);
                  this.state_ = state;
                  if (this.request_ !== null) {
                      this.request_.cancel();
                  }
                  break;
              case InternalTaskState.PAUSING:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.RUNNING);
                  this.state_ = state;
                  if (this.request_ !== null) {
                      this.request_.cancel();
                  }
                  break;
              case InternalTaskState.RUNNING:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.PAUSED ||
                  //        this.state_ === InternalTaskState.PAUSING);
                  var wasPaused = this.state_ === InternalTaskState.PAUSED;
                  this.state_ = state;
                  if (wasPaused) {
                      this.notifyObservers_();
                      this.start_();
                  }
                  break;
              case InternalTaskState.PAUSED:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.PAUSING);
                  this.state_ = state;
                  this.notifyObservers_();
                  break;
              case InternalTaskState.CANCELED:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.PAUSED ||
                  //        this.state_ === InternalTaskState.CANCELING);
                  this.error_ = canceled();
                  this.state_ = state;
                  this.notifyObservers_();
                  break;
              case InternalTaskState.ERROR:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.RUNNING ||
                  //        this.state_ === InternalTaskState.PAUSING ||
                  //        this.state_ === InternalTaskState.CANCELING);
                  this.state_ = state;
                  this.notifyObservers_();
                  break;
              case InternalTaskState.SUCCESS:
                  // TODO(andysoto):
                  // assert(this.state_ === InternalTaskState.RUNNING ||
                  //        this.state_ === InternalTaskState.PAUSING ||
                  //        this.state_ === InternalTaskState.CANCELING);
                  this.state_ = state;
                  this.notifyObservers_();
                  break;
              default: // Ignore
          }
      };
      UploadTask.prototype.completeTransitions_ = function () {
          switch (this.state_) {
              case InternalTaskState.PAUSING:
                  this.transition_(InternalTaskState.PAUSED);
                  break;
              case InternalTaskState.CANCELING:
                  this.transition_(InternalTaskState.CANCELED);
                  break;
              case InternalTaskState.RUNNING:
                  this.start_();
                  break;
              default:
                  // TODO(andysoto): assert(false);
                  break;
          }
      };
      Object.defineProperty(UploadTask.prototype, "snapshot", {
          get: function () {
              var externalState = taskStateFromInternalTaskState(this.state_);
              return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);
          },
          enumerable: true,
          configurable: true
      });
      /**
       * Adds a callback for an event.
       * @param type The type of event to listen for.
       */
      UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {
          function typeValidator() {
              if (type !== TaskEvent.STATE_CHANGED) {
                  throw "Expected one of the event types: [" + TaskEvent.STATE_CHANGED + "].";
              }
          }
          var nextOrObserverMessage = 'Expected a function or an Object with one of ' +
              '`next`, `error`, `complete` properties.';
          var nextValidator = nullFunctionSpec(true).validator;
          var observerValidator = looseObjectSpec(null, true).validator;
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          function nextOrObserverValidator(p) {
              try {
                  nextValidator(p);
                  return;
              }
              catch (e) { }
              try {
                  observerValidator(p);
                  var anyDefined = isJustDef(p['next']) ||
                      isJustDef(p['error']) ||
                      isJustDef(p['complete']);
                  if (!anyDefined) {
                      throw '';
                  }
                  return;
              }
              catch (e) {
                  throw nextOrObserverMessage;
              }
          }
          var specs = [
              stringSpec(typeValidator),
              looseObjectSpec(nextOrObserverValidator, true),
              nullFunctionSpec(true),
              nullFunctionSpec(true)
          ];
          validate('on', specs, arguments);
          var self = this;
          function makeBinder(specs) {
              function binder(nextOrObserver, error, complete) {
                  if (specs !== null) {
                      validate('on', specs, arguments);
                  }
                  var observer = new Observer(nextOrObserver, error, completed);
                  self.addObserver_(observer);
                  return function () {
                      self.removeObserver_(observer);
                  };
              }
              return binder;
          }
          function binderNextOrObserverValidator(p) {
              if (p === null) {
                  throw nextOrObserverMessage;
              }
              nextOrObserverValidator(p);
          }
          var binderSpecs = [
              looseObjectSpec(binderNextOrObserverValidator),
              nullFunctionSpec(true),
              nullFunctionSpec(true)
          ];
          var typeOnly = !(isJustDef(nextOrObserver) ||
              isJustDef(error) ||
              isJustDef(completed));
          if (typeOnly) {
              return makeBinder(binderSpecs);
          }
          else {
              return makeBinder(null)(nextOrObserver, error, completed);
          }
      };
      /**
       * This object behaves like a Promise, and resolves with its snapshot data
       * when the upload completes.
       * @param onFulfilled The fulfillment callback. Promise chaining works as normal.
       * @param onRejected The rejection callback.
       */
      UploadTask.prototype.then = function (onFulfilled, onRejected) {
          // These casts are needed so that TypeScript can infer the types of the
          // resulting Promise.
          return this.promise_.then(onFulfilled, onRejected);
      };
      /**
       * Equivalent to calling `then(null, onRejected)`.
       */
      UploadTask.prototype.catch = function (onRejected) {
          return this.then(null, onRejected);
      };
      /**
       * Adds the given observer.
       */
      UploadTask.prototype.addObserver_ = function (observer) {
          this.observers_.push(observer);
          this.notifyObserver_(observer);
      };
      /**
       * Removes the given observer.
       */
      UploadTask.prototype.removeObserver_ = function (observer) {
          var i = this.observers_.indexOf(observer);
          if (i !== -1) {
              this.observers_.splice(i, 1);
          }
      };
      UploadTask.prototype.notifyObservers_ = function () {
          var _this = this;
          this.finishPromise_();
          var observers = this.observers_.slice();
          observers.forEach(function (observer) {
              _this.notifyObserver_(observer);
          });
      };
      UploadTask.prototype.finishPromise_ = function () {
          if (this.resolve_ !== null) {
              var triggered = true;
              switch (taskStateFromInternalTaskState(this.state_)) {
                  case TaskState.SUCCESS:
                      async(this.resolve_.bind(null, this.snapshot))();
                      break;
                  case TaskState.CANCELED:
                  case TaskState.ERROR:
                      var toCall = this.reject_;
                      async(toCall.bind(null, this.error_))();
                      break;
                  default:
                      triggered = false;
                      break;
              }
              if (triggered) {
                  this.resolve_ = null;
                  this.reject_ = null;
              }
          }
      };
      UploadTask.prototype.notifyObserver_ = function (observer) {
          var externalState = taskStateFromInternalTaskState(this.state_);
          switch (externalState) {
              case TaskState.RUNNING:
              case TaskState.PAUSED:
                  if (observer.next) {
                      async(observer.next.bind(observer, this.snapshot))();
                  }
                  break;
              case TaskState.SUCCESS:
                  if (observer.complete) {
                      async(observer.complete.bind(observer))();
                  }
                  break;
              case TaskState.CANCELED:
              case TaskState.ERROR:
                  if (observer.error) {
                      async(observer.error.bind(observer, this.error_))();
                  }
                  break;
              default:
                  // TODO(andysoto): assert(false);
                  if (observer.error) {
                      async(observer.error.bind(observer, this.error_))();
                  }
          }
      };
      /**
       * Resumes a paused task. Has no effect on a currently running or failed task.
       * @return True if the operation took effect, false if ignored.
       */
      UploadTask.prototype.resume = function () {
          validate('resume', [], arguments);
          var valid = this.state_ === InternalTaskState.PAUSED ||
              this.state_ === InternalTaskState.PAUSING;
          if (valid) {
              this.transition_(InternalTaskState.RUNNING);
          }
          return valid;
      };
      /**
       * Pauses a currently running task. Has no effect on a paused or failed task.
       * @return True if the operation took effect, false if ignored.
       */
      UploadTask.prototype.pause = function () {
          validate('pause', [], arguments);
          var valid = this.state_ === InternalTaskState.RUNNING;
          if (valid) {
              this.transition_(InternalTaskState.PAUSING);
          }
          return valid;
      };
      /**
       * Cancels a currently running or paused task. Has no effect on a complete or
       * failed task.
       * @return True if the operation took effect, false if ignored.
       */
      UploadTask.prototype.cancel = function () {
          validate('cancel', [], arguments);
          var valid = this.state_ === InternalTaskState.RUNNING ||
              this.state_ === InternalTaskState.PAUSING;
          if (valid) {
              this.transition_(InternalTaskState.CANCELING);
          }
          return valid;
      };
      return UploadTask;
  }());
  
  /**
   * @license
   * Copyright 2019 Google Inc.
   *
   * 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.
   */
  /**
   * Provides methods to interact with a bucket in the Firebase Storage service.
   * @param location An fbs.location, or the URL at
   *     which to base this object, in one of the following forms:
   *         gs://<bucket>/<object-path>
   *         http[s]://firebasestorage.googleapis.com/
   *                     <api-version>/b/<bucket>/o/<object-path>
   *     Any query or fragment strings will be ignored in the http[s]
   *     format. If no value is passed, the storage object will use a URL based on
   *     the project ID of the base firebase.App instance.
   */
  var Reference = /** @class */ (function () {
      function Reference(authWrapper, location) {
          this.authWrapper = authWrapper;
          if (location instanceof Location) {
              this.location = location;
          }
          else {
              this.location = Location.makeFromUrl(location);
          }
      }
      /**
       * @return The URL for the bucket and path this object references,
       *     in the form gs://<bucket>/<object-path>
       * @override
       */
      Reference.prototype.toString = function () {
          validate('toString', [], arguments);
          return 'gs://' + this.location.bucket + '/' + this.location.path;
      };
      Reference.prototype.newRef = function (authWrapper, location) {
          return new Reference(authWrapper, location);
      };
      Reference.prototype.mappings = function () {
          return getMappings();
      };
      /**
       * @return A reference to the object obtained by
       *     appending childPath, removing any duplicate, beginning, or trailing
       *     slashes.
       */
      Reference.prototype.child = function (childPath) {
          validate('child', [stringSpec()], arguments);
          var newPath = child(this.location.path, childPath);
          var location = new Location(this.location.bucket, newPath);
          return this.newRef(this.authWrapper, location);
      };
      Object.defineProperty(Reference.prototype, "parent", {
          /**
           * @return A reference to the parent of the
           *     current object, or null if the current object is the root.
           */
          get: function () {
              var newPath = parent(this.location.path);
              if (newPath === null) {
                  return null;
              }
              var location = new Location(this.location.bucket, newPath);
              return this.newRef(this.authWrapper, location);
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Reference.prototype, "root", {
          /**
           * @return An reference to the root of this
           *     object's bucket.
           */
          get: function () {
              var location = new Location(this.location.bucket, '');
              return this.newRef(this.authWrapper, location);
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Reference.prototype, "bucket", {
          get: function () {
              return this.location.bucket;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Reference.prototype, "fullPath", {
          get: function () {
              return this.location.path;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Reference.prototype, "name", {
          get: function () {
              return lastComponent(this.location.path);
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Reference.prototype, "storage", {
          get: function () {
              return this.authWrapper.service();
          },
          enumerable: true,
          configurable: true
      });
      /**
       * Uploads a blob to this object's location.
       * @param data The blob to upload.
       * @return An UploadTask that lets you control and
       *     observe the upload.
       */
      Reference.prototype.put = function (data, metadata) {
          if (metadata === void 0) { metadata = null; }
          validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);
          this.throwIfRoot_('put');
          return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);
      };
      /**
       * Uploads a string to this object's location.
       * @param value The string to upload.
       * @param format The format of the string to upload.
       * @return An UploadTask that lets you control and
       *     observe the upload.
       */
      Reference.prototype.putString = function (value, format, metadata) {
          if (format === void 0) { format = StringFormat.RAW; }
          validate('putString', [stringSpec(), stringSpec(formatValidator, true), metadataSpec(true)], arguments);
          this.throwIfRoot_('putString');
          var data = dataFromString(format, value);
          var metadataClone = Object.assign({}, metadata);
          if (!isDef(metadataClone['contentType']) &&
              isDef(data.contentType)) {
              metadataClone['contentType'] = data.contentType;
          }
          return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadataClone);
      };
      /**
       * Deletes the object at this location.
       * @return A promise that resolves if the deletion succeeds.
       */
      Reference.prototype.delete = function () {
          var _this = this;
          validate('delete', [], arguments);
          this.throwIfRoot_('delete');
          return this.authWrapper.getAuthToken().then(function (authToken) {
              var requestInfo = deleteObject(_this.authWrapper, _this.location);
              return _this.authWrapper.makeRequest(requestInfo, authToken).getPromise();
          });
      };
      /**
       * List all items (files) and prefixes (folders) under this storage reference.
       *
       * This is a helper method for calling list() repeatedly until there are
       * no more results. The default pagination size is 1000.
       *
       * Note: The results may not be consistent if objects are changed while this
       * operation is running.
       *
       * Warning: listAll may potentially consume too many resources if there are
       * too many results.
       *
       * @return A Promise that resolves with all the items and prefixes under
       *      the current storage reference. `prefixes` contains references to
       *      sub-directories and `items` contains references to objects in this
       *      folder. `nextPageToken` is never returned.
       */
      Reference.prototype.listAll = function () {
          validate('listAll', [], arguments);
          var accumulator = {
              prefixes: [],
              items: []
          };
          return this.listAllHelper(accumulator).then(function () { return accumulator; });
      };
      Reference.prototype.listAllHelper = function (accumulator, pageToken) {
          return Object(tslib__WEBPACK_IMPORTED_MODULE_1__["__awaiter"])(this, void 0, void 0, function () {
              var opt, nextPage;
              var _a, _b;
              return Object(tslib__WEBPACK_IMPORTED_MODULE_1__["__generator"])(this, function (_c) {
                  switch (_c.label) {
                      case 0:
                          opt = {
                              // maxResults is 1000 by default.
                              pageToken: pageToken
                          };
                          return [4 /*yield*/, this.list(opt)];
                      case 1:
                          nextPage = _c.sent();
                          (_a = accumulator.prefixes).push.apply(_a, nextPage.prefixes);
                          (_b = accumulator.items).push.apply(_b, nextPage.items);
                          if (!(nextPage.nextPageToken != null)) return [3 /*break*/, 3];
                          return [4 /*yield*/, this.listAllHelper(accumulator, nextPage.nextPageToken)];
                      case 2:
                          _c.sent();
                          _c.label = 3;
                      case 3: return [2 /*return*/];
                  }
              });
          });
      };
      /**
       * List items (files) and prefixes (folders) under this storage reference.
       *
       * List API is only available for Firebase Rules Version 2.
       *
       * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
       * delimited folder structure.
       * Refer to GCS's List API if you want to learn more.
       *
       * To adhere to Firebase Rules's Semantics, Firebase Storage does not
       * support objects whose paths end with "/" or contain two consecutive
       * "/"s. Firebase Storage List API will filter these unsupported objects.
       * list() may fail if there are too many unsupported objects in the bucket.
       *
       * @param options See ListOptions for details.
       * @return A Promise that resolves with the items and prefixes.
       *      `prefixes` contains references to sub-folders and `items`
       *      contains references to objects in this folder. `nextPageToken`
       *      can be used to get the rest of the results.
       */
      Reference.prototype.list = function (options) {
          validate('list', [listOptionSpec(true)], arguments);
          var self = this;
          return this.authWrapper.getAuthToken().then(function (authToken) {
              var op = options || {};
              var requestInfo = list(self.authWrapper, self.location, 
              /*delimiter= */ '/', op.pageToken, op.maxResults);
              return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();
          });
      };
      /**
       *     A promise that resolves with the metadata for this object. If this
       *     object doesn't exist or metadata cannot be retreived, the promise is
       *     rejected.
       */
      Reference.prototype.getMetadata = function () {
          var _this = this;
          validate('getMetadata', [], arguments);
          this.throwIfRoot_('getMetadata');
          return this.authWrapper.getAuthToken().then(function (authToken) {
              var requestInfo = getMetadata(_this.authWrapper, _this.location, _this.mappings());
              return _this.authWrapper.makeRequest(requestInfo, authToken).getPromise();
          });
      };
      /**
       * Updates the metadata for this object.
       * @param metadata The new metadata for the object.
       *     Only values that have been explicitly set will be changed. Explicitly
       *     setting a value to null will remove the metadata.
       * @return A promise that resolves
       *     with the new metadata for this object.
       *     @see firebaseStorage.Reference.prototype.getMetadata
       */
      Reference.prototype.updateMetadata = function (metadata) {
          var _this = this;
          validate('updateMetadata', [metadataSpec()], arguments);
          this.throwIfRoot_('updateMetadata');
          return this.authWrapper.getAuthToken().then(function (authToken) {
              var requestInfo = updateMetadata(_this.authWrapper, _this.location, metadata, _this.mappings());
              return _this.authWrapper.makeRequest(requestInfo, authToken).getPromise();
          });
      };
      /**
       * @return A promise that resolves with the download
       *     URL for this object.
       */
      Reference.prototype.getDownloadURL = function () {
          var _this = this;
          validate('getDownloadURL', [], arguments);
          this.throwIfRoot_('getDownloadURL');
          return this.authWrapper.getAuthToken().then(function (authToken) {
              var requestInfo = getDownloadUrl(_this.authWrapper, _this.location, _this.mappings());
              return _this.authWrapper
                  .makeRequest(requestInfo, authToken)
                  .getPromise()
                  .then(function (url) {
                  if (url === null) {
                      throw noDownloadURL();
                  }
                  return url;
              });
          });
      };
      Reference.prototype.throwIfRoot_ = function (name) {
          if (this.location.path === '') {
              throw invalidRootOperation(name);
          }
      };
      return Reference;
  }());
  
  /**
   * A request whose promise always fails.
   * @struct
   * @template T
   */
  var FailRequest = /** @class */ (function () {
      function FailRequest(error) {
          this.promise_ = Promise.reject(error);
      }
      /** @inheritDoc */
      FailRequest.prototype.getPromise = function () {
          return this.promise_;
      };
      /** @inheritDoc */
      FailRequest.prototype.cancel = function (_appDelete) {
      };
      return FailRequest;
  }());
  
  var RequestMap = /** @class */ (function () {
      function RequestMap() {
          this.map = new Map();
          this.id = MIN_SAFE_INTEGER;
      }
      /**
       * Registers the given request with this map.
       * The request is unregistered when it completes.
       *
       * @param request The request to register.
       */
      RequestMap.prototype.addRequest = function (request) {
          var _this = this;
          var id = this.id;
          this.id++;
          this.map.set(id, request);
          request
              .getPromise()
              .then(function () { return _this.map.delete(id); }, function () { return _this.map.delete(id); });
      };
      /**
       * Cancels all registered requests.
       */
      RequestMap.prototype.clear = function () {
          this.map.forEach(function (v) {
              v && v.cancel(true);
          });
          this.map.clear();
      };
      return RequestMap;
  }());
  
  /**
   * @param app If null, getAuthToken always resolves with null.
   * @param service The storage service associated with this auth wrapper.
   *     Untyped to avoid circular type dependencies.
   * @struct
   */
  var AuthWrapper = /** @class */ (function () {
      function AuthWrapper(app, maker, requestMaker, service, pool) {
          this.bucket_ = null;
          this.deleted_ = false;
          this.app_ = app;
          if (this.app_ !== null) {
              var options = this.app_.options;
              if (isDef(options)) {
                  this.bucket_ = AuthWrapper.extractBucket_(options);
              }
          }
          this.storageRefMaker_ = maker;
          this.requestMaker_ = requestMaker;
          this.pool_ = pool;
          this.service_ = service;
          this.maxOperationRetryTime_ = DEFAULT_MAX_OPERATION_RETRY_TIME;
          this.maxUploadRetryTime_ = DEFAULT_MAX_UPLOAD_RETRY_TIME;
          this.requestMap_ = new RequestMap();
      }
      AuthWrapper.extractBucket_ = function (config) {
          var bucketString = config[CONFIG_STORAGE_BUCKET_KEY] || null;
          if (bucketString == null) {
              return null;
          }
          var loc = Location.makeFromBucketSpec(bucketString);
          return loc.bucket;
      };
      AuthWrapper.prototype.getAuthToken = function () {
          // TODO(andysoto): remove ifDef checks after firebase-app implements stubs
          // (b/28673818).
          if (this.app_ !== null &&
              isDef(this.app_.INTERNAL) &&
              isDef(this.app_.INTERNAL.getToken)) {
              return this.app_.INTERNAL.getToken().then(function (response) {
                  if (response !== null) {
                      return response.accessToken;
                  }
                  else {
                      return null;
                  }
              }, function () { return null; });
          }
          else {
              return Promise.resolve(null);
          }
      };
      AuthWrapper.prototype.bucket = function () {
          if (this.deleted_) {
              throw appDeleted();
          }
          else {
              return this.bucket_;
          }
      };
      /**
       * The service associated with this auth wrapper. Untyped to avoid circular
       * type dependencies.
       */
      AuthWrapper.prototype.service = function () {
          return this.service_;
      };
      /**
       * Returns a new firebaseStorage.Reference object referencing this AuthWrapper
       * at the given Location.
       * @param loc The Location.
       * @return Actually a firebaseStorage.Reference, typing not allowed
       *     because of circular dependency problems.
       */
      AuthWrapper.prototype.makeStorageReference = function (loc) {
          return this.storageRefMaker_(this, loc);
      };
      AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {
          if (!this.deleted_) {
              var request = this.requestMaker_(requestInfo, authToken, this.pool_);
              this.requestMap_.addRequest(request);
              return request;
          }
          else {
              return new FailRequest(appDeleted());
          }
      };
      /**
       * Stop running requests and prevent more from being created.
       */
      AuthWrapper.prototype.deleteApp = function () {
          this.deleted_ = true;
          this.app_ = null;
          this.requestMap_.clear();
      };
      AuthWrapper.prototype.maxUploadRetryTime = function () {
          return this.maxUploadRetryTime_;
      };
      AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {
          this.maxUploadRetryTime_ = time;
      };
      AuthWrapper.prototype.maxOperationRetryTime = function () {
          return this.maxOperationRetryTime_;
      };
      AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {
          this.maxOperationRetryTime_ = time;
      };
      return AuthWrapper;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @param f May be invoked
   *     before the function returns.
   * @param callback Get all the arguments passed to the function
   *     passed to f, including the initial boolean.
   */
  function start(f, callback, timeout) {
      // TODO(andysoto): make this code cleaner (probably refactor into an actual
      // type instead of a bunch of functions with state shared in the closure)
      var waitSeconds = 1;
      // Would type this as "number" but that doesn't work for Node so ¯\_(ツ)_/¯
      // TODO: find a way to exclude Node type definition for storage because storage only works in browser
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      var timeoutId = null;
      var hitTimeout = false;
      var cancelState = 0;
      function canceled() {
          return cancelState === 2;
      }
      var triggeredCallback = false;
      // TODO: This disable can be removed and the 'ignoreRestArgs' option added to
      // the no-explicit-any rule when ESlint releases it.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      function triggerCallback() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          if (!triggeredCallback) {
              triggeredCallback = true;
              callback.apply(null, args);
          }
      }
      function callWithDelay(millis) {
          timeoutId = setTimeout(function () {
              timeoutId = null;
              f(handler, canceled());
          }, millis);
      }
      // TODO: This disable can be removed and the 'ignoreRestArgs' option added to
      // the no-explicit-any rule when ESlint releases it.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      function handler(success) {
          var args = [];
          for (var _i = 1; _i < arguments.length; _i++) {
              args[_i - 1] = arguments[_i];
          }
          if (triggeredCallback) {
              return;
          }
          if (success) {
              triggerCallback.call.apply(triggerCallback, [null, success].concat(args));
              return;
          }
          var mustStop = canceled() || hitTimeout;
          if (mustStop) {
              triggerCallback.call.apply(triggerCallback, [null, success].concat(args));
              return;
          }
          if (waitSeconds < 64) {
              /* TODO(andysoto): don't back off so quickly if we know we're offline. */
              waitSeconds *= 2;
          }
          var waitMillis;
          if (cancelState === 1) {
              cancelState = 2;
              waitMillis = 0;
          }
          else {
              waitMillis = (waitSeconds + Math.random()) * 1000;
          }
          callWithDelay(waitMillis);
      }
      var stopped = false;
      function stop(wasTimeout) {
          if (stopped) {
              return;
          }
          stopped = true;
          if (triggeredCallback) {
              return;
          }
          if (timeoutId !== null) {
              if (!wasTimeout) {
                  cancelState = 2;
              }
              clearTimeout(timeoutId);
              callWithDelay(0);
          }
          else {
              if (!wasTimeout) {
                  cancelState = 1;
              }
          }
      }
      callWithDelay(0);
      setTimeout(function () {
          hitTimeout = true;
          stop(true);
      }, timeout);
      return stop;
  }
  /**
   * Stops the retry loop from repeating.
   * If the function is currently "in between" retries, it is invoked immediately
   * with the second parameter as "true". Otherwise, it will be invoked once more
   * after the current invocation finishes iff the current invocation would have
   * triggered another retry.
   */
  function stop(id) {
      id(false);
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * @struct
   * @template T
   */
  var NetworkRequest = /** @class */ (function () {
      function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {
          var _this = this;
          this.pendingXhr_ = null;
          this.backoffId_ = null;
          this.resolve_ = null;
          this.reject_ = null;
          this.canceled_ = false;
          this.appDelete_ = false;
          this.url_ = url;
          this.method_ = method;
          this.headers_ = headers;
          this.body_ = body;
          this.successCodes_ = successCodes.slice();
          this.additionalRetryCodes_ = additionalRetryCodes.slice();
          this.callback_ = callback;
          this.errorCallback_ = errorCallback;
          this.progressCallback_ = progressCallback;
          this.timeout_ = timeout;
          this.pool_ = pool;
          this.promise_ = new Promise(function (resolve, reject) {
              _this.resolve_ = resolve;
              _this.reject_ = reject;
              _this.start_();
          });
      }
      /**
       * Actually starts the retry loop.
       */
      NetworkRequest.prototype.start_ = function () {
          var self = this;
          function doTheRequest(backoffCallback, canceled) {
              if (canceled) {
                  backoffCallback(false, new RequestEndStatus(false, null, true));
                  return;
              }
              var xhr = self.pool_.createXhrIo();
              self.pendingXhr_ = xhr;
              function progressListener(progressEvent) {
                  var loaded = progressEvent.loaded;
                  var total = progressEvent.lengthComputable ? progressEvent.total : -1;
                  if (self.progressCallback_ !== null) {
                      self.progressCallback_(loaded, total);
                  }
              }
              if (self.progressCallback_ !== null) {
                  xhr.addUploadProgressListener(progressListener);
              }
              // tslint:disable-next-line:no-floating-promises
              xhr
                  .send(self.url_, self.method_, self.body_, self.headers_)
                  .then(function (xhr) {
                  if (self.progressCallback_ !== null) {
                      xhr.removeUploadProgressListener(progressListener);
                  }
                  self.pendingXhr_ = null;
                  xhr = xhr;
                  var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;
                  var status = xhr.getStatus();
                  if (!hitServer || self.isRetryStatusCode_(status)) {
                      var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;
                      backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
                      return;
                  }
                  var successCode = self.successCodes_.indexOf(status) !== -1;
                  backoffCallback(true, new RequestEndStatus(successCode, xhr));
              });
          }
          /**
           * @param requestWentThrough True if the request eventually went
           *     through, false if it hit the retry limit or was canceled.
           */
          function backoffDone(requestWentThrough, status) {
              var resolve = self.resolve_;
              var reject = self.reject_;
              var xhr = status.xhr;
              if (status.wasSuccessCode) {
                  try {
                      var result = self.callback_(xhr, xhr.getResponseText());
                      if (isJustDef(result)) {
                          resolve(result);
                      }
                      else {
                          resolve();
                      }
                  }
                  catch (e) {
                      reject(e);
                  }
              }
              else {
                  if (xhr !== null) {
                      var err = unknown();
                      err.setServerResponseProp(xhr.getResponseText());
                      if (self.errorCallback_) {
                          reject(self.errorCallback_(xhr, err));
                      }
                      else {
                          reject(err);
                      }
                  }
                  else {
                      if (status.canceled) {
                          var err = self.appDelete_ ? appDeleted() : canceled();
                          reject(err);
                      }
                      else {
                          var err = retryLimitExceeded();
                          reject(err);
                      }
                  }
              }
          }
          if (this.canceled_) {
              backoffDone(false, new RequestEndStatus(false, null, true));
          }
          else {
              this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);
          }
      };
      /** @inheritDoc */
      NetworkRequest.prototype.getPromise = function () {
          return this.promise_;
      };
      /** @inheritDoc */
      NetworkRequest.prototype.cancel = function (appDelete) {
          this.canceled_ = true;
          this.appDelete_ = appDelete || false;
          if (this.backoffId_ !== null) {
              stop(this.backoffId_);
          }
          if (this.pendingXhr_ !== null) {
              this.pendingXhr_.abort();
          }
      };
      NetworkRequest.prototype.isRetryStatusCode_ = function (status) {
          // The codes for which to retry came from this page:
          // https://cloud.google.com/storage/docs/exponential-backoff
          var isFiveHundredCode = status >= 500 && status < 600;
          var extraRetryCodes = [
              // Request Timeout: web server didn't receive full request in time.
              408,
              // Too Many Requests: you're getting rate-limited, basically.
              429
          ];
          var isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
          var isRequestSpecificRetryCode = this.additionalRetryCodes_.indexOf(status) !== -1;
          return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;
      };
      return NetworkRequest;
  }());
  /**
   * A collection of information about the result of a network request.
   * @param opt_canceled Defaults to false.
   * @struct
   */
  var RequestEndStatus = /** @class */ (function () {
      function RequestEndStatus(wasSuccessCode, xhr, canceled) {
          this.wasSuccessCode = wasSuccessCode;
          this.xhr = xhr;
          this.canceled = !!canceled;
      }
      return RequestEndStatus;
  }());
  function addAuthHeader_(headers, authToken) {
      if (authToken !== null && authToken.length > 0) {
          headers['Authorization'] = 'Firebase ' + authToken;
      }
  }
  function addVersionHeader_(headers) {
      var version = typeof _firebase_app__WEBPACK_IMPORTED_MODULE_0___default.a !== 'undefined' ? _firebase_app__WEBPACK_IMPORTED_MODULE_0___default.a.SDK_VERSION : 'AppManager';
      headers['X-Firebase-Storage-Version'] = 'webjs/' + version;
  }
  /**
   * @template T
   */
  function makeRequest(requestInfo, authToken, pool) {
      var queryPart = makeQueryString(requestInfo.urlParams);
      var url = requestInfo.url + queryPart;
      var headers = Object.assign({}, requestInfo.headers);
      addAuthHeader_(headers, authToken);
      addVersionHeader_(headers);
      return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * A service that provides firebaseStorage.Reference instances.
   * @param opt_url gs:// url to a custom Storage Bucket
   *
   * @struct
   */
  var Service = /** @class */ (function () {
      function Service(app, pool, url) {
          this.bucket_ = null;
          function maker(authWrapper, loc) {
              return new Reference(authWrapper, loc);
          }
          this.authWrapper_ = new AuthWrapper(app, maker, makeRequest, this, pool);
          this.app_ = app;
          if (url != null) {
              this.bucket_ = Location.makeFromBucketSpec(url);
          }
          else {
              var authWrapperBucket = this.authWrapper_.bucket();
              if (authWrapperBucket != null) {
                  this.bucket_ = new Location(authWrapperBucket, '');
              }
          }
          this.internals_ = new ServiceInternals(this);
      }
      /**
       * Returns a firebaseStorage.Reference for the given path in the default
       * bucket.
       */
      Service.prototype.ref = function (path) {
          function validator(path) {
              if (typeof path !== 'string') {
                  throw 'Path is not a string.';
              }
              if (/^[A-Za-z]+:\/\//.test(path)) {
                  throw 'Expected child path but got a URL, use refFromURL instead.';
              }
          }
          validate('ref', [stringSpec(validator, true)], arguments);
          if (this.bucket_ == null) {
              throw new Error('No Storage Bucket defined in Firebase Options.');
          }
          var ref = new Reference(this.authWrapper_, this.bucket_);
          if (path != null) {
              return ref.child(path);
          }
          else {
              return ref;
          }
      };
      /**
       * Returns a firebaseStorage.Reference object for the given absolute URL,
       * which must be a gs:// or http[s]:// URL.
       */
      Service.prototype.refFromURL = function (url) {
          function validator(p) {
              if (typeof p !== 'string') {
                  throw 'Path is not a string.';
              }
              if (!/^[A-Za-z]+:\/\//.test(p)) {
                  throw 'Expected full URL but got a child path, use ref instead.';
              }
              try {
                  Location.makeFromUrl(p);
              }
              catch (e) {
                  throw 'Expected valid full URL but got an invalid one.';
              }
          }
          validate('refFromURL', [stringSpec(validator, false)], arguments);
          return new Reference(this.authWrapper_, url);
      };
      Object.defineProperty(Service.prototype, "maxUploadRetryTime", {
          get: function () {
              return this.authWrapper_.maxUploadRetryTime();
          },
          enumerable: true,
          configurable: true
      });
      Service.prototype.setMaxUploadRetryTime = function (time) {
          validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);
          this.authWrapper_.setMaxUploadRetryTime(time);
      };
      Service.prototype.setMaxOperationRetryTime = function (time) {
          validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);
          this.authWrapper_.setMaxOperationRetryTime(time);
      };
      Object.defineProperty(Service.prototype, "app", {
          get: function () {
              return this.app_;
          },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(Service.prototype, "INTERNAL", {
          get: function () {
              return this.internals_;
          },
          enumerable: true,
          configurable: true
      });
      return Service;
  }());
  /**
   * @struct
   */
  var ServiceInternals = /** @class */ (function () {
      function ServiceInternals(service) {
          this.service_ = service;
      }
      /**
       * Called when the associated app is deleted.
       * @see {!fbs.AuthWrapper.prototype.deleteApp}
       */
      ServiceInternals.prototype.delete = function () {
          this.service_.authWrapper_.deleteApp();
          return Promise.resolve();
      };
      return ServiceInternals;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Type constant for Firebase Storage.
   */
  var STORAGE_TYPE = 'storage';
  function factory(app, unused, url) {
      return new Service(app, new XhrIoPool(), url);
  }
  function registerStorage(instance) {
      var namespaceExports = {
          // no-inline
          TaskState: TaskState,
          TaskEvent: TaskEvent,
          StringFormat: StringFormat,
          Storage: Service,
          Reference: Reference
      };
      instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, 
      // Allow multiple storage instances per app.
      true);
  }
  registerStorage(_firebase_app__WEBPACK_IMPORTED_MODULE_0___default.a);
  
  
  //# sourceMappingURL=index.esm.js.map
  
  
  /***/ }),
  
  /***/ "./node_modules/@firebase/util/dist/index.cjs.js":
  /*!*******************************************************!*\
    !*** ./node_modules/@firebase/util/dist/index.cjs.js ***!
    \*******************************************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  "use strict";
  /* WEBPACK VAR INJECTION */(function(global) {
  
  Object.defineProperty(exports, '__esModule', { value: true });
  
  var tslib_1 = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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 Firebase constants.  Some of these (@defines) can be overridden at compile-time.
   */
  var CONSTANTS = {
      /**
       * @define {boolean} Whether this is the client Node.js SDK.
       */
      NODE_CLIENT: false,
      /**
       * @define {boolean} Whether this is the Admin Node.js SDK.
       */
      NODE_ADMIN: false,
      /**
       * Firebase SDK Version
       */
      SDK_VERSION: '${JSCORE_VERSION}'
  };
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Throws an error if the provided assertion is falsy
   */
  var assert = function (assertion, message) {
      if (!assertion) {
          throw assertionError(message);
      }
  };
  /**
   * Returns an Error object suitable for throwing.
   */
  var assertionError = function (message) {
      return new Error('Firebase Database (' +
          CONSTANTS.SDK_VERSION +
          ') INTERNAL ASSERT FAILED: ' +
          message);
  };
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  var stringToByteArray = function (str) {
      // TODO(user): Use native implementations if/when available
      var out = [];
      var p = 0;
      for (var i = 0; i < str.length; i++) {
          var c = str.charCodeAt(i);
          if (c < 128) {
              out[p++] = c;
          }
          else if (c < 2048) {
              out[p++] = (c >> 6) | 192;
              out[p++] = (c & 63) | 128;
          }
          else if ((c & 0xfc00) === 0xd800 &&
              i + 1 < str.length &&
              (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
              // Surrogate Pair
              c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
              out[p++] = (c >> 18) | 240;
              out[p++] = ((c >> 12) & 63) | 128;
              out[p++] = ((c >> 6) & 63) | 128;
              out[p++] = (c & 63) | 128;
          }
          else {
              out[p++] = (c >> 12) | 224;
              out[p++] = ((c >> 6) & 63) | 128;
              out[p++] = (c & 63) | 128;
          }
      }
      return out;
  };
  /**
   * Turns an array of numbers into the string given by the concatenation of the
   * characters to which the numbers correspond.
   * @param bytes Array of numbers representing characters.
   * @return Stringification of the array.
   */
  var byteArrayToString = function (bytes) {
      // TODO(user): Use native implementations if/when available
      var out = [];
      var pos = 0, c = 0;
      while (pos < bytes.length) {
          var c1 = bytes[pos++];
          if (c1 < 128) {
              out[c++] = String.fromCharCode(c1);
          }
          else if (c1 > 191 && c1 < 224) {
              var c2 = bytes[pos++];
              out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
          }
          else if (c1 > 239 && c1 < 365) {
              // Surrogate Pair
              var c2 = bytes[pos++];
              var c3 = bytes[pos++];
              var c4 = bytes[pos++];
              var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
                  0x10000;
              out[c++] = String.fromCharCode(0xd800 + (u >> 10));
              out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
          }
          else {
              var c2 = bytes[pos++];
              var c3 = bytes[pos++];
              out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
          }
      }
      return out.join('');
  };
  // We define it as an object literal instead of a class because a class compiled down to es5 can't
  // be treeshaked. https://github.com/rollup/rollup/issues/1691
  // Static lookup maps, lazily populated by init_()
  var base64 = {
      /**
       * Maps bytes to characters.
       */
      byteToCharMap_: null,
      /**
       * Maps characters to bytes.
       */
      charToByteMap_: null,
      /**
       * Maps bytes to websafe characters.
       * @private
       */
      byteToCharMapWebSafe_: null,
      /**
       * Maps websafe characters to bytes.
       * @private
       */
      charToByteMapWebSafe_: null,
      /**
       * Our default alphabet, shared between
       * ENCODED_VALS and ENCODED_VALS_WEBSAFE
       */
      ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
      /**
       * Our default alphabet. Value 64 (=) is special; it means "nothing."
       */
      get ENCODED_VALS() {
          return this.ENCODED_VALS_BASE + '+/=';
      },
      /**
       * Our websafe alphabet.
       */
      get ENCODED_VALS_WEBSAFE() {
          return this.ENCODED_VALS_BASE + '-_.';
      },
      /**
       * Whether this browser supports the atob and btoa functions. This extension
       * started at Mozilla but is now implemented by many browsers. We use the
       * ASSUME_* variables to avoid pulling in the full useragent detection library
       * but still allowing the standard per-browser compilations.
       *
       */
      HAS_NATIVE_SUPPORT: typeof atob === 'function',
      /**
       * Base64-encode an array of bytes.
       *
       * @param input An array of bytes (numbers with
       *     value in [0, 255]) to encode.
       * @param webSafe Boolean indicating we should use the
       *     alternative alphabet.
       * @return The base64 encoded string.
       */
      encodeByteArray: function (input, webSafe) {
          if (!Array.isArray(input)) {
              throw Error('encodeByteArray takes an array as a parameter');
          }
          this.init_();
          var byteToCharMap = webSafe
              ? this.byteToCharMapWebSafe_
              : this.byteToCharMap_;
          var output = [];
          for (var i = 0; i < input.length; i += 3) {
              var byte1 = input[i];
              var haveByte2 = i + 1 < input.length;
              var byte2 = haveByte2 ? input[i + 1] : 0;
              var haveByte3 = i + 2 < input.length;
              var byte3 = haveByte3 ? input[i + 2] : 0;
              var outByte1 = byte1 >> 2;
              var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
              var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
              var outByte4 = byte3 & 0x3f;
              if (!haveByte3) {
                  outByte4 = 64;
                  if (!haveByte2) {
                      outByte3 = 64;
                  }
              }
              output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
          }
          return output.join('');
      },
      /**
       * Base64-encode a string.
       *
       * @param input A string to encode.
       * @param webSafe If true, we should use the
       *     alternative alphabet.
       * @return The base64 encoded string.
       */
      encodeString: function (input, webSafe) {
          // Shortcut for Mozilla browsers that implement
          // a native base64 encoder in the form of "btoa/atob"
          if (this.HAS_NATIVE_SUPPORT && !webSafe) {
              return btoa(input);
          }
          return this.encodeByteArray(stringToByteArray(input), webSafe);
      },
      /**
       * Base64-decode a string.
       *
       * @param input to decode.
       * @param webSafe True if we should use the
       *     alternative alphabet.
       * @return string representing the decoded value.
       */
      decodeString: function (input, webSafe) {
          // Shortcut for Mozilla browsers that implement
          // a native base64 encoder in the form of "btoa/atob"
          if (this.HAS_NATIVE_SUPPORT && !webSafe) {
              return atob(input);
          }
          return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
      },
      /**
       * Base64-decode a string.
       *
       * In base-64 decoding, groups of four characters are converted into three
       * bytes.  If the encoder did not apply padding, the input length may not
       * be a multiple of 4.
       *
       * In this case, the last group will have fewer than 4 characters, and
       * padding will be inferred.  If the group has one or two characters, it decodes
       * to one byte.  If the group has three characters, it decodes to two bytes.
       *
       * @param input Input to decode.
       * @param webSafe True if we should use the web-safe alphabet.
       * @return bytes representing the decoded value.
       */
      decodeStringToByteArray: function (input, webSafe) {
          this.init_();
          var charToByteMap = webSafe
              ? this.charToByteMapWebSafe_
              : this.charToByteMap_;
          var output = [];
          for (var i = 0; i < input.length;) {
              var byte1 = charToByteMap[input.charAt(i++)];
              var haveByte2 = i < input.length;
              var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
              ++i;
              var haveByte3 = i < input.length;
              var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
              ++i;
              var haveByte4 = i < input.length;
              var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
              ++i;
              if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
                  throw Error();
              }
              var outByte1 = (byte1 << 2) | (byte2 >> 4);
              output.push(outByte1);
              if (byte3 !== 64) {
                  var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
                  output.push(outByte2);
                  if (byte4 !== 64) {
                      var outByte3 = ((byte3 << 6) & 0xc0) | byte4;
                      output.push(outByte3);
                  }
              }
          }
          return output;
      },
      /**
       * Lazy static initialization function. Called before
       * accessing any of the static map variables.
       * @private
       */
      init_: function () {
          if (!this.byteToCharMap_) {
              this.byteToCharMap_ = {};
              this.charToByteMap_ = {};
              this.byteToCharMapWebSafe_ = {};
              this.charToByteMapWebSafe_ = {};
              // We want quick mappings back and forth, so we precompute two maps.
              for (var i = 0; i < this.ENCODED_VALS.length; i++) {
                  this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
                  this.charToByteMap_[this.byteToCharMap_[i]] = i;
                  this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
                  this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
                  // Be forgiving when decoding and correctly decode both encodings.
                  if (i >= this.ENCODED_VALS_BASE.length) {
                      this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
                      this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
                  }
              }
          }
      }
  };
  /**
   * URL-safe base64 encoding
   */
  var base64Encode = function (str) {
      var utf8Bytes = stringToByteArray(str);
      return base64.encodeByteArray(utf8Bytes, true);
  };
  /**
   * URL-safe base64 decoding
   *
   * NOTE: DO NOT use the global atob() function - it does NOT support the
   * base64Url variant encoding.
   *
   * @param str To be decoded
   * @return Decoded result, if possible
   */
  var base64Decode = function (str) {
      try {
          return base64.decodeString(str, true);
      }
      catch (e) {
          console.error('base64Decode failed: ', e);
      }
      return null;
  };
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Do a deep-copy of basic JavaScript Objects or Arrays.
   */
  function deepCopy(value) {
      return deepExtend(undefined, value);
  }
  /**
   * Copy properties from source to target (recursively allows extension
   * of Objects and Arrays).  Scalar values in the target are over-written.
   * If target is undefined, an object of the appropriate type will be created
   * (and returned).
   *
   * We recursively copy all child properties of plain Objects in the source- so
   * that namespace- like dictionaries are merged.
   *
   * Note that the target can be a function, in which case the properties in
   * the source Object are copied onto it as static properties of the Function.
   */
  function deepExtend(target, source) {
      if (!(source instanceof Object)) {
          return source;
      }
      switch (source.constructor) {
          case Date:
              // Treat Dates like scalars; if the target date object had any child
              // properties - they will be lost!
              var dateValue = source;
              return new Date(dateValue.getTime());
          case Object:
              if (target === undefined) {
                  target = {};
              }
              break;
          case Array:
              // Always copy the array source and overwrite the target.
              target = [];
              break;
          default:
              // Not a plain Object - treat it as a scalar.
              return source;
      }
      for (var prop in source) {
          if (!source.hasOwnProperty(prop)) {
              continue;
          }
          target[prop] = deepExtend(target[prop], source[prop]);
      }
      return target;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  var Deferred = /** @class */ (function () {
      function Deferred() {
          var _this = this;
          this.reject = function () { };
          this.resolve = function () { };
          this.promise = new Promise(function (resolve, reject) {
              _this.resolve = resolve;
              _this.reject = reject;
          });
      }
      /**
       * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around
       * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
       * and returns a node-style callback which will resolve or reject the Deferred's promise.
       */
      Deferred.prototype.wrapCallback = function (callback) {
          var _this = this;
          return function (error, value) {
              if (error) {
                  _this.reject(error);
              }
              else {
                  _this.resolve(value);
              }
              if (typeof callback === 'function') {
                  // Attaching noop handler just in case developer wasn't expecting
                  // promises
                  _this.promise.catch(function () { });
                  // Some of our callbacks don't expect a value and our own tests
                  // assert that the parameter length is 1
                  if (callback.length === 1) {
                      callback(error);
                  }
                  else {
                      callback(error, value);
                  }
              }
          };
      };
      return Deferred;
  }());
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Returns navigator.userAgent string or '' if it's not defined.
   * @return user agent string
   */
  function getUA() {
      if (typeof navigator !== 'undefined' &&
          typeof navigator['userAgent'] === 'string') {
          return navigator['userAgent'];
      }
      else {
          return '';
      }
  }
  /**
   * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
   *
   * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
   * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
   * wait for a callback.
   */
  function isMobileCordova() {
      return (typeof window !== 'undefined' &&
          // @ts-ignore Setting up an broadly applicable index signature for Window
          // just to deal with this case would probably be a bad idea.
          !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&
          /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));
  }
  /**
   * Detect Node.js.
   *
   * @return true if Node.js environment is detected.
   */
  // Node detection logic from: https://github.com/iliakan/detect-node/
  function isNode() {
      try {
          return (Object.prototype.toString.call(global.process) === '[object process]');
      }
      catch (e) {
          return false;
      }
  }
  /**
   * Detect Browser Environment
   */
  function isBrowser() {
      return typeof self === 'object' && self.self === self;
  }
  /**
   * Detect React Native.
   *
   * @return true if ReactNative environment is detected.
   */
  function isReactNative() {
      return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');
  }
  /**
   * Detect whether the current SDK build is the Node version.
   *
   * @return true if it's the Node SDK build.
   */
  function isNodeSdk() {
      return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  var ERROR_NAME = 'FirebaseError';
  // Based on code from:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
  var FirebaseError = /** @class */ (function (_super) {
      tslib_1.__extends(FirebaseError, _super);
      function FirebaseError(code, message) {
          var _this = _super.call(this, message) || this;
          _this.code = code;
          _this.name = ERROR_NAME;
          // Fix For ES5
          // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
          Object.setPrototypeOf(_this, FirebaseError.prototype);
          // Maintains proper stack trace for where our error was thrown.
          // Only available on V8.
          if (Error.captureStackTrace) {
              Error.captureStackTrace(_this, ErrorFactory.prototype.create);
          }
          return _this;
      }
      return FirebaseError;
  }(Error));
  var ErrorFactory = /** @class */ (function () {
      function ErrorFactory(service, serviceName, errors) {
          this.service = service;
          this.serviceName = serviceName;
          this.errors = errors;
      }
      ErrorFactory.prototype.create = function (code) {
          var data = [];
          for (var _i = 1; _i < arguments.length; _i++) {
              data[_i - 1] = arguments[_i];
          }
          var customData = data[0] || {};
          var fullCode = this.service + "/" + code;
          var template = this.errors[code];
          var message = template ? replaceTemplate(template, customData) : 'Error';
          // Service Name: Error message (service/code).
          var fullMessage = this.serviceName + ": " + message + " (" + fullCode + ").";
          var error = new FirebaseError(fullCode, fullMessage);
          // Keys with an underscore at the end of their name are not included in
          // error.data for some reason.
          // TODO: Replace with Object.entries when lib is updated to es2017.
          for (var _a = 0, _b = Object.keys(customData); _a < _b.length; _a++) {
              var key = _b[_a];
              if (key.slice(-1) !== '_') {
                  if (key in error) {
                      console.warn("Overwriting FirebaseError base field \"" + key + "\" can cause unexpected behavior.");
                  }
                  error[key] = customData[key];
              }
          }
          return error;
      };
      return ErrorFactory;
  }());
  function replaceTemplate(template, data) {
      return template.replace(PATTERN, function (_, key) {
          var value = data[key];
          return value != null ? value.toString() : "<" + key + "?>";
      });
  }
  var PATTERN = /\{\$([^}]+)}/g;
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Evaluates a JSON string into a javascript object.
   *
   * @param {string} str A string containing JSON.
   * @return {*} The javascript object representing the specified JSON.
   */
  function jsonEval(str) {
      return JSON.parse(str);
  }
  /**
   * Returns JSON representing a javascript object.
   * @param {*} data Javascript object to be stringified.
   * @return {string} The JSON contents of the object.
   */
  function stringify(data) {
      return JSON.stringify(data);
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Decodes a Firebase auth. token into constituent parts.
   *
   * Notes:
   * - May return with invalid / incomplete claims if there's no native base64 decoding support.
   * - Doesn't check if the token is actually valid.
   */
  var decode = function (token) {
      var header = {}, claims = {}, data = {}, signature = '';
      try {
          var parts = token.split('.');
          header = jsonEval(base64Decode(parts[0]) || '');
          claims = jsonEval(base64Decode(parts[1]) || '');
          signature = parts[2];
          data = claims['d'] || {};
          delete claims['d'];
      }
      catch (e) { }
      return {
          header: header,
          claims: claims,
          data: data,
          signature: signature
      };
  };
  /**
   * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the
   * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.
   *
   * Notes:
   * - May return a false negative if there's no native base64 decoding support.
   * - Doesn't check if the token is actually valid.
   */
  var isValidTimestamp = function (token) {
      var claims = decode(token).claims;
      var now = Math.floor(new Date().getTime() / 1000);
      var validSince = 0, validUntil = 0;
      if (typeof claims === 'object') {
          if (claims.hasOwnProperty('nbf')) {
              validSince = claims['nbf'];
          }
          else if (claims.hasOwnProperty('iat')) {
              validSince = claims['iat'];
          }
          if (claims.hasOwnProperty('exp')) {
              validUntil = claims['exp'];
          }
          else {
              // token will expire after 24h by default
              validUntil = validSince + 86400;
          }
      }
      return (!!now &&
          !!validSince &&
          !!validUntil &&
          now >= validSince &&
          now <= validUntil);
  };
  /**
   * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.
   *
   * Notes:
   * - May return null if there's no native base64 decoding support.
   * - Doesn't check if the token is actually valid.
   */
  var issuedAtTime = function (token) {
      var claims = decode(token).claims;
      if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {
          return claims['iat'];
      }
      return null;
  };
  /**
   * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.
   *
   * Notes:
   * - May return a false negative if there's no native base64 decoding support.
   * - Doesn't check if the token is actually valid.
   */
  var isValidFormat = function (token) {
      var decoded = decode(token), claims = decoded.claims;
      return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');
  };
  /**
   * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.
   *
   * Notes:
   * - May return a false negative if there's no native base64 decoding support.
   * - Doesn't check if the token is actually valid.
   */
  var isAdmin = function (token) {
      var claims = decode(token).claims;
      return typeof claims === 'object' && claims['admin'] === true;
  };
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  function contains(obj, key) {
      return Object.prototype.hasOwnProperty.call(obj, key);
  }
  function safeGet(obj, key) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
          return obj[key];
      }
      else {
          return undefined;
      }
  }
  function isEmpty(obj) {
      for (var key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
              return false;
          }
      }
      return true;
  }
  function map(obj, fn, contextObj) {
      var res = {};
      for (var key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
              res[key] = fn.call(contextObj, obj[key], key, obj);
          }
      }
      return res;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a
   * params object (e.g. {arg: 'val', arg2: 'val2'})
   * Note: You must prepend it with ? when adding it to a URL.
   */
  function querystring(querystringParams) {
      var params = [];
      var _loop_1 = function (key, value) {
          if (Array.isArray(value)) {
              value.forEach(function (arrayVal) {
                  params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));
              });
          }
          else {
              params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
          }
      };
      for (var _i = 0, _a = Object.entries(querystringParams); _i < _a.length; _i++) {
          var _b = _a[_i], key = _b[0], value = _b[1];
          _loop_1(key, value);
      }
      return params.length ? '&' + params.join('&') : '';
  }
  /**
   * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object
   * (e.g. {arg: 'val', arg2: 'val2'})
   */
  function querystringDecode(querystring) {
      var obj = {};
      var tokens = querystring.replace(/^\?/, '').split('&');
      tokens.forEach(function (token) {
          if (token) {
              var key = token.split('=');
              obj[key[0]] = key[1];
          }
      });
      return obj;
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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 SHA-1 cryptographic hash.
   * Variable names follow the notation in FIPS PUB 180-3:
   * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.
   *
   * Usage:
   *   var sha1 = new sha1();
   *   sha1.update(bytes);
   *   var hash = sha1.digest();
   *
   * Performance:
   *   Chrome 23:   ~400 Mbit/s
   *   Firefox 16:  ~250 Mbit/s
   *
   */
  /**
   * SHA-1 cryptographic hash constructor.
   *
   * The properties declared here are discussed in the above algorithm document.
   * @constructor
   * @final
   * @struct
   */
  var Sha1 = /** @class */ (function () {
      function Sha1() {
          /**
           * Holds the previous values of accumulated variables a-e in the compress_
           * function.
           * @private
           */
          this.chain_ = [];
          /**
           * A buffer holding the partially computed hash result.
           * @private
           */
          this.buf_ = [];
          /**
           * An array of 80 bytes, each a part of the message to be hashed.  Referred to
           * as the message schedule in the docs.
           * @private
           */
          this.W_ = [];
          /**
           * Contains data needed to pad messages less than 64 bytes.
           * @private
           */
          this.pad_ = [];
          /**
           * @private {number}
           */
          this.inbuf_ = 0;
          /**
           * @private {number}
           */
          this.total_ = 0;
          this.blockSize = 512 / 8;
          this.pad_[0] = 128;
          for (var i = 1; i < this.blockSize; ++i) {
              this.pad_[i] = 0;
          }
          this.reset();
      }
      Sha1.prototype.reset = function () {
          this.chain_[0] = 0x67452301;
          this.chain_[1] = 0xefcdab89;
          this.chain_[2] = 0x98badcfe;
          this.chain_[3] = 0x10325476;
          this.chain_[4] = 0xc3d2e1f0;
          this.inbuf_ = 0;
          this.total_ = 0;
      };
      /**
       * Internal compress helper function.
       * @param buf Block to compress.
       * @param offset Offset of the block in the buffer.
       * @private
       */
      Sha1.prototype.compress_ = function (buf, offset) {
          if (!offset) {
              offset = 0;
          }
          var W = this.W_;
          // get 16 big endian words
          if (typeof buf === 'string') {
              for (var i = 0; i < 16; i++) {
                  // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS
                  // have a bug that turns the post-increment ++ operator into pre-increment
                  // during JIT compilation.  We have code that depends heavily on SHA-1 for
                  // correctness and which is affected by this bug, so I've removed all uses
                  // of post-increment ++ in which the result value is used.  We can revert
                  // this change once the Safari bug
                  // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and
                  // most clients have been updated.
                  W[i] =
                      (buf.charCodeAt(offset) << 24) |
                          (buf.charCodeAt(offset + 1) << 16) |
                          (buf.charCodeAt(offset + 2) << 8) |
                          buf.charCodeAt(offset + 3);
                  offset += 4;
              }
          }
          else {
              for (var i = 0; i < 16; i++) {
                  W[i] =
                      (buf[offset] << 24) |
                          (buf[offset + 1] << 16) |
                          (buf[offset + 2] << 8) |
                          buf[offset + 3];
                  offset += 4;
              }
          }
          // expand to 80 words
          for (var i = 16; i < 80; i++) {
              var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
              W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;
          }
          var a = this.chain_[0];
          var b = this.chain_[1];
          var c = this.chain_[2];
          var d = this.chain_[3];
          var e = this.chain_[4];
          var f, k;
          // TODO(user): Try to unroll this loop to speed up the computation.
          for (var i = 0; i < 80; i++) {
              if (i < 40) {
                  if (i < 20) {
                      f = d ^ (b & (c ^ d));
                      k = 0x5a827999;
                  }
                  else {
                      f = b ^ c ^ d;
                      k = 0x6ed9eba1;
                  }
              }
              else {
                  if (i < 60) {
                      f = (b & c) | (d & (b | c));
                      k = 0x8f1bbcdc;
                  }
                  else {
                      f = b ^ c ^ d;
                      k = 0xca62c1d6;
                  }
              }
              var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;
              e = d;
              d = c;
              c = ((b << 30) | (b >>> 2)) & 0xffffffff;
              b = a;
              a = t;
          }
          this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;
          this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;
          this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;
          this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;
          this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;
      };
      Sha1.prototype.update = function (bytes, length) {
          // TODO(johnlenz): tighten the function signature and remove this check
          if (bytes == null) {
              return;
          }
          if (length === undefined) {
              length = bytes.length;
          }
          var lengthMinusBlock = length - this.blockSize;
          var n = 0;
          // Using local instead of member variables gives ~5% speedup on Firefox 16.
          var buf = this.buf_;
          var inbuf = this.inbuf_;
          // The outer while loop should execute at most twice.
          while (n < length) {
              // When we have no data in the block to top up, we can directly process the
              // input buffer (assuming it contains sufficient data). This gives ~25%
              // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that
              // the data is provided in large chunks (or in multiples of 64 bytes).
              if (inbuf === 0) {
                  while (n <= lengthMinusBlock) {
                      this.compress_(bytes, n);
                      n += this.blockSize;
                  }
              }
              if (typeof bytes === 'string') {
                  while (n < length) {
                      buf[inbuf] = bytes.charCodeAt(n);
                      ++inbuf;
                      ++n;
                      if (inbuf === this.blockSize) {
                          this.compress_(buf);
                          inbuf = 0;
                          // Jump to the outer loop so we use the full-block optimization.
                          break;
                      }
                  }
              }
              else {
                  while (n < length) {
                      buf[inbuf] = bytes[n];
                      ++inbuf;
                      ++n;
                      if (inbuf === this.blockSize) {
                          this.compress_(buf);
                          inbuf = 0;
                          // Jump to the outer loop so we use the full-block optimization.
                          break;
                      }
                  }
              }
          }
          this.inbuf_ = inbuf;
          this.total_ += length;
      };
      /** @override */
      Sha1.prototype.digest = function () {
          var digest = [];
          var totalBits = this.total_ * 8;
          // Add pad 0x80 0x00*.
          if (this.inbuf_ < 56) {
              this.update(this.pad_, 56 - this.inbuf_);
          }
          else {
              this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
          }
          // Add # bits.
          for (var i = this.blockSize - 1; i >= 56; i--) {
              this.buf_[i] = totalBits & 255;
              totalBits /= 256; // Don't use bit-shifting here!
          }
          this.compress_(this.buf_);
          var n = 0;
          for (var i = 0; i < 5; i++) {
              for (var j = 24; j >= 0; j -= 8) {
                  digest[n] = (this.chain_[i] >> j) & 255;
                  ++n;
              }
          }
          return digest;
      };
      return Sha1;
  }());
  
  /**
   * Helper to make a Subscribe function (just like Promise helps make a
   * Thenable).
   *
   * @param executor Function which can make calls to a single Observer
   *     as a proxy.
   * @param onNoObservers Callback when count of Observers goes to zero.
   */
  function createSubscribe(executor, onNoObservers) {
      var proxy = new ObserverProxy(executor, onNoObservers);
      return proxy.subscribe.bind(proxy);
  }
  /**
   * Implement fan-out for any number of Observers attached via a subscribe
   * function.
   */
  var ObserverProxy = /** @class */ (function () {
      /**
       * @param executor Function which can make calls to a single Observer
       *     as a proxy.
       * @param onNoObservers Callback when count of Observers goes to zero.
       */
      function ObserverProxy(executor, onNoObservers) {
          var _this = this;
          this.observers = [];
          this.unsubscribes = [];
          this.observerCount = 0;
          // Micro-task scheduling by calling task.then().
          this.task = Promise.resolve();
          this.finalized = false;
          this.onNoObservers = onNoObservers;
          // Call the executor asynchronously so subscribers that are called
          // synchronously after the creation of the subscribe function
          // can still receive the very first value generated in the executor.
          this.task
              .then(function () {
              executor(_this);
          })
              .catch(function (e) {
              _this.error(e);
          });
      }
      ObserverProxy.prototype.next = function (value) {
          this.forEachObserver(function (observer) {
              observer.next(value);
          });
      };
      ObserverProxy.prototype.error = function (error) {
          this.forEachObserver(function (observer) {
              observer.error(error);
          });
          this.close(error);
      };
      ObserverProxy.prototype.complete = function () {
          this.forEachObserver(function (observer) {
              observer.complete();
          });
          this.close();
      };
      /**
       * Subscribe function that can be used to add an Observer to the fan-out list.
       *
       * - We require that no event is sent to a subscriber sychronously to their
       *   call to subscribe().
       */
      ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) {
          var _this = this;
          var observer;
          if (nextOrObserver === undefined &&
              error === undefined &&
              complete === undefined) {
              throw new Error('Missing Observer.');
          }
          // Assemble an Observer object when passed as callback functions.
          if (implementsAnyMethods(nextOrObserver, [
              'next',
              'error',
              'complete'
          ])) {
              observer = nextOrObserver;
          }
          else {
              observer = {
                  next: nextOrObserver,
                  error: error,
                  complete: complete
              };
          }
          if (observer.next === undefined) {
              observer.next = noop;
          }
          if (observer.error === undefined) {
              observer.error = noop;
          }
          if (observer.complete === undefined) {
              observer.complete = noop;
          }
          var unsub = this.unsubscribeOne.bind(this, this.observers.length);
          // Attempt to subscribe to a terminated Observable - we
          // just respond to the Observer with the final error or complete
          // event.
          if (this.finalized) {
              // tslint:disable-next-line:no-floating-promises
              this.task.then(function () {
                  try {
                      if (_this.finalError) {
                          observer.error(_this.finalError);
                      }
                      else {
                          observer.complete();
                      }
                  }
                  catch (e) {
                      // nothing
                  }
                  return;
              });
          }
          this.observers.push(observer);
          return unsub;
      };
      // Unsubscribe is synchronous - we guarantee that no events are sent to
      // any unsubscribed Observer.
      ObserverProxy.prototype.unsubscribeOne = function (i) {
          if (this.observers === undefined || this.observers[i] === undefined) {
              return;
          }
          delete this.observers[i];
          this.observerCount -= 1;
          if (this.observerCount === 0 && this.onNoObservers !== undefined) {
              this.onNoObservers(this);
          }
      };
      ObserverProxy.prototype.forEachObserver = function (fn) {
          if (this.finalized) {
              // Already closed by previous event....just eat the additional values.
              return;
          }
          // Since sendOne calls asynchronously - there is no chance that
          // this.observers will become undefined.
          for (var i = 0; i < this.observers.length; i++) {
              this.sendOne(i, fn);
          }
      };
      // Call the Observer via one of it's callback function. We are careful to
      // confirm that the observe has not been unsubscribed since this asynchronous
      // function had been queued.
      ObserverProxy.prototype.sendOne = function (i, fn) {
          var _this = this;
          // Execute the callback asynchronously
          // tslint:disable-next-line:no-floating-promises
          this.task.then(function () {
              if (_this.observers !== undefined && _this.observers[i] !== undefined) {
                  try {
                      fn(_this.observers[i]);
                  }
                  catch (e) {
                      // Ignore exceptions raised in Observers or missing methods of an
                      // Observer.
                      // Log error to console. b/31404806
                      if (typeof console !== 'undefined' && console.error) {
                          console.error(e);
                      }
                  }
              }
          });
      };
      ObserverProxy.prototype.close = function (err) {
          var _this = this;
          if (this.finalized) {
              return;
          }
          this.finalized = true;
          if (err !== undefined) {
              this.finalError = err;
          }
          // Proxy is no longer needed - garbage collect references
          // tslint:disable-next-line:no-floating-promises
          this.task.then(function () {
              _this.observers = undefined;
              _this.onNoObservers = undefined;
          });
      };
      return ObserverProxy;
  }());
  /** Turn synchronous function into one called asynchronously. */
  function async(fn, onError) {
      return function () {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
          }
          Promise.resolve(true)
              .then(function () {
              fn.apply(void 0, args);
          })
              .catch(function (error) {
              if (onError) {
                  onError(error);
              }
          });
      };
  }
  /**
   * Return true if the object passed in implements any of the named methods.
   */
  function implementsAnyMethods(obj, methods) {
      if (typeof obj !== 'object' || obj === null) {
          return false;
      }
      for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {
          var method = methods_1[_i];
          if (method in obj && typeof obj[method] === 'function') {
              return true;
          }
      }
      return false;
  }
  function noop() {
      // do nothing
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  /**
   * Check to make sure the appropriate number of arguments are provided for a public function.
   * Throws an error if it fails.
   *
   * @param fnName The function name
   * @param minCount The minimum number of arguments to allow for the function call
   * @param maxCount The maximum number of argument to allow for the function call
   * @param argCount The actual number of arguments provided.
   */
  var validateArgCount = function (fnName, minCount, maxCount, argCount) {
      var argError;
      if (argCount < minCount) {
          argError = 'at least ' + minCount;
      }
      else if (argCount > maxCount) {
          argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;
      }
      if (argError) {
          var error = fnName +
              ' failed: Was called with ' +
              argCount +
              (argCount === 1 ? ' argument.' : ' arguments.') +
              ' Expects ' +
              argError +
              '.';
          throw new Error(error);
      }
  };
  /**
   * Generates a string to prefix an error message about failed argument validation
   *
   * @param fnName The function name
   * @param argumentNumber The index of the argument
   * @param optional Whether or not the argument is optional
   * @return The prefix to add to the error thrown for validation.
   */
  function errorPrefix(fnName, argumentNumber, optional) {
      var argName = '';
      switch (argumentNumber) {
          case 1:
              argName = optional ? 'first' : 'First';
              break;
          case 2:
              argName = optional ? 'second' : 'Second';
              break;
          case 3:
              argName = optional ? 'third' : 'Third';
              break;
          case 4:
              argName = optional ? 'fourth' : 'Fourth';
              break;
          default:
              throw new Error('errorPrefix called with argumentNumber > 4.  Need to update it?');
      }
      var error = fnName + ' failed: ';
      error += argName + ' argument ';
      return error;
  }
  /**
   * @param fnName
   * @param argumentNumber
   * @param namespace
   * @param optional
   */
  function validateNamespace(fnName, argumentNumber, namespace, optional) {
      if (optional && !namespace) {
          return;
      }
      if (typeof namespace !== 'string') {
          //TODO: I should do more validation here. We only allow certain chars in namespaces.
          throw new Error(errorPrefix(fnName, argumentNumber, optional) +
              'must be a valid firebase namespace.');
      }
  }
  function validateCallback(fnName, argumentNumber, callback, optional) {
      if (optional && !callback) {
          return;
      }
      if (typeof callback !== 'function') {
          throw new Error(errorPrefix(fnName, argumentNumber, optional) +
              'must be a valid function.');
      }
  }
  function validateContextObject(fnName, argumentNumber, context, optional) {
      if (optional && !context) {
          return;
      }
      if (typeof context !== 'object' || context === null) {
          throw new Error(errorPrefix(fnName, argumentNumber, optional) +
              'must be a valid context object.');
      }
  }
  
  /**
   * @license
   * Copyright 2017 Google Inc.
   *
   * 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.
   */
  // Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they
  // automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs,
  // so it's been modified.
  // Note that not all Unicode characters appear as single characters in JavaScript strings.
  // fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters
  // use 2 characters in Javascript.  All 4-byte UTF-8 characters begin with a first
  // character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate
  // pair).
  // See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3
  /**
   * @param {string} str
   * @return {Array}
   */
  var stringToByteArray$1 = function (str) {
      var out = [];
      var p = 0;
      for (var i = 0; i < str.length; i++) {
          var c = str.charCodeAt(i);
          // Is this the lead surrogate in a surrogate pair?
          if (c >= 0xd800 && c <= 0xdbff) {
              var high = c - 0xd800; // the high 10 bits.
              i++;
              assert(i < str.length, 'Surrogate pair missing trail surrogate.');
              var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.
              c = 0x10000 + (high << 10) + low;
          }
          if (c < 128) {
              out[p++] = c;
          }
          else if (c < 2048) {
              out[p++] = (c >> 6) | 192;
              out[p++] = (c & 63) | 128;
          }
          else if (c < 65536) {
              out[p++] = (c >> 12) | 224;
              out[p++] = ((c >> 6) & 63) | 128;
              out[p++] = (c & 63) | 128;
          }
          else {
              out[p++] = (c >> 18) | 240;
              out[p++] = ((c >> 12) & 63) | 128;
              out[p++] = ((c >> 6) & 63) | 128;
              out[p++] = (c & 63) | 128;
          }
      }
      return out;
  };
  /**
   * Calculate length without actually converting; useful for doing cheaper validation.
   * @param {string} str
   * @return {number}
   */
  var stringLength = function (str) {
      var p = 0;
      for (var i = 0; i < str.length; i++) {
          var c = str.charCodeAt(i);
          if (c < 128) {
              p++;
          }
          else if (c < 2048) {
              p += 2;
          }
          else if (c >= 0xd800 && c <= 0xdbff) {
              // Lead surrogate of a surrogate pair.  The pair together will take 4 bytes to represent.
              p += 4;
              i++; // skip trail surrogate.
          }
          else {
              p += 3;
          }
      }
      return p;
  };
  
  exports.CONSTANTS = CONSTANTS;
  exports.Deferred = Deferred;
  exports.ErrorFactory = ErrorFactory;
  exports.FirebaseError = FirebaseError;
  exports.Sha1 = Sha1;
  exports.assert = assert;
  exports.assertionError = assertionError;
  exports.async = async;
  exports.base64 = base64;
  exports.base64Decode = base64Decode;
  exports.base64Encode = base64Encode;
  exports.contains = contains;
  exports.createSubscribe = createSubscribe;
  exports.decode = decode;
  exports.deepCopy = deepCopy;
  exports.deepExtend = deepExtend;
  exports.errorPrefix = errorPrefix;
  exports.getUA = getUA;
  exports.isAdmin = isAdmin;
  exports.isBrowser = isBrowser;
  exports.isEmpty = isEmpty;
  exports.isMobileCordova = isMobileCordova;
  exports.isNode = isNode;
  exports.isNodeSdk = isNodeSdk;
  exports.isReactNative = isReactNative;
  exports.isValidFormat = isValidFormat;
  exports.isValidTimestamp = isValidTimestamp;
  exports.issuedAtTime = issuedAtTime;
  exports.jsonEval = jsonEval;
  exports.map = map;
  exports.querystring = querystring;
  exports.querystringDecode = querystringDecode;
  exports.safeGet = safeGet;
  exports.stringLength = stringLength;
  exports.stringToByteArray = stringToByteArray$1;
  exports.stringify = stringify;
  exports.validateArgCount = validateArgCount;
  exports.validateCallback = validateCallback;
  exports.validateContextObject = validateContextObject;
  exports.validateNamespace = validateNamespace;
  //# sourceMappingURL=index.cjs.js.map
  
  /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))
  
  /***/ }),
  
  /***/ "./node_modules/firebase/app/dist/index.cjs.js":
  /*!*****************************************************!*\
    !*** ./node_modules/firebase/app/dist/index.cjs.js ***!
    \*****************************************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  "use strict";
  
  
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  
  var firebase = _interopDefault(__webpack_require__(/*! @firebase/app */ "./node_modules/@firebase/app/dist/index.cjs.js"));
  
  /**
   * @license
   * Copyright 2018 Google Inc.
   *
   * 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.
   */
  
  module.exports = firebase;
  //# sourceMappingURL=index.cjs.js.map
  
  
  /***/ }),
  
  /***/ "./node_modules/firebase/storage/dist/index.esm.js":
  /*!*********************************************************!*\
    !*** ./node_modules/firebase/storage/dist/index.esm.js ***!
    \*********************************************************/
  /*! no exports provided */
  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  
  "use strict";
  __webpack_require__.r(__webpack_exports__);
  /* harmony import */ var _firebase_storage__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/storage */ "./node_modules/@firebase/storage/dist/index.esm.js");
  
  //# sourceMappingURL=index.esm.js.map
  
  
  /***/ }),
  
  /***/ "./node_modules/tslib/tslib.es6.js":
  /*!*****************************************!*\
    !*** ./node_modules/tslib/tslib.es6.js ***!
    \*****************************************/
  /*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __values, __read, __spread, __spreadArrays, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault */
  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  
  "use strict";
  __webpack_require__.r(__webpack_exports__);
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
  /*! *****************************************************************************
  Copyright (c) Microsoft Corporation. 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
  
  THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  MERCHANTABLITY OR NON-INFRINGEMENT.
  
  See the Apache Version 2.0 License for specific language governing permissions
  and limitations under the License.
  ***************************************************************************** */
  /* global Reflect, Promise */
  
  var extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf ||
          ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
          function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
      return extendStatics(d, b);
  };
  
  function __extends(d, b) {
      extendStatics(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }
  
  var __assign = function() {
      __assign = Object.assign || function __assign(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
          }
          return t;
      }
      return __assign.apply(this, arguments);
  }
  
  function __rest(s, e) {
      var t = {};
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
          t[p] = s[p];
      if (s != null && typeof Object.getOwnPropertySymbols === "function")
          for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
              if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                  t[p[i]] = s[p[i]];
          }
      return t;
  }
  
  function __decorate(decorators, target, key, desc) {
      var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
      if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
      else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
      return c > 3 && r && Object.defineProperty(target, key, r), r;
  }
  
  function __param(paramIndex, decorator) {
      return function (target, key) { decorator(target, key, paramIndex); }
  }
  
  function __metadata(metadataKey, metadataValue) {
      if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
  }
  
  function __awaiter(thisArg, _arguments, P, generator) {
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  }
  
  function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
      function verb(n) { return function (v) { return step([n, v]); }; }
      function step(op) {
          if (f) throw new TypeError("Generator is already executing.");
          while (_) try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [op[0] & 2, t.value];
              switch (op[0]) {
                  case 0: case 1: t = op; break;
                  case 4: _.label++; return { value: op[1], done: false };
                  case 5: _.label++; y = op[1]; op = [0]; continue;
                  case 7: op = _.ops.pop(); _.trys.pop(); continue;
                  default:
                      if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                      if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                      if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                      if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                      if (t[2]) _.ops.pop();
                      _.trys.pop(); continue;
              }
              op = body.call(thisArg, _);
          } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
          if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
      }
  }
  
  function __exportStar(m, exports) {
      for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  }
  
  function __values(o) {
      var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
      if (m) return m.call(o);
      return {
          next: function () {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
          }
      };
  }
  
  function __read(o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m) return o;
      var i = m.call(o), r, ar = [], e;
      try {
          while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
      }
      catch (error) { e = { error: error }; }
      finally {
          try {
              if (r && !r.done && (m = i["return"])) m.call(i);
          }
          finally { if (e) throw e.error; }
      }
      return ar;
  }
  
  function __spread() {
      for (var ar = [], i = 0; i < arguments.length; i++)
          ar = ar.concat(__read(arguments[i]));
      return ar;
  }
  
  function __spreadArrays() {
      for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
      for (var r = Array(s), k = 0, i = 0; i < il; i++)
          for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
              r[k] = a[j];
      return r;
  };
  
  function __await(v) {
      return this instanceof __await ? (this.v = v, this) : new __await(v);
  }
  
  function __asyncGenerator(thisArg, _arguments, generator) {
      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
      var g = generator.apply(thisArg, _arguments || []), i, q = [];
      return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
      function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
      function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
      function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
      function fulfill(value) { resume("next", value); }
      function reject(value) { resume("throw", value); }
      function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
  }
  
  function __asyncDelegator(o) {
      var i, p;
      return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
      function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
  }
  
  function __asyncValues(o) {
      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
      var m = o[Symbol.asyncIterator], i;
      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
      function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
      function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  }
  
  function __makeTemplateObject(cooked, raw) {
      if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
      return cooked;
  };
  
  function __importStar(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
      result.default = mod;
      return result;
  }
  
  function __importDefault(mod) {
      return (mod && mod.__esModule) ? mod : { default: mod };
  }
  
  
  /***/ }),
  
  /***/ "./node_modules/webpack/buildin/global.js":
  /*!***********************************!*\
    !*** (webpack)/buildin/global.js ***!
    \***********************************/
  /*! no static exports found */
  /***/ (function(module, exports) {
  
  var g;
  
  // This works in non-strict mode
  g = (function() {
  	return this;
  })();
  
  try {
  	// This works if eval is allowed (see CSP)
  	g = g || new Function("return this")();
  } catch (e) {
  	// This works if the window reference is available
  	if (typeof window === "object") g = window;
  }
  
  // g can still be undefined, but nothing to do about it...
  // We return undefined, instead of nothing here, so it's
  // easier to handle this case. if(!global) { ...}
  
  module.exports = g;
  
  
  /***/ }),
  
  /***/ "./resources/js/desktop/_dashboard.js":
  /*!********************************************!*\
    !*** ./resources/js/desktop/_dashboard.js ***!
    \********************************************/
  /*! no exports provided */
  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  
  "use strict";
  __webpack_require__.r(__webpack_exports__);
  /* harmony import */ var firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! firebase/app */ "./node_modules/firebase/app/dist/index.cjs.js");
  /* harmony import */ var firebase_app__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(firebase_app__WEBPACK_IMPORTED_MODULE_0__);
  /* harmony import */ var firebase_storage__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! firebase/storage */ "./node_modules/firebase/storage/dist/index.esm.js");
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  
  
  
  if (!firebase_app__WEBPACK_IMPORTED_MODULE_0___default.a.apps.length) {
    firebase_app__WEBPACK_IMPORTED_MODULE_0___default.a.initializeApp({
      apiKey: "AIzaSyC8YUBMf4wZbue3Hy8K1oFAdq67x2JyGDs",
      authDomain: "first-app-e4b1c.firebaseapp.com",
      databaseURL: "https://first-app-e4b1c.firebaseio.com",
      projectId: "first-app-e4b1c",
      storageBucket: "first-app-e4b1c.appspot.com",
      messagingSenderId: "1090500936315",
      appId: "1:1090500936315:web:80b0f6c8ba7f29b61318de"
    });
  }
  
  var Dashboard = function Dashboard() {
    _classCallCheck(this, Dashboard);
  
    // var uploader = document.getElementById('uploader');
    // var fileButton = document.getElementById('fileButton');
    // fileButton.addEventListener('change', function(e){
    //     var file = e.target.files[0];
    //     var storageRef = firebase.storage().ref('images/img_' + file.name);
    //     var task = storageRef.put(file);
    //     task.on('state_changed',
    //         function progress(snapshot){
    //             var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    //             uploader.value = percentage;
    //         },
    //         function error(err){
    //         },
    //         function complete(){
    //             task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    //                 console.log('Fuck u bitch at=>', downloadURL);
    //               });
    //         }
    //     );
    // });
    $('#img-upload-temp').on('change', function () {
      var formData = new FormData();
      formData.append('file', $(this)[0].files[0]); // let _file = e.target.files[0];
  
      console.log($(this)[0].files[0]);
      $.ajax({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: '/upload-image',
        type: 'POST',
        dataType: 'json',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function success(data) {
          // if ( data.success == true) {
          //     $('#Path').val(data.url);
          //     $('._filename').val(data.filename);
          $('.resp_img').html('<div class="thumbnail" style="width: 100px; height: 65px"><img src="' + data.url + '" class="portrait"/></div>'); // }
          // else {
          //     alertify.error(data.message);
          // }
        }
      });
    });
  };
  
  var dashboard = new Dashboard();
  
  /***/ }),
  
  /***/ 4:
  /*!**************************************************!*\
    !*** multi ./resources/js/desktop/_dashboard.js ***!
    \**************************************************/
  /*! no static exports found */
  /***/ (function(module, exports, __webpack_require__) {
  
  module.exports = __webpack_require__(/*! F:\xampp\htdocs\first-app\resources\js\desktop\_dashboard.js */"./resources/js/desktop/_dashboard.js");
  
  
  /***/ })
  
  /******/ });