{"version":3,"file":"index.mjs","names":[],"sources":["../src/messageSW.ts","../src/utils/SerwistEvent.ts","../src/utils/SerwistEventTarget.ts","../src/utils/urlsMatch.ts","../src/Serwist.ts"],"sourcesContent":["/*\n  Copyright 2019 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\n\n/**\n * Sends a data object to a service worker via `postMessage` and resolves with\n * a response (if any).\n *\n * A response can be sent by calling `event.ports[0].postMessage(...)`, which will\n * resolve the promise returned by `messageSW()`. If no response is sent, the promise\n * will never resolve.\n *\n * @param sw The service worker to send the message to.\n * @param data An object to send to the service worker.\n * @returns\n */\nexport const messageSW = (sw: ServiceWorker, data: any): Promise<any> => {\n  return new Promise((resolve) => {\n    const messageChannel = new MessageChannel();\n    messageChannel.port1.onmessage = (event: MessageEvent) => {\n      resolve(event.data);\n    };\n    sw.postMessage(data, [messageChannel.port2]);\n  });\n};\n","/*\n  Copyright 2019 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\n\nimport type { SerwistEventTarget } from \"./SerwistEventTarget.js\";\n\n/**\n * A minimal `Event` subclass shim.\n * This doesn't *actually* subclass `Event` because not all browsers support\n * constructable `EventTarget`, and using a real `Event` will error.\n * @private\n */\nexport class SerwistEvent<K extends keyof SerwistEventMap> {\n  target?: SerwistEventTarget;\n  sw?: ServiceWorker;\n  originalEvent?: Event;\n  isExternal?: boolean;\n\n  constructor(\n    public type: K,\n    props: Omit<SerwistEventMap[K], \"target\" | \"type\">,\n  ) {\n    Object.assign(this, props);\n  }\n}\n\nexport interface SerwistMessageEvent extends SerwistEvent<\"message\"> {\n  data: any;\n  originalEvent: Event;\n  ports: readonly MessagePort[];\n}\n\nexport interface SerwistLifecycleEvent extends SerwistEvent<keyof SerwistLifecycleEventMap> {\n  isUpdate?: boolean;\n}\n\nexport interface SerwistLifecycleWaitingEvent extends SerwistLifecycleEvent {\n  wasWaitingBeforeRegister?: boolean;\n}\n\nexport interface SerwistLifecycleEventMap {\n  installing: SerwistLifecycleEvent;\n  installed: SerwistLifecycleEvent;\n  waiting: SerwistLifecycleWaitingEvent;\n  activating: SerwistLifecycleEvent;\n  activated: SerwistLifecycleEvent;\n  controlling: SerwistLifecycleEvent;\n  redundant: SerwistLifecycleEvent;\n}\n\nexport interface SerwistEventMap extends SerwistLifecycleEventMap {\n  message: SerwistMessageEvent;\n}\n","/*\n  Copyright 2019 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\n\nimport type { SerwistEvent, SerwistEventMap } from \"./SerwistEvent.js\";\n\nexport type ListenerCallback = (event: SerwistEvent<any>) => any;\n\n/**\n * A minimal `EventTarget` shim.\n * This is necessary because not all browsers support constructable\n * `EventTarget`, so using a real `EventTarget` will error.\n * @private\n */\nexport class SerwistEventTarget {\n  private readonly _eventListenerRegistry: Map<keyof SerwistEventMap, Set<ListenerCallback>> = new Map();\n\n  /**\n   * @param type\n   * @param listener\n   * @private\n   */\n  addEventListener<K extends keyof SerwistEventMap>(type: K, listener: (event: SerwistEventMap[K]) => any): void {\n    const foo = this._getEventListenersByType(type);\n    foo.add(listener as ListenerCallback);\n  }\n\n  /**\n   * @param type\n   * @param listener\n   * @private\n   */\n  removeEventListener<K extends keyof SerwistEventMap>(type: K, listener: (event: SerwistEventMap[K]) => any): void {\n    this._getEventListenersByType(type).delete(listener as ListenerCallback);\n  }\n\n  /**\n   * @param event\n   * @private\n   */\n  dispatchEvent(event: SerwistEvent<any>): void {\n    event.target = this;\n\n    const listeners = this._getEventListenersByType(event.type);\n    for (const listener of listeners) {\n      listener(event);\n    }\n  }\n\n  /**\n   * Returns a Set of listeners associated with the passed event type.\n   * If no handlers have been registered, an empty Set is returned.\n   *\n   * @param type The event type.\n   * @returns An array of handler functions.\n   * @private\n   */\n  private _getEventListenersByType(type: keyof SerwistEventMap) {\n    if (!this._eventListenerRegistry.has(type)) {\n      this._eventListenerRegistry.set(type, new Set());\n    }\n    return this._eventListenerRegistry.get(type)!;\n  }\n}\n","/*\n  Copyright 2019 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\n\n/**\n * Returns true if two URLs have the same `.href` property. The URLs can be\n * relative, and if they are the current location href is used to resolve URLs.\n *\n * @private\n * @param url1\n * @param url2\n * @returns\n */\nexport function urlsMatch(url1: string, url2: string): boolean {\n  const { href } = location;\n  return new URL(url1, href).href === new URL(url2, href).href;\n}\n","/*\n  Copyright 2019 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\n\nimport { Deferred, logger } from \"serwist/internal\";\n\nimport { messageSW } from \"./messageSW.js\";\nimport { isCurrentPageOutOfScope } from \"./utils/isCurrentPageOutOfScope.js\";\nimport type { SerwistLifecycleEventMap } from \"./utils/SerwistEvent.js\";\nimport { SerwistEvent } from \"./utils/SerwistEvent.js\";\nimport { SerwistEventTarget } from \"./utils/SerwistEventTarget.js\";\nimport { urlsMatch } from \"./utils/urlsMatch.js\";\n\n// The time a SW must be in the waiting phase before we can conclude\n// `skipWaiting()` wasn't called. This 200 amount wasn't scientifically\n// chosen, but it seems to avoid false positives in my testing.\nconst WAITING_TIMEOUT_DURATION = 200;\n\n// The amount of time after a registration that we can reasonably conclude\n// that the registration didn't trigger an update.\nconst REGISTRATION_TIMEOUT_DURATION = 60000;\n\n// The de facto standard message that a service worker should be listening for\n// to trigger a call to skipWaiting().\nconst SKIP_WAITING_MESSAGE = { type: \"SKIP_WAITING\" } as const;\n\n/**\n * A class to aid in handling service worker registration, updates, and\n * reacting to service worker lifecycle events.\n *\n * @fires `@serwist/window.Serwist.message`\n * @fires `@serwist/window.Serwist.installed`\n * @fires `@serwist/window.Serwist.waiting`\n * @fires `@serwist/window.Serwist.controlling`\n * @fires `@serwist/window.Serwist.activated`\n * @fires `@serwist/window.Serwist.redundant`\n */\nexport class Serwist extends SerwistEventTarget {\n  private readonly _scriptURL: string | TrustedScriptURL;\n  private readonly _registerOptions: RegistrationOptions = {};\n  private _updateFoundCount = 0;\n\n  // Deferreds we can resolve later.\n  private readonly _swDeferred: Deferred<ServiceWorker> = new Deferred();\n  private readonly _activeDeferred: Deferred<ServiceWorker> = new Deferred();\n  private readonly _controllingDeferred: Deferred<ServiceWorker> = new Deferred();\n\n  private _registrationTime: DOMHighResTimeStamp = 0;\n  private _isUpdate?: boolean;\n  private _compatibleControllingSW?: ServiceWorker;\n  private _registration?: ServiceWorkerRegistration;\n  private _sw?: ServiceWorker;\n  private readonly _ownSWs: Set<ServiceWorker> = new Set();\n  private _externalSW?: ServiceWorker;\n  private _waitingTimeout?: number;\n\n  /**\n   * Creates a new Serwist instance with a script URL and service worker\n   * options. The script URL and options are the same as those used when\n   * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).\n   *\n   * @param scriptURL The service worker script associated with this instance. Using a\n   * [`TrustedScriptURL`](https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL) is supported.\n   * @param registerOptions The service worker options associated with this instance.\n   */\n  constructor(scriptURL: string | TrustedScriptURL, registerOptions: RegistrationOptions = {}) {\n    super();\n\n    this._scriptURL = scriptURL;\n    this._registerOptions = registerOptions;\n\n    // Add a message listener immediately since messages received during\n    // page load are buffered only until the DOMContentLoaded event:\n    // https://github.com/GoogleChrome/workbox/issues/2202\n    navigator.serviceWorker.addEventListener(\"message\", this._onMessage);\n  }\n\n  /**\n   * Registers a service worker for this instances script URL and service\n   * worker options. By default this method delays registration until after\n   * the window has loaded.\n   *\n   * @param options\n   */\n  async register({\n    immediate = false,\n  }: {\n    /**\n     * Setting this to true will register the service worker immediately,\n     * even if the window has not loaded (not recommended).\n     */\n    immediate?: boolean;\n  } = {}): Promise<ServiceWorkerRegistration | undefined> {\n    if (process.env.NODE_ENV !== \"production\") {\n      if (this._registrationTime) {\n        logger.error(\"Cannot re-register a Serwist instance after it has been registered. Create a new instance instead.\");\n        return;\n      }\n    }\n\n    if (!immediate && document.readyState !== \"complete\") {\n      await new Promise((res) => window.addEventListener(\"load\", res));\n    }\n\n    // Set this flag to true if any service worker was controlling the page\n    // at registration time.\n    this._isUpdate = Boolean(navigator.serviceWorker.controller);\n\n    // Before registering, attempt to determine if a SW is already controlling\n    // the page and if that SW script (and version, if specified) matches this\n    // instance's script.\n    this._compatibleControllingSW = this._getControllingSWIfCompatible();\n\n    this._registration = await this._registerScript();\n\n    // If we have a compatible controller, store the controller as the \"own\"\n    // SW, resolve active/controlling deferreds and add necessary listeners.\n    if (this._compatibleControllingSW) {\n      this._sw = this._compatibleControllingSW;\n      this._activeDeferred.resolve(this._compatibleControllingSW);\n      this._controllingDeferred.resolve(this._compatibleControllingSW);\n\n      this._compatibleControllingSW.addEventListener(\"statechange\", this._onStateChange, { once: true });\n    }\n\n    // If there's a waiting service worker with a matching URL before the\n    // `updatefound` event fires, it likely means that this site is open\n    // in another tab, or the user refreshed the page (and thus the previous\n    // page wasn't fully unloaded before this page started loading).\n    // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting\n    const waitingSW = this._registration.waiting;\n    if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {\n      // Store the waiting SW as the \"own\" SW, even if it means overwriting\n      // a compatible controller.\n      this._sw = waitingSW;\n\n      // Run this in the next microtask, so any code that adds an event\n      // listener after awaiting `register()` will get this event.\n      void Promise.resolve().then(() => {\n        this.dispatchEvent(\n          new SerwistEvent(\"waiting\", {\n            sw: waitingSW,\n            wasWaitingBeforeRegister: true,\n          }),\n        );\n        if (process.env.NODE_ENV !== \"production\") {\n          logger.warn(\"A service worker was already waiting to activate before this script was registered...\");\n        }\n      });\n    }\n\n    // If an \"own\" SW is already set, resolve the deferred.\n    if (this._sw) {\n      this._swDeferred.resolve(this._sw);\n      this._ownSWs.add(this._sw);\n    }\n\n    if (process.env.NODE_ENV !== \"production\") {\n      logger.log(\"Successfully registered service worker.\", this._scriptURL.toString());\n\n      if (navigator.serviceWorker.controller) {\n        if (this._compatibleControllingSW) {\n          logger.debug(\"A service worker with the same script URL is already controlling this page.\");\n        } else {\n          logger.debug(\n            \"A service worker with a different script URL is currently controlling the page. The browser is now fetching the new script now...\",\n          );\n        }\n      }\n\n      if (isCurrentPageOutOfScope(this._registerOptions.scope || this._scriptURL.toString())) {\n        logger.warn(\"The current page is not in scope for the registered service worker. Was this a mistake?\");\n      }\n    }\n\n    this._registration.addEventListener(\"updatefound\", this._onUpdateFound);\n    navigator.serviceWorker.addEventListener(\"controllerchange\", this._onControllerChange);\n\n    return this._registration;\n  }\n\n  /**\n   * Checks for updates of the registered service worker.\n   */\n  async update(): Promise<void> {\n    if (!this._registration) {\n      if (process.env.NODE_ENV !== \"production\") {\n        logger.error(\"Cannot update a Serwist instance without being registered. Register the Serwist instance first.\");\n      }\n      return;\n    }\n\n    // Try to update registration\n    await this._registration.update();\n  }\n\n  /**\n   * Resolves to the service worker registered by this instance as soon as it\n   * is active. If a service worker was already controlling at registration\n   * time then it will resolve to that if the script URLs (and optionally\n   * script versions) match, otherwise it will wait until an update is found\n   * and activates.\n   *\n   * @returns\n   */\n  get active(): Promise<ServiceWorker> {\n    return this._activeDeferred.promise;\n  }\n\n  /**\n   * Resolves to the service worker registered by this instance as soon as it\n   * is controlling the page. If a service worker was already controlling at\n   * registration time then it will resolve to that if the script URLs (and\n   * optionally script versions) match, otherwise it will wait until an update\n   * is found and starts controlling the page.\n   * Note: the first time a service worker is installed it will active but\n   * not start controlling the page unless `clients.claim()` is called in the\n   * service worker.\n   *\n   * @returns\n   */\n  get controlling(): Promise<ServiceWorker> {\n    return this._controllingDeferred.promise;\n  }\n\n  /**\n   * Resolves with a reference to a service worker that matches the script URL\n   * of this instance, as soon as it's available.\n   *\n   * If, at registration time, there's already an active or waiting service\n   * worker with a matching script URL, it will be used (with the waiting\n   * service worker taking precedence over the active service worker if both\n   * match, since the waiting service worker would have been registered more\n   * recently).\n   * If there's no matching active or waiting service worker at registration\n   * time then the promise will not resolve until an update is found and starts\n   * installing, at which point the installing service worker is used.\n   *\n   * @returns\n   */\n  getSW(): Promise<ServiceWorker> {\n    // If `this._sw` is set, resolve with that as we want `getSW()` to\n    // return the correct (new) service worker if an update is found.\n    return this._sw !== undefined ? Promise.resolve(this._sw) : this._swDeferred.promise;\n  }\n\n  /**\n   * Sends the passed data object to the service worker registered by this\n   * instance (via `getSW`) and resolves with a response (if any).\n   *\n   * A response can be sent by calling `event.ports[0].postMessage(...)`, which will\n   * resolve the promise returned by `messageSW()`. If no response is sent, the promise\n   * will never resolve.\n   *\n   * @param data An object to send to the service worker\n   * @returns\n   */\n  // We might be able to change the 'data' type to Record<string, unknown> in the future.\n  async messageSW(data: any): Promise<any> {\n    const sw = await this.getSW();\n    return messageSW(sw, data);\n  }\n\n  /**\n   * Sends a `{ type: \"SKIP_WAITING\" }` message to the service worker that is\n   * currently waiting and associated with the current registration.\n   *\n   * If there is no current registration, or no service worker is waiting,\n   * calling this will have no effect.\n   */\n  messageSkipWaiting(): void {\n    if (this._registration?.waiting) {\n      void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);\n    }\n  }\n\n  /**\n   * Checks for a service worker already controlling the page and returns\n   * it if its script URL matches.\n   *\n   * @private\n   * @returns\n   */\n  private _getControllingSWIfCompatible() {\n    const controller = navigator.serviceWorker.controller;\n    if (controller && urlsMatch(controller.scriptURL, this._scriptURL.toString())) {\n      return controller;\n    }\n    return undefined;\n  }\n\n  /**\n   * Registers a service worker for this instances script URL and register\n   * options and tracks the time registration was complete.\n   *\n   * @private\n   */\n  private async _registerScript() {\n    try {\n      // this._scriptURL may be a TrustedScriptURL, but there's no support for\n      // passing that to register() in lib.dom right now.\n      // https://github.com/GoogleChrome/workbox/issues/2855\n      const reg = await navigator.serviceWorker.register(this._scriptURL as string, this._registerOptions);\n\n      // Keep track of when registration happened, so it can be used in the\n      // `this._onUpdateFound` heuristic. Also use the presence of this\n      // property as a way to see if `.register()` has been called.\n      this._registrationTime = performance.now();\n\n      return reg;\n    } catch (error) {\n      if (process.env.NODE_ENV !== \"production\") {\n        logger.error(error);\n      }\n      // Re-throw the error.\n      throw error;\n    }\n  }\n\n  /**\n   * @private\n   * @param originalEvent\n   */\n  private readonly _onUpdateFound = (originalEvent: Event) => {\n    // `this._registration` will never be `undefined` after an update is found.\n    const registration = this._registration!;\n    const installingSW = registration.installing as ServiceWorker;\n\n    // If the script URL passed to `navigator.serviceWorker.register()` is\n    // different from the current controlling SW's script URL, we know any\n    // successful registration calls will trigger an `updatefound` event.\n    // But if the registered script URL is the same as the current controlling\n    // SW's script URL, we'll only get an `updatefound` event if the file\n    // changed since it was last registered. This can be a problem if the user\n    // opens up the same page in a different tab, and that page registers\n    // a SW that triggers an update. It's a problem because this page has no\n    // good way of knowing whether the `updatefound` event came from the SW\n    // script it registered or from a registration attempt made by a newer\n    // version of the page running in another tab.\n    // To minimize the possibility of a false positive, we use the logic here:\n    const updateLikelyTriggeredExternally =\n      // Since we enforce only calling `register()` once, and since we don't\n      // add the `updatefound` event listener until the `register()` call, if\n      // `_updateFoundCount` is > 0 then it means this method has already\n      // been called, thus this SW must be external\n      this._updateFoundCount > 0 ||\n      // If the script URL of the installing SW is different from this\n      // instance's script URL, we know it's definitely not from our\n      // registration.\n      !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||\n      // If all of the above are false, then we use a time-based heuristic:\n      // Any `updatefound` event that occurs long after our registration is\n      // assumed to be external.\n      performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION;\n    // If any of the above are not true, we assume the update was\n    // triggered by this instance.\n\n    if (updateLikelyTriggeredExternally) {\n      this._externalSW = installingSW;\n      registration.removeEventListener(\"updatefound\", this._onUpdateFound);\n    } else {\n      // If the update was not triggered externally we know the installing\n      // SW is the one we registered, so we set it.\n      this._sw = installingSW;\n      this._ownSWs.add(installingSW);\n      this._swDeferred.resolve(installingSW);\n\n      if (process.env.NODE_ENV !== \"production\") {\n        if (this._isUpdate) {\n          logger.log(\"Updated service worker found. Installing now...\");\n        } else {\n          logger.log(\"Service worker is installing...\");\n        }\n      }\n    }\n\n    // Dispatch the `installing` event when the SW is installing.\n    this.dispatchEvent(\n      new SerwistEvent(\"installing\", {\n        sw: installingSW,\n        originalEvent,\n        isExternal: updateLikelyTriggeredExternally,\n        isUpdate: this._isUpdate,\n      }),\n    );\n\n    // Increment the `updatefound` count, so future invocations of this\n    // method can be sure they were triggered externally.\n    ++this._updateFoundCount;\n\n    // Add a `statechange` listener regardless of whether this update was\n    // triggered externally, since we have callbacks for both.\n    installingSW.addEventListener(\"statechange\", this._onStateChange);\n  };\n\n  /**\n   * @private\n   * @param originalEvent\n   */\n  private readonly _onStateChange = (originalEvent: Event) => {\n    // `this._registration` will never be `undefined` after an update is found.\n    const registration = this._registration!;\n    const sw = originalEvent.target as ServiceWorker;\n    const { state } = sw;\n    const isExternal = sw === this._externalSW;\n\n    const eventProps: {\n      sw: ServiceWorker;\n      originalEvent: Event;\n      isUpdate?: boolean;\n      isExternal: boolean;\n    } = {\n      sw,\n      isExternal,\n      originalEvent,\n    };\n    if (!isExternal && this._isUpdate) {\n      eventProps.isUpdate = true;\n    }\n\n    this.dispatchEvent(new SerwistEvent(state as keyof SerwistLifecycleEventMap, eventProps));\n\n    if (state === \"installed\") {\n      // This timeout is used to ignore cases where the service worker calls\n      // `skipWaiting()` in the install event, thus moving it directly in the\n      // activating state. (Since all service workers *must* go through the\n      // waiting phase, the only way to detect `skipWaiting()` called in the\n      // install event is to observe that the time spent in the waiting phase\n      // is very short.)\n      // NOTE: we don't need separate timeouts for the own and external SWs\n      // since they can't go through these phases at the same time.\n      this._waitingTimeout = self.setTimeout(() => {\n        // Ensure the SW is still waiting (it may now be redundant).\n        if (state === \"installed\" && registration.waiting === sw) {\n          this.dispatchEvent(new SerwistEvent(\"waiting\", eventProps));\n\n          if (process.env.NODE_ENV !== \"production\") {\n            if (isExternal) {\n              logger.warn(\"An external service worker has installed but is \" + \"waiting for this client to close before activating...\");\n            } else {\n              logger.warn(\"The service worker has installed but is waiting \" + \"for existing clients to close before activating...\");\n            }\n          }\n        }\n      }, WAITING_TIMEOUT_DURATION);\n    } else if (state === \"activating\") {\n      clearTimeout(this._waitingTimeout);\n      if (!isExternal) {\n        this._activeDeferred.resolve(sw);\n      }\n    }\n\n    if (process.env.NODE_ENV !== \"production\") {\n      switch (state) {\n        case \"installed\":\n          if (isExternal) {\n            logger.warn(\"An external service worker has installed. \" + \"You may want to suggest users reload this page.\");\n          } else {\n            logger.log(\"Registered service worker installed.\");\n          }\n          break;\n        case \"activated\":\n          if (isExternal) {\n            logger.warn(\"An external service worker has activated.\");\n          } else {\n            logger.log(\"Registered service worker activated.\");\n            if (sw !== navigator.serviceWorker.controller) {\n              logger.warn(\n                \"The registered service worker is active but \" +\n                  \"not yet controlling the page. Reload or run \" +\n                  \"`clients.claim()` in the service worker.\",\n              );\n            }\n          }\n          break;\n        case \"redundant\":\n          if (sw === this._compatibleControllingSW) {\n            logger.log(\"Previously controlling service worker now redundant!\");\n          } else if (!isExternal) {\n            logger.log(\"Registered service worker now redundant!\");\n          }\n          break;\n      }\n    }\n  };\n\n  /**\n   * @private\n   * @param originalEvent\n   */\n  private readonly _onControllerChange = (originalEvent: Event) => {\n    const sw = this._sw;\n    const isExternal = sw !== navigator.serviceWorker.controller;\n\n    // Unconditionally dispatch the controlling event, with isExternal set\n    // to distinguish between controller changes due to the initial registration\n    // vs. an update-check or other tab's registration.\n    // See https://github.com/GoogleChrome/workbox/issues/2786\n    this.dispatchEvent(\n      new SerwistEvent(\"controlling\", {\n        isExternal,\n        originalEvent,\n        sw,\n        isUpdate: this._isUpdate,\n      }),\n    );\n\n    if (!isExternal) {\n      if (process.env.NODE_ENV !== \"production\") {\n        logger.log(\"Registered service worker now controlling this page.\");\n      }\n      this._controllingDeferred.resolve(sw);\n    }\n  };\n\n  /**\n   * @private\n   * @param originalEvent\n   */\n  private readonly _onMessage = async (originalEvent: MessageEvent) => {\n    const { data, ports, source } = originalEvent;\n\n    // Wait until there's an \"own\" service worker. This is used to buffer\n    // `message` events that may be received prior to calling `register()`.\n    await this.getSW();\n\n    // If the service worker that sent the message is in the list of own\n    // service workers for this instance, dispatch a `message` event.\n    // NOTE: we check for all previously owned service workers rather than\n    // just the current one because some messages (e.g. cache updates) use\n    // a timeout when sent and may be delayed long enough for a service worker\n    // update to be found.\n    if (this._ownSWs.has(source as ServiceWorker)) {\n      this.dispatchEvent(\n        new SerwistEvent(\"message\", {\n          data,\n          originalEvent,\n          ports,\n          sw: source as ServiceWorker,\n        }),\n      );\n    }\n  };\n}\n\n// The jsdoc comments below outline the events this instance may dispatch:\n// -----------------------------------------------------------------------\n\n/**\n * The `message` event is dispatched any time a `postMessage` is received.\n *\n * @event workbox-window.Workbox#message\n * @type {SerwistEvent}\n * @property {*} data The `data` property from the original `message` event.\n * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}\n *     event.\n * @property {string} type `message`.\n * @property {MessagePort[]} ports The `ports` value from `originalEvent`.\n * @property {Workbox} target The `Workbox` instance.\n */\n\n/**\n * The `installed` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `installed`.\n *\n * Then can happen either the very first time a service worker is installed,\n * or after an update to the current service worker is found. In the case\n * of an update being found, the event's `isUpdate` property will be `true`.\n *\n * @event workbox-window.Workbox#installed\n * @type {SerwistEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n *     event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n *     controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n *     with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `installed`.\n * @property {Workbox} target The `Workbox` instance.\n */\n\n/**\n * The `waiting` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `installed` and then doesn't immediately change to `activating`.\n * It may also be dispatched if a service worker with the same\n * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * was already waiting when the {@link workbox-window.Workbox#register}\n * method was called.\n *\n * @event workbox-window.Workbox#waiting\n * @type {SerwistEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event|undefined} originalEvent The original\n *    [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n *     event, or `undefined` in the case where the service worker was waiting\n *     to before `.register()` was called.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n *     controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n *     with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with\n *     a matching `scriptURL` was already waiting when this `Workbox`\n *     instance called `register()`.\n * @property {string} type `waiting`.\n * @property {Workbox} target The `Workbox` instance.\n */\n\n/**\n * The `controlling` event is dispatched if a\n * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}\n * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}\n * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}\n * matches the `scriptURL` of the `Workbox` instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.\n *\n * @event workbox-window.Workbox#controlling\n * @type {SerwistEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}\n *     event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n *     controlling when this service worker was registered.\n * @property {boolean|undefined} isExternal True if this event is associated\n *     with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `controlling`.\n * @property {Workbox} target The `Workbox` instance.\n */\n\n/**\n * The `activated` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}\n * changes to `activated`.\n *\n * @event workbox-window.Workbox#activated\n * @type {SerwistEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n *     event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n *     controlling when this `Workbox` instance called `register()`.\n * @property {boolean|undefined} isExternal True if this event is associated\n *     with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.\n * @property {string} type `activated`.\n * @property {Workbox} target The `Workbox` instance.\n */\n\n/**\n * The `redundant` event is dispatched if the state of a\n * {@link workbox-window.Workbox} instance's\n * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}\n * changes to `redundant`.\n *\n * @event workbox-window.Workbox#redundant\n * @type {SerwistEvent}\n * @property {ServiceWorker} sw The service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n *     event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n *     controlling when this `Workbox` instance called `register()`.\n * @property {string} type `redundant`.\n * @property {Workbox} target The `Workbox` instance.\n */\n\n/**\n * The `installing` event is dispatched if the service worker\n * finds the new version and starts installing.\n *\n * @event workbox-window.Workbox#installing\n * @type {SerwistEvent}\n * @property {ServiceWorker} sw The installing service worker instance.\n * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}\n *     event.\n * @property {boolean|undefined} isUpdate True if a service worker was already\n *     controlling when this `Workbox` instance called `register()`.\n * @property {string} type `installing`.\n * @property {Workbox} target The `Workbox` instance.\n */\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,aAAa,IAAmB,SAA4B;AACvE,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,iBAAiB,IAAI,gBAAgB;AAC3C,iBAAe,MAAM,aAAa,UAAwB;AACxD,WAAQ,MAAM,KAAK;;AAErB,KAAG,YAAY,MAAM,CAAC,eAAe,MAAM,CAAC;GAC5C;;;;;;;;;;ACXJ,IAAa,eAAb,MAA2D;CACzD;CACA;CACA;CACA;CAEA,YACE,MACA,OACA;AAFO,OAAA,OAAA;AAGP,SAAO,OAAO,MAAM,MAAM;;;;;;;;;;;ACR9B,IAAa,qBAAb,MAAgC;CAC9B,yCAA6F,IAAI,KAAK;;;;;;CAOtG,iBAAkD,MAAS,UAAoD;AACjG,OAAK,yBAAyB,KACvC,CAAC,IAAI,SAA6B;;;;;;;CAQvC,oBAAqD,MAAS,UAAoD;AAChH,OAAK,yBAAyB,KAAK,CAAC,OAAO,SAA6B;;;;;;CAO1E,cAAc,OAAgC;AAC5C,QAAM,SAAS;EAEf,MAAM,YAAY,KAAK,yBAAyB,MAAM,KAAK;AAC3D,OAAK,MAAM,YAAY,UACrB,UAAS,MAAM;;;;;;;;;;CAYnB,yBAAiC,MAA6B;AAC5D,MAAI,CAAC,KAAK,uBAAuB,IAAI,KAAK,CACxC,M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