jekyll-pwa-workbox 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. checksums.yaml +4 -4
  2. data/lib/jekyll-pwa-workbox.rb +1 -1
  3. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-background-sync.dev.js +818 -818
  4. data/lib/vendor/workbox-v5.1.1/workbox-background-sync.dev.js.map +1 -0
  5. data/lib/vendor/workbox-v5.1.1/workbox-background-sync.prod.js +2 -0
  6. data/lib/vendor/workbox-v5.1.1/workbox-background-sync.prod.js.map +1 -0
  7. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-broadcast-update.dev.js +288 -288
  8. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-broadcast-update.dev.js.map +1 -1
  9. data/lib/vendor/workbox-v5.1.1/workbox-broadcast-update.prod.js +2 -0
  10. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-broadcast-update.prod.js.map +1 -1
  11. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-cacheable-response.dev.js +191 -191
  12. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-cacheable-response.dev.js.map +1 -1
  13. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-cacheable-response.prod.js +2 -2
  14. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-cacheable-response.prod.js.map +1 -1
  15. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-core.dev.js +1880 -1882
  16. data/lib/vendor/workbox-v5.1.1/workbox-core.dev.js.map +1 -0
  17. data/lib/vendor/workbox-v5.1.1/workbox-core.prod.js +2 -0
  18. data/lib/vendor/workbox-v5.1.1/workbox-core.prod.js.map +1 -0
  19. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-expiration.dev.js +649 -651
  20. data/lib/vendor/workbox-v5.1.1/workbox-expiration.dev.js.map +1 -0
  21. data/lib/vendor/workbox-v5.1.1/workbox-expiration.prod.js +2 -0
  22. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-expiration.prod.js.map +1 -1
  23. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-navigation-preload.dev.js +102 -102
  24. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-navigation-preload.dev.js.map +1 -1
  25. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-navigation-preload.prod.js +2 -2
  26. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-navigation-preload.prod.js.map +1 -1
  27. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-offline-ga.dev.js +235 -235
  28. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-offline-ga.dev.js.map +1 -1
  29. data/lib/vendor/workbox-v5.1.1/workbox-offline-ga.prod.js +2 -0
  30. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-offline-ga.prod.js.map +1 -1
  31. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-precaching.dev.js +1222 -1222
  32. data/lib/vendor/workbox-v5.1.1/workbox-precaching.dev.js.map +1 -0
  33. data/lib/vendor/workbox-v5.1.1/workbox-precaching.prod.js +2 -0
  34. data/lib/vendor/workbox-v5.1.1/workbox-precaching.prod.js.map +1 -0
  35. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-range-requests.dev.js +262 -262
  36. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-range-requests.dev.js.map +1 -1
  37. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-range-requests.prod.js +2 -2
  38. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-range-requests.prod.js.map +1 -1
  39. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-routing.dev.js +923 -923
  40. data/lib/vendor/workbox-v5.1.1/workbox-routing.dev.js.map +1 -0
  41. data/lib/vendor/workbox-v5.1.1/workbox-routing.prod.js +2 -0
  42. data/lib/vendor/workbox-v5.1.1/workbox-routing.prod.js.map +1 -0
  43. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-strategies.dev.js +923 -923
  44. data/lib/vendor/workbox-v5.1.1/workbox-strategies.dev.js.map +1 -0
  45. data/lib/vendor/workbox-v5.1.1/workbox-strategies.prod.js +2 -0
  46. data/lib/vendor/workbox-v5.1.1/workbox-strategies.prod.js.map +1 -0
  47. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-streams.dev.js +318 -318
  48. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-streams.dev.js.map +1 -1
  49. data/lib/vendor/workbox-v5.1.1/workbox-streams.prod.js +2 -0
  50. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-streams.prod.js.map +1 -1
  51. data/lib/vendor/workbox-v5.1.1/workbox-sw.js +2 -0
  52. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-sw.js.map +1 -1
  53. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-window.dev.es5.mjs +1094 -1075
  54. data/lib/vendor/workbox-v5.1.1/workbox-window.dev.es5.mjs.map +1 -0
  55. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-window.dev.mjs +943 -943
  56. data/lib/vendor/workbox-v5.1.1/workbox-window.dev.mjs.map +1 -0
  57. data/lib/vendor/{workbox-v5.0.0 → workbox-v5.1.1}/workbox-window.dev.umd.js +1105 -1086
  58. data/lib/vendor/workbox-v5.1.1/workbox-window.dev.umd.js.map +1 -0
  59. data/lib/vendor/workbox-v5.1.1/workbox-window.prod.es5.mjs +2 -0
  60. data/lib/vendor/workbox-v5.1.1/workbox-window.prod.es5.mjs.map +1 -0
  61. data/lib/vendor/workbox-v5.1.1/workbox-window.prod.mjs +2 -0
  62. data/lib/vendor/workbox-v5.1.1/workbox-window.prod.mjs.map +1 -0
  63. data/lib/vendor/workbox-v5.1.1/workbox-window.prod.umd.js +2 -0
  64. data/lib/vendor/workbox-v5.1.1/workbox-window.prod.umd.js.map +1 -0
  65. metadata +65 -65
  66. data/lib/vendor/workbox-v5.0.0/workbox-background-sync.dev.js.map +0 -1
  67. data/lib/vendor/workbox-v5.0.0/workbox-background-sync.prod.js +0 -2
  68. data/lib/vendor/workbox-v5.0.0/workbox-background-sync.prod.js.map +0 -1
  69. data/lib/vendor/workbox-v5.0.0/workbox-broadcast-update.prod.js +0 -2
  70. data/lib/vendor/workbox-v5.0.0/workbox-core.dev.js.map +0 -1
  71. data/lib/vendor/workbox-v5.0.0/workbox-core.prod.js +0 -2
  72. data/lib/vendor/workbox-v5.0.0/workbox-core.prod.js.map +0 -1
  73. data/lib/vendor/workbox-v5.0.0/workbox-expiration.dev.js.map +0 -1
  74. data/lib/vendor/workbox-v5.0.0/workbox-expiration.prod.js +0 -2
  75. data/lib/vendor/workbox-v5.0.0/workbox-offline-ga.prod.js +0 -2
  76. data/lib/vendor/workbox-v5.0.0/workbox-precaching.dev.js.map +0 -1
  77. data/lib/vendor/workbox-v5.0.0/workbox-precaching.prod.js +0 -2
  78. data/lib/vendor/workbox-v5.0.0/workbox-precaching.prod.js.map +0 -1
  79. data/lib/vendor/workbox-v5.0.0/workbox-routing.dev.js.map +0 -1
  80. data/lib/vendor/workbox-v5.0.0/workbox-routing.prod.js +0 -2
  81. data/lib/vendor/workbox-v5.0.0/workbox-routing.prod.js.map +0 -1
  82. data/lib/vendor/workbox-v5.0.0/workbox-strategies.dev.js.map +0 -1
  83. data/lib/vendor/workbox-v5.0.0/workbox-strategies.prod.js +0 -2
  84. data/lib/vendor/workbox-v5.0.0/workbox-strategies.prod.js.map +0 -1
  85. data/lib/vendor/workbox-v5.0.0/workbox-streams.prod.js +0 -2
  86. data/lib/vendor/workbox-v5.0.0/workbox-sw.js +0 -2
  87. data/lib/vendor/workbox-v5.0.0/workbox-window.dev.es5.mjs.map +0 -1
  88. data/lib/vendor/workbox-v5.0.0/workbox-window.dev.mjs.map +0 -1
  89. data/lib/vendor/workbox-v5.0.0/workbox-window.dev.umd.js.map +0 -1
  90. data/lib/vendor/workbox-v5.0.0/workbox-window.prod.es5.mjs +0 -2
  91. data/lib/vendor/workbox-v5.0.0/workbox-window.prod.es5.mjs.map +0 -1
  92. data/lib/vendor/workbox-v5.0.0/workbox-window.prod.mjs +0 -2
  93. data/lib/vendor/workbox-v5.0.0/workbox-window.prod.mjs.map +0 -1
  94. data/lib/vendor/workbox-v5.0.0/workbox-window.prod.umd.js +0 -2
  95. data/lib/vendor/workbox-v5.0.0/workbox-window.prod.umd.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"workbox-broadcast-update.dev.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:broadcast-update:5.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array<string>} headersToCheck\n * @return {boolean}\n *\n * @memberof module:workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response &&\n secondResponse instanceof Response)) {\n throw new WorkboxError('invalid-responses-are-same-args');\n }\n }\n const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n return firstResponse.headers.has(header) &&\n secondResponse.headers.has(header);\n });\n if (!atLeastOneHeaderAvailable) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to determine where the response has been updated ` +\n `because none of the headers that would be checked are present.`);\n logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n }\n // Just return true, indicating the that responses are the same, since we\n // can't determine otherwise.\n return true;\n }\n return headersToCheck.every((header) => {\n const headerStateComparison = firstResponse.headers.has(header) ===\n secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) ===\n secondResponse.headers.get(header);\n return headerStateComparison && headerValueComparison;\n });\n};\nexport { responsesAreSame };\n","/*\n Copyright 2018 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*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const DEFAULT_HEADERS_TO_CHECK = [\n 'content-length',\n 'etag',\n 'last-modified',\n];\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_TYPE, CACHE_UPDATED_MESSAGE_META, DEFAULT_HEADERS_TO_CHECK } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n return {\n cacheName: data.cacheName,\n updatedURL: data.request.url,\n };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n /**\n * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n * broadcast messages on\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor({ headersToCheck, generatePayload, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n }\n /**\n * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * and sends a message (via `postMessage()`) to all window clients if the\n * responses differ (note: neither of the Responses can be\n * {@link http://stackoverflow.com/questions/39109789|opaque}).\n *\n * The message that's posted has the following format (where `payload` can\n * be customized via the `generatePayload` option the instance is created\n * with):\n *\n * ```\n * {\n * type: 'CACHE_UPDATED',\n * meta: 'workbox-broadcast-update',\n * payload: {\n * cacheName: 'the-cache-name',\n * updatedURL: 'https://example.com/'\n * }\n * }\n * ```\n *\n * @param {Object} options\n * @param {Response} [options.oldResponse] Cached response to compare.\n * @param {Response} options.newResponse Possibly updated response to compare.\n * @param {Request} options.request The request.\n * @param {string} options.cacheName Name of the cache the responses belong\n * to. This is included in the broadcast message.\n * @param {Event} [options.event] event An optional event that triggered\n * this possible cache update.\n * @return {Promise} Resolves once the update is sent.\n */\n async notifyIfUpdated(options) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(options.cacheName, 'string', {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'cacheName',\n });\n assert.isInstance(options.newResponse, Response, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'newResponse',\n });\n assert.isInstance(options.request, Request, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'request',\n });\n }\n // Without two responses there is nothing to compare.\n if (!options.oldResponse) {\n return;\n }\n if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Newer response found (and cached) for:`, options.request.url);\n }\n const messageData = {\n type: CACHE_UPDATED_MESSAGE_TYPE,\n meta: CACHE_UPDATED_MESSAGE_META,\n payload: this._generatePayload(options),\n };\n // For navigation requests, wait until the new window client exists\n // before sending the message\n if (options.request.mode === 'navigate') {\n let resultingClientId;\n if (options.event instanceof FetchEvent) {\n resultingClientId = options.event.resultingClientId;\n }\n const resultingWin = await resultingClientExists(resultingClientId);\n // Safari does not currently implement postMessage buffering and\n // there's no good way to feature detect that, so to increase the\n // chances of the message being delivered in Safari, we add a timeout.\n // We also do this if `resultingClientExists()` didn't return a client,\n // which means it timed out, so it's worth waiting a bit longer.\n if (!resultingWin || isSafari) {\n // 3500 is chosen because (according to CrUX data) 80% of mobile\n // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n // And presumably sites implementing service worker are on the\n // higher end of the performance spectrum.\n await timeout(3500);\n }\n }\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n }\n}\nexport { BroadcastCacheUpdate };\n","/*\n Copyright 2018 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*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a BroadcastCacheUpdate instance with the passed options and\n * calls its [`notifyIfUpdated()`]{@link module:workbox-broadcast-update.BroadcastCacheUpdate~notifyIfUpdated}\n * method whenever the plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor(options) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n * added to a cache.\n *\n * @private\n * @param {Object} options The input object to this function.\n * @param {string} options.cacheName Name of the cache being updated.\n * @param {Response} [options.oldResponse] The previous cached value, if any.\n * @param {Response} options.newResponse The new value in the cache.\n * @param {Request} options.request The request that triggered the update.\n * @param {Request} [options.event] The event that triggered the update.\n */\n this.cacheDidUpdate = async (options) => {\n dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n };\n this._broadcastUpdate = new BroadcastCacheUpdate(options);\n }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","Response","WorkboxError","atLeastOneHeaderAvailable","some","header","headers","has","logger","warn","debug","every","headerStateComparison","headerValueComparison","get","CACHE_UPDATED_MESSAGE_TYPE","CACHE_UPDATED_MESSAGE_META","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","_headersToCheck","_generatePayload","notifyIfUpdated","options","assert","isType","moduleName","className","funcName","paramName","isInstance","newResponse","Request","oldResponse","log","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingWin","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","BroadcastUpdatePlugin","cacheDidUpdate","dontWaitFor","_broadcastUpdate"],"mappings":"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"}
1
+ {"version":3,"file":"workbox-broadcast-update.dev.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:broadcast-update:5.1.1'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array<string>} headersToCheck\n * @return {boolean}\n *\n * @memberof module:workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response &&\n secondResponse instanceof Response)) {\n throw new WorkboxError('invalid-responses-are-same-args');\n }\n }\n const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n return firstResponse.headers.has(header) &&\n secondResponse.headers.has(header);\n });\n if (!atLeastOneHeaderAvailable) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to determine where the response has been updated ` +\n `because none of the headers that would be checked are present.`);\n logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n }\n // Just return true, indicating the that responses are the same, since we\n // can't determine otherwise.\n return true;\n }\n return headersToCheck.every((header) => {\n const headerStateComparison = firstResponse.headers.has(header) ===\n secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) ===\n secondResponse.headers.get(header);\n return headerStateComparison && headerValueComparison;\n });\n};\nexport { responsesAreSame };\n","/*\n Copyright 2018 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*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const DEFAULT_HEADERS_TO_CHECK = [\n 'content-length',\n 'etag',\n 'last-modified',\n];\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_TYPE, CACHE_UPDATED_MESSAGE_META, DEFAULT_HEADERS_TO_CHECK } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n return {\n cacheName: data.cacheName,\n updatedURL: data.request.url,\n };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n /**\n * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n * broadcast messages on\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor({ headersToCheck, generatePayload, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n }\n /**\n * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * and sends a message (via `postMessage()`) to all window clients if the\n * responses differ (note: neither of the Responses can be\n * {@link http://stackoverflow.com/questions/39109789|opaque}).\n *\n * The message that's posted has the following format (where `payload` can\n * be customized via the `generatePayload` option the instance is created\n * with):\n *\n * ```\n * {\n * type: 'CACHE_UPDATED',\n * meta: 'workbox-broadcast-update',\n * payload: {\n * cacheName: 'the-cache-name',\n * updatedURL: 'https://example.com/'\n * }\n * }\n * ```\n *\n * @param {Object} options\n * @param {Response} [options.oldResponse] Cached response to compare.\n * @param {Response} options.newResponse Possibly updated response to compare.\n * @param {Request} options.request The request.\n * @param {string} options.cacheName Name of the cache the responses belong\n * to. This is included in the broadcast message.\n * @param {Event} [options.event] event An optional event that triggered\n * this possible cache update.\n * @return {Promise} Resolves once the update is sent.\n */\n async notifyIfUpdated(options) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(options.cacheName, 'string', {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'cacheName',\n });\n assert.isInstance(options.newResponse, Response, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'newResponse',\n });\n assert.isInstance(options.request, Request, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'request',\n });\n }\n // Without two responses there is nothing to compare.\n if (!options.oldResponse) {\n return;\n }\n if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Newer response found (and cached) for:`, options.request.url);\n }\n const messageData = {\n type: CACHE_UPDATED_MESSAGE_TYPE,\n meta: CACHE_UPDATED_MESSAGE_META,\n payload: this._generatePayload(options),\n };\n // For navigation requests, wait until the new window client exists\n // before sending the message\n if (options.request.mode === 'navigate') {\n let resultingClientId;\n if (options.event instanceof FetchEvent) {\n resultingClientId = options.event.resultingClientId;\n }\n const resultingWin = await resultingClientExists(resultingClientId);\n // Safari does not currently implement postMessage buffering and\n // there's no good way to feature detect that, so to increase the\n // chances of the message being delivered in Safari, we add a timeout.\n // We also do this if `resultingClientExists()` didn't return a client,\n // which means it timed out, so it's worth waiting a bit longer.\n if (!resultingWin || isSafari) {\n // 3500 is chosen because (according to CrUX data) 80% of mobile\n // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n // And presumably sites implementing service worker are on the\n // higher end of the performance spectrum.\n await timeout(3500);\n }\n }\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n }\n}\nexport { BroadcastCacheUpdate };\n","/*\n Copyright 2018 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*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a BroadcastCacheUpdate instance with the passed options and\n * calls its [`notifyIfUpdated()`]{@link module:workbox-broadcast-update.BroadcastCacheUpdate~notifyIfUpdated}\n * method whenever the plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor(options) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n * added to a cache.\n *\n * @private\n * @param {Object} options The input object to this function.\n * @param {string} options.cacheName Name of the cache being updated.\n * @param {Response} [options.oldResponse] The previous cached value, if any.\n * @param {Response} options.newResponse The new value in the cache.\n * @param {Request} options.request The request that triggered the update.\n * @param {Request} [options.event] The event that triggered the update.\n */\n this.cacheDidUpdate = async (options) => {\n dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n };\n this._broadcastUpdate = new BroadcastCacheUpdate(options);\n }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","Response","WorkboxError","atLeastOneHeaderAvailable","some","header","headers","has","logger","warn","debug","every","headerStateComparison","headerValueComparison","get","CACHE_UPDATED_MESSAGE_TYPE","CACHE_UPDATED_MESSAGE_META","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","_headersToCheck","_generatePayload","notifyIfUpdated","options","assert","isType","moduleName","className","funcName","paramName","isInstance","newResponse","Request","oldResponse","log","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingWin","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","BroadcastUpdatePlugin","cacheDidUpdate","dontWaitFor","_broadcastUpdate"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ this.workbox=this.workbox||{},this.workbox.broadcastUpdate=function(t,a,o,s){"use strict";try{self["workbox:broadcast-update:5.1.1"]&&_()}catch(t){}const e=(t,a,o)=>!o.some(o=>t.headers.has(o)&&a.headers.has(o))||o.every(o=>{const s=t.headers.has(o)===a.headers.has(o),e=t.headers.get(o)===a.headers.get(o);return s&&e}),n=["content-length","etag","last-modified"],i=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);function c(t){return{cacheName:t.cacheName,updatedURL:t.request.url}}class r{constructor({headersToCheck:t,generatePayload:a}={}){this.t=t||n,this.o=a||c}async notifyIfUpdated(t){if(t.oldResponse&&!e(t.oldResponse,t.newResponse,this.t)){const s={type:"CACHE_UPDATED",meta:"workbox-broadcast-update",payload:this.o(t)};if("navigate"===t.request.mode){let s;t.event instanceof FetchEvent&&(s=t.event.resultingClientId),await o.resultingClientExists(s)&&!i||await a.timeout(3500)}const e=await self.clients.matchAll({type:"window"});for(const t of e)t.postMessage(s)}}}return t.BroadcastCacheUpdate=r,t.BroadcastUpdatePlugin=class{constructor(t){this.cacheDidUpdate=async t=>{s.dontWaitFor(this.s.notifyIfUpdated(t))},this.s=new r(t)}},t.responsesAreSame=e,t}({},workbox.core._private,workbox.core._private,workbox.core._private);
2
+ //# sourceMappingURL=workbox-broadcast-update.prod.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workbox-broadcast-update.prod.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:broadcast-update:5.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array<string>} headersToCheck\n * @return {boolean}\n *\n * @memberof module:workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response &&\n secondResponse instanceof Response)) {\n throw new WorkboxError('invalid-responses-are-same-args');\n }\n }\n const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n return firstResponse.headers.has(header) &&\n secondResponse.headers.has(header);\n });\n if (!atLeastOneHeaderAvailable) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to determine where the response has been updated ` +\n `because none of the headers that would be checked are present.`);\n logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n }\n // Just return true, indicating the that responses are the same, since we\n // can't determine otherwise.\n return true;\n }\n return headersToCheck.every((header) => {\n const headerStateComparison = firstResponse.headers.has(header) ===\n secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) ===\n secondResponse.headers.get(header);\n return headerStateComparison && headerValueComparison;\n });\n};\nexport { responsesAreSame };\n","/*\n Copyright 2018 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*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const DEFAULT_HEADERS_TO_CHECK = [\n 'content-length',\n 'etag',\n 'last-modified',\n];\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_TYPE, CACHE_UPDATED_MESSAGE_META, DEFAULT_HEADERS_TO_CHECK } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n return {\n cacheName: data.cacheName,\n updatedURL: data.request.url,\n };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n /**\n * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n * broadcast messages on\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor({ headersToCheck, generatePayload, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n }\n /**\n * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * and sends a message (via `postMessage()`) to all window clients if the\n * responses differ (note: neither of the Responses can be\n * {@link http://stackoverflow.com/questions/39109789|opaque}).\n *\n * The message that's posted has the following format (where `payload` can\n * be customized via the `generatePayload` option the instance is created\n * with):\n *\n * ```\n * {\n * type: 'CACHE_UPDATED',\n * meta: 'workbox-broadcast-update',\n * payload: {\n * cacheName: 'the-cache-name',\n * updatedURL: 'https://example.com/'\n * }\n * }\n * ```\n *\n * @param {Object} options\n * @param {Response} [options.oldResponse] Cached response to compare.\n * @param {Response} options.newResponse Possibly updated response to compare.\n * @param {Request} options.request The request.\n * @param {string} options.cacheName Name of the cache the responses belong\n * to. This is included in the broadcast message.\n * @param {Event} [options.event] event An optional event that triggered\n * this possible cache update.\n * @return {Promise} Resolves once the update is sent.\n */\n async notifyIfUpdated(options) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(options.cacheName, 'string', {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'cacheName',\n });\n assert.isInstance(options.newResponse, Response, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'newResponse',\n });\n assert.isInstance(options.request, Request, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'request',\n });\n }\n // Without two responses there is nothing to compare.\n if (!options.oldResponse) {\n return;\n }\n if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Newer response found (and cached) for:`, options.request.url);\n }\n const messageData = {\n type: CACHE_UPDATED_MESSAGE_TYPE,\n meta: CACHE_UPDATED_MESSAGE_META,\n payload: this._generatePayload(options),\n };\n // For navigation requests, wait until the new window client exists\n // before sending the message\n if (options.request.mode === 'navigate') {\n let resultingClientId;\n if (options.event instanceof FetchEvent) {\n resultingClientId = options.event.resultingClientId;\n }\n const resultingWin = await resultingClientExists(resultingClientId);\n // Safari does not currently implement postMessage buffering and\n // there's no good way to feature detect that, so to increase the\n // chances of the message being delivered in Safari, we add a timeout.\n // We also do this if `resultingClientExists()` didn't return a client,\n // which means it timed out, so it's worth waiting a bit longer.\n if (!resultingWin || isSafari) {\n // 3500 is chosen because (according to CrUX data) 80% of mobile\n // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n // And presumably sites implementing service worker are on the\n // higher end of the performance spectrum.\n await timeout(3500);\n }\n }\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n }\n}\nexport { BroadcastCacheUpdate };\n","/*\n Copyright 2018 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*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a BroadcastCacheUpdate instance with the passed options and\n * calls its [`notifyIfUpdated()`]{@link module:workbox-broadcast-update.BroadcastCacheUpdate~notifyIfUpdated}\n * method whenever the plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor(options) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n * added to a cache.\n *\n * @private\n * @param {Object} options The input object to this function.\n * @param {string} options.cacheName Name of the cache being updated.\n * @param {Response} [options.oldResponse] The previous cached value, if any.\n * @param {Response} options.newResponse The new value in the cache.\n * @param {Request} options.request The request that triggered the update.\n * @param {Request} [options.event] The event that triggered the update.\n */\n this.cacheDidUpdate = async (options) => {\n dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n };\n this._broadcastUpdate = new BroadcastCacheUpdate(options);\n }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","some","header","headers","has","every","headerStateComparison","headerValueComparison","get","CACHE_UPDATED_MESSAGE_TYPE","CACHE_UPDATED_MESSAGE_META","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","_headersToCheck","_generatePayload","options","oldResponse","newResponse","this","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","cacheDidUpdate","async","dontWaitFor","_broadcastUpdate","notifyIfUpdated"],"mappings":"0FAEA,IACIA,KAAK,mCAAqCC,IAE9C,MAAOC,UCgBDC,EAAmB,CAACC,EAAeC,EAAgBC,YAOnBA,EAAeC,KAAMC,GAC5CJ,EAAcK,QAAQC,IAAIF,IAC7BH,EAAeI,QAAQC,IAAIF,KAY5BF,EAAeK,MAAOH,UACnBI,EAAwBR,EAAcK,QAAQC,IAAIF,KACpDH,EAAeI,QAAQC,IAAIF,GACzBK,EAAwBT,EAAcK,QAAQK,IAAIN,KACpDH,EAAeI,QAAQK,IAAIN,UACxBI,GAAyBC,KCvC3BE,EAA6B,gBAC7BC,EAA6B,2BAC7BC,EAA2B,CACpC,iBACA,OACA,iBCIEC,EAAW,iCAAiCC,KAAKC,UAAUC,WAQjE,SAASC,EAAwBC,SACtB,CACHC,UAAWD,EAAKC,UAChBC,WAAYF,EAAKG,QAAQC,KAYjC,MAAMC,EAaFC,aAAYvB,eAAEA,EAAFwB,gBAAkBA,GAAqB,SAC1CC,EAAkBzB,GAAkBW,OACpCe,EAAmBF,GAAmBR,wBAiCzBW,MAsBbA,EAAQC,cAGR/B,EAAiB8B,EAAQC,YAAaD,EAAQE,YAAaC,KAAKL,GAAkB,OAI7EM,EAAc,CAChBC,KAAMvB,EACNwB,KAAMvB,EACNwB,QAASJ,KAAKJ,EAAiBC,OAIN,aAAzBA,EAAQP,QAAQe,KAAqB,KACjCC,EACAT,EAAQU,iBAAiBC,aACzBF,EAAoBT,EAAQU,MAAMD,yBAEXG,wBAAsBH,KAM5BxB,SAKX4B,UAAQ,YAGhBC,QAAgB/C,KAAKgD,QAAQC,SAAS,CAAEX,KAAM,eAC/C,MAAMY,KAAOH,EACdG,EAAIC,YAAYd,6DCjIhC,MAcIR,YAAYI,QAcHmB,eAAiBC,OAAAA,IAClBC,cAAYlB,KAAKmB,EAAiBC,gBAAgBvB,WAEjDsB,EAAmB,IAAI3B,EAAqBK"}
1
+ {"version":3,"file":"workbox-broadcast-update.prod.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:broadcast-update:5.1.1'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array<string>} headersToCheck\n * @return {boolean}\n *\n * @memberof module:workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(firstResponse instanceof Response &&\n secondResponse instanceof Response)) {\n throw new WorkboxError('invalid-responses-are-same-args');\n }\n }\n const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n return firstResponse.headers.has(header) &&\n secondResponse.headers.has(header);\n });\n if (!atLeastOneHeaderAvailable) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`Unable to determine where the response has been updated ` +\n `because none of the headers that would be checked are present.`);\n logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n }\n // Just return true, indicating the that responses are the same, since we\n // can't determine otherwise.\n return true;\n }\n return headersToCheck.every((header) => {\n const headerStateComparison = firstResponse.headers.has(header) ===\n secondResponse.headers.has(header);\n const headerValueComparison = firstResponse.headers.get(header) ===\n secondResponse.headers.get(header);\n return headerStateComparison && headerValueComparison;\n });\n};\nexport { responsesAreSame };\n","/*\n Copyright 2018 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*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const DEFAULT_HEADERS_TO_CHECK = [\n 'content-length',\n 'etag',\n 'last-modified',\n];\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_TYPE, CACHE_UPDATED_MESSAGE_META, DEFAULT_HEADERS_TO_CHECK } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n return {\n cacheName: data.cacheName,\n updatedURL: data.request.url,\n };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n /**\n * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n * broadcast messages on\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor({ headersToCheck, generatePayload, } = {}) {\n this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n this._generatePayload = generatePayload || defaultPayloadGenerator;\n }\n /**\n * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * and sends a message (via `postMessage()`) to all window clients if the\n * responses differ (note: neither of the Responses can be\n * {@link http://stackoverflow.com/questions/39109789|opaque}).\n *\n * The message that's posted has the following format (where `payload` can\n * be customized via the `generatePayload` option the instance is created\n * with):\n *\n * ```\n * {\n * type: 'CACHE_UPDATED',\n * meta: 'workbox-broadcast-update',\n * payload: {\n * cacheName: 'the-cache-name',\n * updatedURL: 'https://example.com/'\n * }\n * }\n * ```\n *\n * @param {Object} options\n * @param {Response} [options.oldResponse] Cached response to compare.\n * @param {Response} options.newResponse Possibly updated response to compare.\n * @param {Request} options.request The request.\n * @param {string} options.cacheName Name of the cache the responses belong\n * to. This is included in the broadcast message.\n * @param {Event} [options.event] event An optional event that triggered\n * this possible cache update.\n * @return {Promise} Resolves once the update is sent.\n */\n async notifyIfUpdated(options) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isType(options.cacheName, 'string', {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'cacheName',\n });\n assert.isInstance(options.newResponse, Response, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'newResponse',\n });\n assert.isInstance(options.request, Request, {\n moduleName: 'workbox-broadcast-update',\n className: 'BroadcastCacheUpdate',\n funcName: 'notifyIfUpdated',\n paramName: 'request',\n });\n }\n // Without two responses there is nothing to compare.\n if (!options.oldResponse) {\n return;\n }\n if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Newer response found (and cached) for:`, options.request.url);\n }\n const messageData = {\n type: CACHE_UPDATED_MESSAGE_TYPE,\n meta: CACHE_UPDATED_MESSAGE_META,\n payload: this._generatePayload(options),\n };\n // For navigation requests, wait until the new window client exists\n // before sending the message\n if (options.request.mode === 'navigate') {\n let resultingClientId;\n if (options.event instanceof FetchEvent) {\n resultingClientId = options.event.resultingClientId;\n }\n const resultingWin = await resultingClientExists(resultingClientId);\n // Safari does not currently implement postMessage buffering and\n // there's no good way to feature detect that, so to increase the\n // chances of the message being delivered in Safari, we add a timeout.\n // We also do this if `resultingClientExists()` didn't return a client,\n // which means it timed out, so it's worth waiting a bit longer.\n if (!resultingWin || isSafari) {\n // 3500 is chosen because (according to CrUX data) 80% of mobile\n // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n // And presumably sites implementing service worker are on the\n // higher end of the performance spectrum.\n await timeout(3500);\n }\n }\n const windows = await self.clients.matchAll({ type: 'window' });\n for (const win of windows) {\n win.postMessage(messageData);\n }\n }\n }\n}\nexport { BroadcastCacheUpdate };\n","/*\n Copyright 2018 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*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n /**\n * Construct a BroadcastCacheUpdate instance with the passed options and\n * calls its [`notifyIfUpdated()`]{@link module:workbox-broadcast-update.BroadcastCacheUpdate~notifyIfUpdated}\n * method whenever the plugin's `cacheDidUpdate` callback is invoked.\n *\n * @param {Object} options\n * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n * A list of headers that will be used to determine whether the responses\n * differ.\n * @param {string} [options.generatePayload] A function whose return value\n * will be used as the `payload` field in any cache update messages sent\n * to the window clients.\n */\n constructor(options) {\n /**\n * A \"lifecycle\" callback that will be triggered automatically by the\n * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n * added to a cache.\n *\n * @private\n * @param {Object} options The input object to this function.\n * @param {string} options.cacheName Name of the cache being updated.\n * @param {Response} [options.oldResponse] The previous cached value, if any.\n * @param {Response} options.newResponse The new value in the cache.\n * @param {Request} options.request The request that triggered the update.\n * @param {Request} [options.event] The event that triggered the update.\n */\n this.cacheDidUpdate = async (options) => {\n dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n };\n this._broadcastUpdate = new BroadcastCacheUpdate(options);\n }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","some","header","headers","has","every","headerStateComparison","headerValueComparison","get","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","_headersToCheck","_generatePayload","options","oldResponse","newResponse","this","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","cacheDidUpdate","async","dontWaitFor","_broadcastUpdate","notifyIfUpdated"],"mappings":"0FAEA,IACIA,KAAK,mCAAqCC,IAE9C,MAAOC,UCgBDC,EAAmB,CAACC,EAAeC,EAAgBC,KAOnBA,EAAeC,KAAMC,GAC5CJ,EAAcK,QAAQC,IAAIF,IAC7BH,EAAeI,QAAQC,IAAIF,KAY5BF,EAAeK,MAAOH,UACnBI,EAAwBR,EAAcK,QAAQC,IAAIF,KACpDH,EAAeI,QAAQC,IAAIF,GACzBK,EAAwBT,EAAcK,QAAQK,IAAIN,KACpDH,EAAeI,QAAQK,IAAIN,UACxBI,GAAyBC,ICrC3BE,EAA2B,CACpC,iBACA,OACA,iBCIEC,EAAW,iCAAiCC,KAAKC,UAAUC,WAQjE,SAASC,EAAwBC,SACtB,CACHC,UAAWD,EAAKC,UAChBC,WAAYF,EAAKG,QAAQC,KAYjC,MAAMC,EAaFC,aAAYrB,eAAEA,EAAFsB,gBAAkBA,GAAqB,SAC1CC,EAAkBvB,GAAkBS,OACpCe,EAAmBF,GAAmBR,wBAiCzBW,MAsBbA,EAAQC,cAGR7B,EAAiB4B,EAAQC,YAAaD,EAAQE,YAAaC,KAAKL,GAAkB,OAI7EM,EAAc,CAChBC,KD9G0B,gBC+G1BC,KD9G0B,2BC+G1BC,QAASJ,KAAKJ,EAAiBC,OAIN,aAAzBA,EAAQP,QAAQe,KAAqB,KACjCC,EACAT,EAAQU,iBAAiBC,aACzBF,EAAoBT,EAAQU,MAAMD,yBAEXG,wBAAsBH,KAM5BxB,SAKX4B,UAAQ,YAGhBC,QAAgB7C,KAAK8C,QAAQC,SAAS,CAAEX,KAAM,eAC/C,MAAMY,KAAOH,EACdG,EAAIC,YAAYd,6DCjIhC,MAcIR,YAAYI,QAcHmB,eAAiBC,MAAAA,IAClBC,cAAYlB,KAAKmB,EAAiBC,gBAAgBvB,UAEjDsB,EAAmB,IAAI3B,EAAqBK"}
@@ -1,191 +1,191 @@
1
- this.workbox = this.workbox || {};
2
- this.workbox.cacheableResponse = (function (exports, assert_js, WorkboxError_js, getFriendlyURL_js, logger_js) {
3
- 'use strict';
4
-
5
- try {
6
- self['workbox:cacheable-response:5.0.0'] && _();
7
- } catch (e) {}
8
-
9
- /*
10
- Copyright 2018 Google LLC
11
-
12
- Use of this source code is governed by an MIT-style
13
- license that can be found in the LICENSE file or at
14
- https://opensource.org/licenses/MIT.
15
- */
16
- /**
17
- * This class allows you to set up rules determining what
18
- * status codes and/or headers need to be present in order for a
19
- * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
20
- * to be considered cacheable.
21
- *
22
- * @memberof module:workbox-cacheable-response
23
- */
24
-
25
- class CacheableResponse {
26
- /**
27
- * To construct a new CacheableResponse instance you must provide at least
28
- * one of the `config` properties.
29
- *
30
- * If both `statuses` and `headers` are specified, then both conditions must
31
- * be met for the `Response` to be considered cacheable.
32
- *
33
- * @param {Object} config
34
- * @param {Array<number>} [config.statuses] One or more status codes that a
35
- * `Response` can have and be considered cacheable.
36
- * @param {Object<string,string>} [config.headers] A mapping of header names
37
- * and expected values that a `Response` can have and be considered cacheable.
38
- * If multiple headers are provided, only one needs to be present.
39
- */
40
- constructor(config = {}) {
41
- {
42
- if (!(config.statuses || config.headers)) {
43
- throw new WorkboxError_js.WorkboxError('statuses-or-headers-required', {
44
- moduleName: 'workbox-cacheable-response',
45
- className: 'CacheableResponse',
46
- funcName: 'constructor'
47
- });
48
- }
49
-
50
- if (config.statuses) {
51
- assert_js.assert.isArray(config.statuses, {
52
- moduleName: 'workbox-cacheable-response',
53
- className: 'CacheableResponse',
54
- funcName: 'constructor',
55
- paramName: 'config.statuses'
56
- });
57
- }
58
-
59
- if (config.headers) {
60
- assert_js.assert.isType(config.headers, 'object', {
61
- moduleName: 'workbox-cacheable-response',
62
- className: 'CacheableResponse',
63
- funcName: 'constructor',
64
- paramName: 'config.headers'
65
- });
66
- }
67
- }
68
-
69
- this._statuses = config.statuses;
70
- this._headers = config.headers;
71
- }
72
- /**
73
- * Checks a response to see whether it's cacheable or not, based on this
74
- * object's configuration.
75
- *
76
- * @param {Response} response The response whose cacheability is being
77
- * checked.
78
- * @return {boolean} `true` if the `Response` is cacheable, and `false`
79
- * otherwise.
80
- */
81
-
82
-
83
- isResponseCacheable(response) {
84
- {
85
- assert_js.assert.isInstance(response, Response, {
86
- moduleName: 'workbox-cacheable-response',
87
- className: 'CacheableResponse',
88
- funcName: 'isResponseCacheable',
89
- paramName: 'response'
90
- });
91
- }
92
-
93
- let cacheable = true;
94
-
95
- if (this._statuses) {
96
- cacheable = this._statuses.includes(response.status);
97
- }
98
-
99
- if (this._headers && cacheable) {
100
- cacheable = Object.keys(this._headers).some(headerName => {
101
- return response.headers.get(headerName) === this._headers[headerName];
102
- });
103
- }
104
-
105
- {
106
- if (!cacheable) {
107
- logger_js.logger.groupCollapsed(`The request for ` + `'${getFriendlyURL_js.getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`);
108
- logger_js.logger.groupCollapsed(`View cacheability criteria here.`);
109
- logger_js.logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));
110
- logger_js.logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));
111
- logger_js.logger.groupEnd();
112
- const logFriendlyHeaders = {};
113
- response.headers.forEach((value, key) => {
114
- logFriendlyHeaders[key] = value;
115
- });
116
- logger_js.logger.groupCollapsed(`View response status and headers here.`);
117
- logger_js.logger.log(`Response status: ` + response.status);
118
- logger_js.logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));
119
- logger_js.logger.groupEnd();
120
- logger_js.logger.groupCollapsed(`View full response details here.`);
121
- logger_js.logger.log(response.headers);
122
- logger_js.logger.log(response);
123
- logger_js.logger.groupEnd();
124
- logger_js.logger.groupEnd();
125
- }
126
- }
127
-
128
- return cacheable;
129
- }
130
-
131
- }
132
-
133
- /*
134
- Copyright 2018 Google LLC
135
-
136
- Use of this source code is governed by an MIT-style
137
- license that can be found in the LICENSE file or at
138
- https://opensource.org/licenses/MIT.
139
- */
140
- /**
141
- * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
142
- * easier to add in cacheability checks to requests made via Workbox's built-in
143
- * strategies.
144
- *
145
- * @memberof module:workbox-cacheable-response
146
- */
147
-
148
- class CacheableResponsePlugin {
149
- /**
150
- * To construct a new CacheableResponsePlugin instance you must provide at
151
- * least one of the `config` properties.
152
- *
153
- * If both `statuses` and `headers` are specified, then both conditions must
154
- * be met for the `Response` to be considered cacheable.
155
- *
156
- * @param {Object} config
157
- * @param {Array<number>} [config.statuses] One or more status codes that a
158
- * `Response` can have and be considered cacheable.
159
- * @param {Object<string,string>} [config.headers] A mapping of header names
160
- * and expected values that a `Response` can have and be considered cacheable.
161
- * If multiple headers are provided, only one needs to be present.
162
- */
163
- constructor(config) {
164
- /**
165
- * @param {Object} options
166
- * @param {Response} options.response
167
- * @return {Response|null}
168
- * @private
169
- */
170
- this.cacheWillUpdate = async ({
171
- response
172
- }) => {
173
- if (this._cacheableResponse.isResponseCacheable(response)) {
174
- return response;
175
- }
176
-
177
- return null;
178
- };
179
-
180
- this._cacheableResponse = new CacheableResponse(config);
181
- }
182
-
183
- }
184
-
185
- exports.CacheableResponse = CacheableResponse;
186
- exports.CacheableResponsePlugin = CacheableResponsePlugin;
187
-
188
- return exports;
189
-
190
- }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
191
- //# sourceMappingURL=workbox-cacheable-response.dev.js.map
1
+ this.workbox = this.workbox || {};
2
+ this.workbox.cacheableResponse = (function (exports, assert_js, WorkboxError_js, getFriendlyURL_js, logger_js) {
3
+ 'use strict';
4
+
5
+ try {
6
+ self['workbox:cacheable-response:5.1.1'] && _();
7
+ } catch (e) {}
8
+
9
+ /*
10
+ Copyright 2018 Google LLC
11
+
12
+ Use of this source code is governed by an MIT-style
13
+ license that can be found in the LICENSE file or at
14
+ https://opensource.org/licenses/MIT.
15
+ */
16
+ /**
17
+ * This class allows you to set up rules determining what
18
+ * status codes and/or headers need to be present in order for a
19
+ * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
20
+ * to be considered cacheable.
21
+ *
22
+ * @memberof module:workbox-cacheable-response
23
+ */
24
+
25
+ class CacheableResponse {
26
+ /**
27
+ * To construct a new CacheableResponse instance you must provide at least
28
+ * one of the `config` properties.
29
+ *
30
+ * If both `statuses` and `headers` are specified, then both conditions must
31
+ * be met for the `Response` to be considered cacheable.
32
+ *
33
+ * @param {Object} config
34
+ * @param {Array<number>} [config.statuses] One or more status codes that a
35
+ * `Response` can have and be considered cacheable.
36
+ * @param {Object<string,string>} [config.headers] A mapping of header names
37
+ * and expected values that a `Response` can have and be considered cacheable.
38
+ * If multiple headers are provided, only one needs to be present.
39
+ */
40
+ constructor(config = {}) {
41
+ {
42
+ if (!(config.statuses || config.headers)) {
43
+ throw new WorkboxError_js.WorkboxError('statuses-or-headers-required', {
44
+ moduleName: 'workbox-cacheable-response',
45
+ className: 'CacheableResponse',
46
+ funcName: 'constructor'
47
+ });
48
+ }
49
+
50
+ if (config.statuses) {
51
+ assert_js.assert.isArray(config.statuses, {
52
+ moduleName: 'workbox-cacheable-response',
53
+ className: 'CacheableResponse',
54
+ funcName: 'constructor',
55
+ paramName: 'config.statuses'
56
+ });
57
+ }
58
+
59
+ if (config.headers) {
60
+ assert_js.assert.isType(config.headers, 'object', {
61
+ moduleName: 'workbox-cacheable-response',
62
+ className: 'CacheableResponse',
63
+ funcName: 'constructor',
64
+ paramName: 'config.headers'
65
+ });
66
+ }
67
+ }
68
+
69
+ this._statuses = config.statuses;
70
+ this._headers = config.headers;
71
+ }
72
+ /**
73
+ * Checks a response to see whether it's cacheable or not, based on this
74
+ * object's configuration.
75
+ *
76
+ * @param {Response} response The response whose cacheability is being
77
+ * checked.
78
+ * @return {boolean} `true` if the `Response` is cacheable, and `false`
79
+ * otherwise.
80
+ */
81
+
82
+
83
+ isResponseCacheable(response) {
84
+ {
85
+ assert_js.assert.isInstance(response, Response, {
86
+ moduleName: 'workbox-cacheable-response',
87
+ className: 'CacheableResponse',
88
+ funcName: 'isResponseCacheable',
89
+ paramName: 'response'
90
+ });
91
+ }
92
+
93
+ let cacheable = true;
94
+
95
+ if (this._statuses) {
96
+ cacheable = this._statuses.includes(response.status);
97
+ }
98
+
99
+ if (this._headers && cacheable) {
100
+ cacheable = Object.keys(this._headers).some(headerName => {
101
+ return response.headers.get(headerName) === this._headers[headerName];
102
+ });
103
+ }
104
+
105
+ {
106
+ if (!cacheable) {
107
+ logger_js.logger.groupCollapsed(`The request for ` + `'${getFriendlyURL_js.getFriendlyURL(response.url)}' returned a response that does ` + `not meet the criteria for being cached.`);
108
+ logger_js.logger.groupCollapsed(`View cacheability criteria here.`);
109
+ logger_js.logger.log(`Cacheable statuses: ` + JSON.stringify(this._statuses));
110
+ logger_js.logger.log(`Cacheable headers: ` + JSON.stringify(this._headers, null, 2));
111
+ logger_js.logger.groupEnd();
112
+ const logFriendlyHeaders = {};
113
+ response.headers.forEach((value, key) => {
114
+ logFriendlyHeaders[key] = value;
115
+ });
116
+ logger_js.logger.groupCollapsed(`View response status and headers here.`);
117
+ logger_js.logger.log(`Response status: ` + response.status);
118
+ logger_js.logger.log(`Response headers: ` + JSON.stringify(logFriendlyHeaders, null, 2));
119
+ logger_js.logger.groupEnd();
120
+ logger_js.logger.groupCollapsed(`View full response details here.`);
121
+ logger_js.logger.log(response.headers);
122
+ logger_js.logger.log(response);
123
+ logger_js.logger.groupEnd();
124
+ logger_js.logger.groupEnd();
125
+ }
126
+ }
127
+
128
+ return cacheable;
129
+ }
130
+
131
+ }
132
+
133
+ /*
134
+ Copyright 2018 Google LLC
135
+
136
+ Use of this source code is governed by an MIT-style
137
+ license that can be found in the LICENSE file or at
138
+ https://opensource.org/licenses/MIT.
139
+ */
140
+ /**
141
+ * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it
142
+ * easier to add in cacheability checks to requests made via Workbox's built-in
143
+ * strategies.
144
+ *
145
+ * @memberof module:workbox-cacheable-response
146
+ */
147
+
148
+ class CacheableResponsePlugin {
149
+ /**
150
+ * To construct a new CacheableResponsePlugin instance you must provide at
151
+ * least one of the `config` properties.
152
+ *
153
+ * If both `statuses` and `headers` are specified, then both conditions must
154
+ * be met for the `Response` to be considered cacheable.
155
+ *
156
+ * @param {Object} config
157
+ * @param {Array<number>} [config.statuses] One or more status codes that a
158
+ * `Response` can have and be considered cacheable.
159
+ * @param {Object<string,string>} [config.headers] A mapping of header names
160
+ * and expected values that a `Response` can have and be considered cacheable.
161
+ * If multiple headers are provided, only one needs to be present.
162
+ */
163
+ constructor(config) {
164
+ /**
165
+ * @param {Object} options
166
+ * @param {Response} options.response
167
+ * @return {Response|null}
168
+ * @private
169
+ */
170
+ this.cacheWillUpdate = async ({
171
+ response
172
+ }) => {
173
+ if (this._cacheableResponse.isResponseCacheable(response)) {
174
+ return response;
175
+ }
176
+
177
+ return null;
178
+ };
179
+
180
+ this._cacheableResponse = new CacheableResponse(config);
181
+ }
182
+
183
+ }
184
+
185
+ exports.CacheableResponse = CacheableResponse;
186
+ exports.CacheableResponsePlugin = CacheableResponsePlugin;
187
+
188
+ return exports;
189
+
190
+ }({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
191
+ //# sourceMappingURL=workbox-cacheable-response.dev.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workbox-cacheable-response.dev.js","sources":["../_version.js","../CacheableResponse.js","../CacheableResponsePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:cacheable-response:5.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * This class allows you to set up rules determining what\n * status codes and/or headers need to be present in order for a\n * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * to be considered cacheable.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponse {\n /**\n * To construct a new CacheableResponse instance you must provide at least\n * one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.statuses || config.headers)) {\n throw new WorkboxError('statuses-or-headers-required', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n });\n }\n if (config.statuses) {\n assert.isArray(config.statuses, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.statuses',\n });\n }\n if (config.headers) {\n assert.isType(config.headers, 'object', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.headers',\n });\n }\n }\n this._statuses = config.statuses;\n this._headers = config.headers;\n }\n /**\n * Checks a response to see whether it's cacheable or not, based on this\n * object's configuration.\n *\n * @param {Response} response The response whose cacheability is being\n * checked.\n * @return {boolean} `true` if the `Response` is cacheable, and `false`\n * otherwise.\n */\n isResponseCacheable(response) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(response, Response, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'isResponseCacheable',\n paramName: 'response',\n });\n }\n let cacheable = true;\n if (this._statuses) {\n cacheable = this._statuses.includes(response.status);\n }\n if (this._headers && cacheable) {\n cacheable = Object.keys(this._headers).some((headerName) => {\n return response.headers.get(headerName) === this._headers[headerName];\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!cacheable) {\n logger.groupCollapsed(`The request for ` +\n `'${getFriendlyURL(response.url)}' returned a response that does ` +\n `not meet the criteria for being cached.`);\n logger.groupCollapsed(`View cacheability criteria here.`);\n logger.log(`Cacheable statuses: ` +\n JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` +\n JSON.stringify(this._headers, null, 2));\n logger.groupEnd();\n const logFriendlyHeaders = {};\n response.headers.forEach((value, key) => {\n logFriendlyHeaders[key] = value;\n });\n logger.groupCollapsed(`View response status and headers here.`);\n logger.log(`Response status: ` + response.status);\n logger.log(`Response headers: ` +\n JSON.stringify(logFriendlyHeaders, null, 2));\n logger.groupEnd();\n logger.groupCollapsed(`View full response details here.`);\n logger.log(response.headers);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n }\n return cacheable;\n }\n}\nexport { CacheableResponse };\n","/*\n Copyright 2018 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*/\nimport { CacheableResponse } from './CacheableResponse.js';\nimport './_version.js';\n/**\n * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it\n * easier to add in cacheability checks to requests made via Workbox's built-in\n * strategies.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponsePlugin {\n /**\n * To construct a new CacheableResponsePlugin instance you must provide at\n * least one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config) {\n /**\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n * @private\n */\n this.cacheWillUpdate = async ({ response }) => {\n if (this._cacheableResponse.isResponseCacheable(response)) {\n return response;\n }\n return null;\n };\n this._cacheableResponse = new CacheableResponse(config);\n }\n}\nexport { CacheableResponsePlugin };\n"],"names":["self","_","e","CacheableResponse","constructor","config","statuses","headers","WorkboxError","moduleName","className","funcName","assert","isArray","paramName","isType","_statuses","_headers","isResponseCacheable","response","isInstance","Response","cacheable","includes","status","Object","keys","some","headerName","get","logger","groupCollapsed","getFriendlyURL","url","log","JSON","stringify","groupEnd","logFriendlyHeaders","forEach","value","key","CacheableResponsePlugin","cacheWillUpdate","_cacheableResponse"],"mappings":"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"}
1
+ {"version":3,"file":"workbox-cacheable-response.dev.js","sources":["../_version.js","../CacheableResponse.js","../CacheableResponsePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:cacheable-response:5.1.1'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * This class allows you to set up rules determining what\n * status codes and/or headers need to be present in order for a\n * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * to be considered cacheable.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponse {\n /**\n * To construct a new CacheableResponse instance you must provide at least\n * one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.statuses || config.headers)) {\n throw new WorkboxError('statuses-or-headers-required', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n });\n }\n if (config.statuses) {\n assert.isArray(config.statuses, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.statuses',\n });\n }\n if (config.headers) {\n assert.isType(config.headers, 'object', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.headers',\n });\n }\n }\n this._statuses = config.statuses;\n this._headers = config.headers;\n }\n /**\n * Checks a response to see whether it's cacheable or not, based on this\n * object's configuration.\n *\n * @param {Response} response The response whose cacheability is being\n * checked.\n * @return {boolean} `true` if the `Response` is cacheable, and `false`\n * otherwise.\n */\n isResponseCacheable(response) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(response, Response, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'isResponseCacheable',\n paramName: 'response',\n });\n }\n let cacheable = true;\n if (this._statuses) {\n cacheable = this._statuses.includes(response.status);\n }\n if (this._headers && cacheable) {\n cacheable = Object.keys(this._headers).some((headerName) => {\n return response.headers.get(headerName) === this._headers[headerName];\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!cacheable) {\n logger.groupCollapsed(`The request for ` +\n `'${getFriendlyURL(response.url)}' returned a response that does ` +\n `not meet the criteria for being cached.`);\n logger.groupCollapsed(`View cacheability criteria here.`);\n logger.log(`Cacheable statuses: ` +\n JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` +\n JSON.stringify(this._headers, null, 2));\n logger.groupEnd();\n const logFriendlyHeaders = {};\n response.headers.forEach((value, key) => {\n logFriendlyHeaders[key] = value;\n });\n logger.groupCollapsed(`View response status and headers here.`);\n logger.log(`Response status: ` + response.status);\n logger.log(`Response headers: ` +\n JSON.stringify(logFriendlyHeaders, null, 2));\n logger.groupEnd();\n logger.groupCollapsed(`View full response details here.`);\n logger.log(response.headers);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n }\n return cacheable;\n }\n}\nexport { CacheableResponse };\n","/*\n Copyright 2018 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*/\nimport { CacheableResponse } from './CacheableResponse.js';\nimport './_version.js';\n/**\n * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it\n * easier to add in cacheability checks to requests made via Workbox's built-in\n * strategies.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponsePlugin {\n /**\n * To construct a new CacheableResponsePlugin instance you must provide at\n * least one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config) {\n /**\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n * @private\n */\n this.cacheWillUpdate = async ({ response }) => {\n if (this._cacheableResponse.isResponseCacheable(response)) {\n return response;\n }\n return null;\n };\n this._cacheableResponse = new CacheableResponse(config);\n }\n}\nexport { CacheableResponsePlugin };\n"],"names":["self","_","e","CacheableResponse","constructor","config","statuses","headers","WorkboxError","moduleName","className","funcName","assert","isArray","paramName","isType","_statuses","_headers","isResponseCacheable","response","isInstance","Response","cacheable","includes","status","Object","keys","some","headerName","get","logger","groupCollapsed","getFriendlyURL","url","log","JSON","stringify","groupEnd","logFriendlyHeaders","forEach","value","key","CacheableResponsePlugin","cacheWillUpdate","_cacheableResponse"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- this.workbox=this.workbox||{},this.workbox.cacheableResponse=function(s){"use strict";try{self["workbox:cacheable-response:5.0.0"]&&_()}catch(s){}class t{constructor(s={}){this.s=s.statuses,this.t=s.headers}isResponseCacheable(s){let t=!0;return this.s&&(t=this.s.includes(s.status)),this.t&&t&&(t=Object.keys(this.t).some(t=>s.headers.get(t)===this.t[t])),t}}return s.CacheableResponse=t,s.CacheableResponsePlugin=class{constructor(s){this.cacheWillUpdate=(async({response:s})=>this.i.isResponseCacheable(s)?s:null),this.i=new t(s)}},s}({});
2
- //# sourceMappingURL=workbox-cacheable-response.prod.js.map
1
+ this.workbox=this.workbox||{},this.workbox.cacheableResponse=function(s){"use strict";try{self["workbox:cacheable-response:5.1.1"]&&_()}catch(s){}class t{constructor(s={}){this.s=s.statuses,this.t=s.headers}isResponseCacheable(s){let t=!0;return this.s&&(t=this.s.includes(s.status)),this.t&&t&&(t=Object.keys(this.t).some(t=>s.headers.get(t)===this.t[t])),t}}return s.CacheableResponse=t,s.CacheableResponsePlugin=class{constructor(s){this.cacheWillUpdate=async({response:s})=>this.i.isResponseCacheable(s)?s:null,this.i=new t(s)}},s}({});
2
+ //# sourceMappingURL=workbox-cacheable-response.prod.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workbox-cacheable-response.prod.js","sources":["../_version.js","../CacheableResponse.js","../CacheableResponsePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:cacheable-response:5.0.0'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * This class allows you to set up rules determining what\n * status codes and/or headers need to be present in order for a\n * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * to be considered cacheable.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponse {\n /**\n * To construct a new CacheableResponse instance you must provide at least\n * one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.statuses || config.headers)) {\n throw new WorkboxError('statuses-or-headers-required', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n });\n }\n if (config.statuses) {\n assert.isArray(config.statuses, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.statuses',\n });\n }\n if (config.headers) {\n assert.isType(config.headers, 'object', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.headers',\n });\n }\n }\n this._statuses = config.statuses;\n this._headers = config.headers;\n }\n /**\n * Checks a response to see whether it's cacheable or not, based on this\n * object's configuration.\n *\n * @param {Response} response The response whose cacheability is being\n * checked.\n * @return {boolean} `true` if the `Response` is cacheable, and `false`\n * otherwise.\n */\n isResponseCacheable(response) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(response, Response, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'isResponseCacheable',\n paramName: 'response',\n });\n }\n let cacheable = true;\n if (this._statuses) {\n cacheable = this._statuses.includes(response.status);\n }\n if (this._headers && cacheable) {\n cacheable = Object.keys(this._headers).some((headerName) => {\n return response.headers.get(headerName) === this._headers[headerName];\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!cacheable) {\n logger.groupCollapsed(`The request for ` +\n `'${getFriendlyURL(response.url)}' returned a response that does ` +\n `not meet the criteria for being cached.`);\n logger.groupCollapsed(`View cacheability criteria here.`);\n logger.log(`Cacheable statuses: ` +\n JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` +\n JSON.stringify(this._headers, null, 2));\n logger.groupEnd();\n const logFriendlyHeaders = {};\n response.headers.forEach((value, key) => {\n logFriendlyHeaders[key] = value;\n });\n logger.groupCollapsed(`View response status and headers here.`);\n logger.log(`Response status: ` + response.status);\n logger.log(`Response headers: ` +\n JSON.stringify(logFriendlyHeaders, null, 2));\n logger.groupEnd();\n logger.groupCollapsed(`View full response details here.`);\n logger.log(response.headers);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n }\n return cacheable;\n }\n}\nexport { CacheableResponse };\n","/*\n Copyright 2018 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*/\nimport { CacheableResponse } from './CacheableResponse.js';\nimport './_version.js';\n/**\n * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it\n * easier to add in cacheability checks to requests made via Workbox's built-in\n * strategies.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponsePlugin {\n /**\n * To construct a new CacheableResponsePlugin instance you must provide at\n * least one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config) {\n /**\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n * @private\n */\n this.cacheWillUpdate = async ({ response }) => {\n if (this._cacheableResponse.isResponseCacheable(response)) {\n return response;\n }\n return null;\n };\n this._cacheableResponse = new CacheableResponse(config);\n }\n}\nexport { CacheableResponsePlugin };\n"],"names":["self","_","e","CacheableResponse","constructor","config","_statuses","statuses","_headers","headers","isResponseCacheable","response","cacheable","this","includes","status","Object","keys","some","headerName","get","cacheWillUpdate","async","_cacheableResponse"],"mappings":"sFAEA,IACIA,KAAK,qCAAuCC,IAEhD,MAAOC,ICeP,MAAMC,EAeFC,YAAYC,EAAS,SA0BZC,EAAYD,EAAOE,cACnBC,EAAWH,EAAOI,QAW3BC,oBAAoBC,OASZC,GAAY,SACZC,KAAKP,IACLM,EAAYC,KAAKP,EAAUQ,SAASH,EAASI,SAE7CF,KAAKL,GAAYI,IACjBA,EAAYI,OAAOC,KAAKJ,KAAKL,GAAUU,KAAMC,GAClCR,EAASF,QAAQW,IAAID,KAAgBN,KAAKL,EAASW,KA8B3DP,0DCtGf,MAeIR,YAAYC,QAOHgB,gBAAkBC,QAASX,SAAAA,KACxBE,KAAKU,EAAmBb,oBAAoBC,GACrCA,EAEJ,WAENY,EAAqB,IAAIpB,EAAkBE"}
1
+ {"version":3,"file":"workbox-cacheable-response.prod.js","sources":["../_version.js","../CacheableResponse.js","../CacheableResponsePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n self['workbox:cacheable-response:5.1.1'] && _();\n}\ncatch (e) { }\n","/*\n Copyright 2018 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*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * This class allows you to set up rules determining what\n * status codes and/or headers need to be present in order for a\n * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n * to be considered cacheable.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponse {\n /**\n * To construct a new CacheableResponse instance you must provide at least\n * one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config = {}) {\n if (process.env.NODE_ENV !== 'production') {\n if (!(config.statuses || config.headers)) {\n throw new WorkboxError('statuses-or-headers-required', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n });\n }\n if (config.statuses) {\n assert.isArray(config.statuses, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.statuses',\n });\n }\n if (config.headers) {\n assert.isType(config.headers, 'object', {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'constructor',\n paramName: 'config.headers',\n });\n }\n }\n this._statuses = config.statuses;\n this._headers = config.headers;\n }\n /**\n * Checks a response to see whether it's cacheable or not, based on this\n * object's configuration.\n *\n * @param {Response} response The response whose cacheability is being\n * checked.\n * @return {boolean} `true` if the `Response` is cacheable, and `false`\n * otherwise.\n */\n isResponseCacheable(response) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isInstance(response, Response, {\n moduleName: 'workbox-cacheable-response',\n className: 'CacheableResponse',\n funcName: 'isResponseCacheable',\n paramName: 'response',\n });\n }\n let cacheable = true;\n if (this._statuses) {\n cacheable = this._statuses.includes(response.status);\n }\n if (this._headers && cacheable) {\n cacheable = Object.keys(this._headers).some((headerName) => {\n return response.headers.get(headerName) === this._headers[headerName];\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!cacheable) {\n logger.groupCollapsed(`The request for ` +\n `'${getFriendlyURL(response.url)}' returned a response that does ` +\n `not meet the criteria for being cached.`);\n logger.groupCollapsed(`View cacheability criteria here.`);\n logger.log(`Cacheable statuses: ` +\n JSON.stringify(this._statuses));\n logger.log(`Cacheable headers: ` +\n JSON.stringify(this._headers, null, 2));\n logger.groupEnd();\n const logFriendlyHeaders = {};\n response.headers.forEach((value, key) => {\n logFriendlyHeaders[key] = value;\n });\n logger.groupCollapsed(`View response status and headers here.`);\n logger.log(`Response status: ` + response.status);\n logger.log(`Response headers: ` +\n JSON.stringify(logFriendlyHeaders, null, 2));\n logger.groupEnd();\n logger.groupCollapsed(`View full response details here.`);\n logger.log(response.headers);\n logger.log(response);\n logger.groupEnd();\n logger.groupEnd();\n }\n }\n return cacheable;\n }\n}\nexport { CacheableResponse };\n","/*\n Copyright 2018 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*/\nimport { CacheableResponse } from './CacheableResponse.js';\nimport './_version.js';\n/**\n * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it\n * easier to add in cacheability checks to requests made via Workbox's built-in\n * strategies.\n *\n * @memberof module:workbox-cacheable-response\n */\nclass CacheableResponsePlugin {\n /**\n * To construct a new CacheableResponsePlugin instance you must provide at\n * least one of the `config` properties.\n *\n * If both `statuses` and `headers` are specified, then both conditions must\n * be met for the `Response` to be considered cacheable.\n *\n * @param {Object} config\n * @param {Array<number>} [config.statuses] One or more status codes that a\n * `Response` can have and be considered cacheable.\n * @param {Object<string,string>} [config.headers] A mapping of header names\n * and expected values that a `Response` can have and be considered cacheable.\n * If multiple headers are provided, only one needs to be present.\n */\n constructor(config) {\n /**\n * @param {Object} options\n * @param {Response} options.response\n * @return {Response|null}\n * @private\n */\n this.cacheWillUpdate = async ({ response }) => {\n if (this._cacheableResponse.isResponseCacheable(response)) {\n return response;\n }\n return null;\n };\n this._cacheableResponse = new CacheableResponse(config);\n }\n}\nexport { CacheableResponsePlugin };\n"],"names":["self","_","e","CacheableResponse","constructor","config","_statuses","statuses","_headers","headers","isResponseCacheable","response","cacheable","this","includes","status","Object","keys","some","headerName","get","cacheWillUpdate","async","_cacheableResponse"],"mappings":"sFAEA,IACIA,KAAK,qCAAuCC,IAEhD,MAAOC,ICeP,MAAMC,EAeFC,YAAYC,EAAS,SA0BZC,EAAYD,EAAOE,cACnBC,EAAWH,EAAOI,QAW3BC,oBAAoBC,OASZC,GAAY,SACZC,KAAKP,IACLM,EAAYC,KAAKP,EAAUQ,SAASH,EAASI,SAE7CF,KAAKL,GAAYI,IACjBA,EAAYI,OAAOC,KAAKJ,KAAKL,GAAUU,KAAMC,GAClCR,EAASF,QAAQW,IAAID,KAAgBN,KAAKL,EAASW,KA8B3DP,0DCtGf,MAeIR,YAAYC,QAOHgB,gBAAkBC,OAASX,SAAAA,KACxBE,KAAKU,EAAmBb,oBAAoBC,GACrCA,EAEJ,UAENY,EAAqB,IAAIpB,EAAkBE"}
@@ -1,1882 +1,1880 @@
1
- this.workbox = this.workbox || {};
2
- this.workbox.core = (function (exports) {
3
- 'use strict';
4
-
5
- try {
6
- self['workbox:core:5.0.0'] && _();
7
- } catch (e) {}
8
-
9
- /*
10
- Copyright 2019 Google LLC
11
- Use of this source code is governed by an MIT-style
12
- license that can be found in the LICENSE file or at
13
- https://opensource.org/licenses/MIT.
14
- */
15
- const logger = (() => {
16
- // Don't overwrite this value if it's already set.
17
- // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
18
- if (!('__WB_DISABLE_DEV_LOGS' in self)) {
19
- self.__WB_DISABLE_DEV_LOGS = false;
20
- }
21
-
22
- let inGroup = false;
23
- const methodToColorMap = {
24
- debug: `#7f8c8d`,
25
- log: `#2ecc71`,
26
- warn: `#f39c12`,
27
- error: `#c0392b`,
28
- groupCollapsed: `#3498db`,
29
- groupEnd: null
30
- };
31
-
32
- const print = function (method, args) {
33
- if (self.__WB_DISABLE_DEV_LOGS) {
34
- return;
35
- }
36
-
37
- if (method === 'groupCollapsed') {
38
- // Safari doesn't print all console.groupCollapsed() arguments:
39
- // https://bugs.webkit.org/show_bug.cgi?id=182754
40
- if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
41
- console[method](...args);
42
- return;
43
- }
44
- }
45
-
46
- const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed.
47
-
48
- const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
49
- console[method](...logPrefix, ...args);
50
-
51
- if (method === 'groupCollapsed') {
52
- inGroup = true;
53
- }
54
-
55
- if (method === 'groupEnd') {
56
- inGroup = false;
57
- }
58
- };
59
-
60
- const api = {};
61
- const loggerMethods = Object.keys(methodToColorMap);
62
-
63
- for (const key of loggerMethods) {
64
- const method = key;
65
-
66
- api[method] = (...args) => {
67
- print(method, args);
68
- };
69
- }
70
-
71
- return api;
72
- })();
73
-
74
- /*
75
- Copyright 2018 Google LLC
76
-
77
- Use of this source code is governed by an MIT-style
78
- license that can be found in the LICENSE file or at
79
- https://opensource.org/licenses/MIT.
80
- */
81
- const messages = {
82
- 'invalid-value': ({
83
- paramName,
84
- validValueDescription,
85
- value
86
- }) => {
87
- if (!paramName || !validValueDescription) {
88
- throw new Error(`Unexpected input to 'invalid-value' error.`);
89
- }
90
-
91
- return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
92
- },
93
- 'not-in-sw': ({
94
- moduleName
95
- }) => {
96
- if (!moduleName) {
97
- throw new Error(`Unexpected input to 'not-in-sw' error.`);
98
- }
99
-
100
- return `The '${moduleName}' must be used in a service worker.`;
101
- },
102
- 'not-an-array': ({
103
- moduleName,
104
- className,
105
- funcName,
106
- paramName
107
- }) => {
108
- if (!moduleName || !className || !funcName || !paramName) {
109
- throw new Error(`Unexpected input to 'not-an-array' error.`);
110
- }
111
-
112
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
113
- },
114
- 'incorrect-type': ({
115
- expectedType,
116
- paramName,
117
- moduleName,
118
- className,
119
- funcName
120
- }) => {
121
- if (!expectedType || !paramName || !moduleName || !funcName) {
122
- throw new Error(`Unexpected input to 'incorrect-type' error.`);
123
- }
124
-
125
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}` + `${funcName}()' must be of type ${expectedType}.`;
126
- },
127
- 'incorrect-class': ({
128
- expectedClass,
129
- paramName,
130
- moduleName,
131
- className,
132
- funcName,
133
- isReturnValueProblem
134
- }) => {
135
- if (!expectedClass || !moduleName || !funcName) {
136
- throw new Error(`Unexpected input to 'incorrect-class' error.`);
137
- }
138
-
139
- if (isReturnValueProblem) {
140
- return `The return value from ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`;
141
- }
142
-
143
- return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`;
144
- },
145
- 'missing-a-method': ({
146
- expectedMethod,
147
- paramName,
148
- moduleName,
149
- className,
150
- funcName
151
- }) => {
152
- if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
153
- throw new Error(`Unexpected input to 'missing-a-method' error.`);
154
- }
155
-
156
- return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
157
- },
158
- 'add-to-cache-list-unexpected-type': ({
159
- entry
160
- }) => {
161
- return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
162
- },
163
- 'add-to-cache-list-conflicting-entries': ({
164
- firstEntry,
165
- secondEntry
166
- }) => {
167
- if (!firstEntry || !secondEntry) {
168
- throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
169
- }
170
-
171
- return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry._entryId} but different revision details. Workbox is ` + `is unable to cache and version the asset correctly. Please remove one ` + `of the entries.`;
172
- },
173
- 'plugin-error-request-will-fetch': ({
174
- thrownError
175
- }) => {
176
- if (!thrownError) {
177
- throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
178
- }
179
-
180
- return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownError.message}'.`;
181
- },
182
- 'invalid-cache-name': ({
183
- cacheNameId,
184
- value
185
- }) => {
186
- if (!cacheNameId) {
187
- throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
188
- }
189
-
190
- return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
191
- },
192
- 'unregister-route-but-not-found-with-method': ({
193
- method
194
- }) => {
195
- if (!method) {
196
- throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
197
- }
198
-
199
- return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
200
- },
201
- 'unregister-route-route-not-registered': () => {
202
- return `The route you're trying to unregister was not previously ` + `registered.`;
203
- },
204
- 'queue-replay-failed': ({
205
- name
206
- }) => {
207
- return `Replaying the background sync queue '${name}' failed.`;
208
- },
209
- 'duplicate-queue-name': ({
210
- name
211
- }) => {
212
- return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
213
- },
214
- 'expired-test-without-max-age': ({
215
- methodName,
216
- paramName
217
- }) => {
218
- return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
219
- },
220
- 'unsupported-route-type': ({
221
- moduleName,
222
- className,
223
- funcName,
224
- paramName
225
- }) => {
226
- return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
227
- },
228
- 'not-array-of-class': ({
229
- value,
230
- expectedClass,
231
- moduleName,
232
- className,
233
- funcName,
234
- paramName
235
- }) => {
236
- return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
237
- },
238
- 'max-entries-or-age-required': ({
239
- moduleName,
240
- className,
241
- funcName
242
- }) => {
243
- return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
244
- },
245
- 'statuses-or-headers-required': ({
246
- moduleName,
247
- className,
248
- funcName
249
- }) => {
250
- return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
251
- },
252
- 'invalid-string': ({
253
- moduleName,
254
- funcName,
255
- paramName
256
- }) => {
257
- if (!paramName || !moduleName || !funcName) {
258
- throw new Error(`Unexpected input to 'invalid-string' error.`);
259
- }
260
-
261
- return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`;
262
- },
263
- 'channel-name-required': () => {
264
- return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
265
- },
266
- 'invalid-responses-are-same-args': () => {
267
- return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
268
- },
269
- 'expire-custom-caches-only': () => {
270
- return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
271
- },
272
- 'unit-must-be-bytes': ({
273
- normalizedRangeHeader
274
- }) => {
275
- if (!normalizedRangeHeader) {
276
- throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
277
- }
278
-
279
- return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
280
- },
281
- 'single-range-only': ({
282
- normalizedRangeHeader
283
- }) => {
284
- if (!normalizedRangeHeader) {
285
- throw new Error(`Unexpected input to 'single-range-only' error.`);
286
- }
287
-
288
- return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
289
- },
290
- 'invalid-range-values': ({
291
- normalizedRangeHeader
292
- }) => {
293
- if (!normalizedRangeHeader) {
294
- throw new Error(`Unexpected input to 'invalid-range-values' error.`);
295
- }
296
-
297
- return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
298
- },
299
- 'no-range-header': () => {
300
- return `No Range header was found in the Request provided.`;
301
- },
302
- 'range-not-satisfiable': ({
303
- size,
304
- start,
305
- end
306
- }) => {
307
- return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
308
- },
309
- 'attempt-to-cache-non-get-request': ({
310
- url,
311
- method
312
- }) => {
313
- return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
314
- },
315
- 'cache-put-with-no-response': ({
316
- url
317
- }) => {
318
- return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
319
- },
320
- 'no-response': ({
321
- url,
322
- error
323
- }) => {
324
- let message = `The strategy could not generate a response for '${url}'.`;
325
-
326
- if (error) {
327
- message += ` The underlying error is ${error}.`;
328
- }
329
-
330
- return message;
331
- },
332
- 'bad-precaching-response': ({
333
- url,
334
- status
335
- }) => {
336
- return `The precaching request for '${url}' failed with an HTTP ` + `status of ${status}.`;
337
- },
338
- 'non-precached-url': ({
339
- url
340
- }) => {
341
- return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
342
- },
343
- 'add-to-cache-list-conflicting-integrities': ({
344
- url
345
- }) => {
346
- return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
347
- },
348
- 'missing-precache-entry': ({
349
- cacheName,
350
- url
351
- }) => {
352
- return `Unable to find a precached response in ${cacheName} for ${url}.`;
353
- }
354
- };
355
-
356
- /*
357
- Copyright 2018 Google LLC
358
-
359
- Use of this source code is governed by an MIT-style
360
- license that can be found in the LICENSE file or at
361
- https://opensource.org/licenses/MIT.
362
- */
363
-
364
- const generatorFunction = (code, details = {}) => {
365
- const message = messages[code];
366
-
367
- if (!message) {
368
- throw new Error(`Unable to find message for code '${code}'.`);
369
- }
370
-
371
- return message(details);
372
- };
373
-
374
- const messageGenerator = generatorFunction;
375
-
376
- /*
377
- Copyright 2018 Google LLC
378
-
379
- Use of this source code is governed by an MIT-style
380
- license that can be found in the LICENSE file or at
381
- https://opensource.org/licenses/MIT.
382
- */
383
- /**
384
- * Workbox errors should be thrown with this class.
385
- * This allows use to ensure the type easily in tests,
386
- * helps developers identify errors from workbox
387
- * easily and allows use to optimise error
388
- * messages correctly.
389
- *
390
- * @private
391
- */
392
-
393
- class WorkboxError extends Error {
394
- /**
395
- *
396
- * @param {string} errorCode The error code that
397
- * identifies this particular error.
398
- * @param {Object=} details Any relevant arguments
399
- * that will help developers identify issues should
400
- * be added as a key on the context object.
401
- */
402
- constructor(errorCode, details) {
403
- let message = messageGenerator(errorCode, details);
404
- super(message);
405
- this.name = errorCode;
406
- this.details = details;
407
- }
408
-
409
- }
410
-
411
- /*
412
- Copyright 2018 Google LLC
413
-
414
- Use of this source code is governed by an MIT-style
415
- license that can be found in the LICENSE file or at
416
- https://opensource.org/licenses/MIT.
417
- */
418
- /*
419
- * This method returns true if the current context is a service worker.
420
- */
421
-
422
- const isSWEnv = moduleName => {
423
- if (!('ServiceWorkerGlobalScope' in self)) {
424
- throw new WorkboxError('not-in-sw', {
425
- moduleName
426
- });
427
- }
428
- };
429
- /*
430
- * This method throws if the supplied value is not an array.
431
- * The destructed values are required to produce a meaningful error for users.
432
- * The destructed and restructured object is so it's clear what is
433
- * needed.
434
- */
435
-
436
-
437
- const isArray = (value, details) => {
438
- if (!Array.isArray(value)) {
439
- throw new WorkboxError('not-an-array', details);
440
- }
441
- };
442
-
443
- const hasMethod = (object, expectedMethod, details) => {
444
- const type = typeof object[expectedMethod];
445
-
446
- if (type !== 'function') {
447
- details['expectedMethod'] = expectedMethod;
448
- throw new WorkboxError('missing-a-method', details);
449
- }
450
- };
451
-
452
- const isType = (object, expectedType, details) => {
453
- if (typeof object !== expectedType) {
454
- details['expectedType'] = expectedType;
455
- throw new WorkboxError('incorrect-type', details);
456
- }
457
- };
458
-
459
- const isInstance = (object, expectedClass, details) => {
460
- if (!(object instanceof expectedClass)) {
461
- details['expectedClass'] = expectedClass;
462
- throw new WorkboxError('incorrect-class', details);
463
- }
464
- };
465
-
466
- const isOneOf = (value, validValues, details) => {
467
- if (!validValues.includes(value)) {
468
- details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
469
- throw new WorkboxError('invalid-value', details);
470
- }
471
- };
472
-
473
- const isArrayOfClass = (value, expectedClass, details) => {
474
- const error = new WorkboxError('not-array-of-class', details);
475
-
476
- if (!Array.isArray(value)) {
477
- throw error;
478
- }
479
-
480
- for (let item of value) {
481
- if (!(item instanceof expectedClass)) {
482
- throw error;
483
- }
484
- }
485
- };
486
-
487
- const finalAssertExports = {
488
- hasMethod,
489
- isArray,
490
- isInstance,
491
- isOneOf,
492
- isSWEnv,
493
- isType,
494
- isArrayOfClass
495
- };
496
-
497
- /*
498
- Copyright 2018 Google LLC
499
-
500
- Use of this source code is governed by an MIT-style
501
- license that can be found in the LICENSE file or at
502
- https://opensource.org/licenses/MIT.
503
- */
504
-
505
- const quotaErrorCallbacks = new Set();
506
-
507
- /*
508
- Copyright 2019 Google LLC
509
-
510
- Use of this source code is governed by an MIT-style
511
- license that can be found in the LICENSE file or at
512
- https://opensource.org/licenses/MIT.
513
- */
514
- /**
515
- * Adds a function to the set of quotaErrorCallbacks that will be executed if
516
- * there's a quota error.
517
- *
518
- * @param {Function} callback
519
- * @memberof module:workbox-core
520
- */
521
-
522
- function registerQuotaErrorCallback(callback) {
523
- {
524
- finalAssertExports.isType(callback, 'function', {
525
- moduleName: 'workbox-core',
526
- funcName: 'register',
527
- paramName: 'callback'
528
- });
529
- }
530
-
531
- quotaErrorCallbacks.add(callback);
532
-
533
- {
534
- logger.log('Registered a callback to respond to quota errors.', callback);
535
- }
536
- }
537
-
538
- /*
539
- Copyright 2018 Google LLC
540
-
541
- Use of this source code is governed by an MIT-style
542
- license that can be found in the LICENSE file or at
543
- https://opensource.org/licenses/MIT.
544
- */
545
- const _cacheNameDetails = {
546
- googleAnalytics: 'googleAnalytics',
547
- precache: 'precache-v2',
548
- prefix: 'workbox',
549
- runtime: 'runtime',
550
- suffix: typeof registration !== 'undefined' ? registration.scope : ''
551
- };
552
-
553
- const _createCacheName = cacheName => {
554
- return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
555
- };
556
-
557
- const eachCacheNameDetail = fn => {
558
- for (const key of Object.keys(_cacheNameDetails)) {
559
- fn(key);
560
- }
561
- };
562
-
563
- const cacheNames = {
564
- updateDetails: details => {
565
- eachCacheNameDetail(key => {
566
- if (typeof details[key] === 'string') {
567
- _cacheNameDetails[key] = details[key];
568
- }
569
- });
570
- },
571
- getGoogleAnalyticsName: userCacheName => {
572
- return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
573
- },
574
- getPrecacheName: userCacheName => {
575
- return userCacheName || _createCacheName(_cacheNameDetails.precache);
576
- },
577
- getPrefix: () => {
578
- return _cacheNameDetails.prefix;
579
- },
580
- getRuntimeName: userCacheName => {
581
- return userCacheName || _createCacheName(_cacheNameDetails.runtime);
582
- },
583
- getSuffix: () => {
584
- return _cacheNameDetails.suffix;
585
- }
586
- };
587
-
588
- /*
589
- Copyright 2018 Google LLC
590
-
591
- Use of this source code is governed by an MIT-style
592
- license that can be found in the LICENSE file or at
593
- https://opensource.org/licenses/MIT.
594
- */
595
- /**
596
- * Runs all of the callback functions, one at a time sequentially, in the order
597
- * in which they were registered.
598
- *
599
- * @memberof module:workbox-core
600
- * @private
601
- */
602
-
603
- async function executeQuotaErrorCallbacks() {
604
- {
605
- logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
606
- }
607
-
608
- for (const callback of quotaErrorCallbacks) {
609
- await callback();
610
-
611
- {
612
- logger.log(callback, 'is complete.');
613
- }
614
- }
615
-
616
- {
617
- logger.log('Finished running callbacks.');
618
- }
619
- }
620
-
621
- /*
622
- Copyright 2018 Google LLC
623
-
624
- Use of this source code is governed by an MIT-style
625
- license that can be found in the LICENSE file or at
626
- https://opensource.org/licenses/MIT.
627
- */
628
-
629
- const getFriendlyURL = url => {
630
- const urlObj = new URL(String(url), location.href);
631
-
632
- if (urlObj.origin === location.origin) {
633
- return urlObj.pathname;
634
- }
635
-
636
- return urlObj.href;
637
- };
638
-
639
- /*
640
- Copyright 2018 Google LLC
641
-
642
- Use of this source code is governed by an MIT-style
643
- license that can be found in the LICENSE file or at
644
- https://opensource.org/licenses/MIT.
645
- */
646
- const pluginUtils = {
647
- filter: (plugins, callbackName) => {
648
- return plugins.filter(plugin => callbackName in plugin);
649
- }
650
- };
651
-
652
- /*
653
- Copyright 2018 Google LLC
654
-
655
- Use of this source code is governed by an MIT-style
656
- license that can be found in the LICENSE file or at
657
- https://opensource.org/licenses/MIT.
658
- */
659
- /**
660
- * Wrapper around cache.put().
661
- *
662
- * Will call `cacheDidUpdate` on plugins if the cache was updated, using
663
- * `matchOptions` when determining what the old entry is.
664
- *
665
- * @param {Object} options
666
- * @param {string} options.cacheName
667
- * @param {Request} options.request
668
- * @param {Response} options.response
669
- * @param {Event} [options.event]
670
- * @param {Array<Object>} [options.plugins=[]]
671
- * @param {Object} [options.matchOptions]
672
- *
673
- * @private
674
- * @memberof module:workbox-core
675
- */
676
-
677
- const putWrapper = async ({
678
- cacheName,
679
- request,
680
- response,
681
- event,
682
- plugins = [],
683
- matchOptions
684
- }) => {
685
- {
686
- if (request.method && request.method !== 'GET') {
687
- throw new WorkboxError('attempt-to-cache-non-get-request', {
688
- url: getFriendlyURL(request.url),
689
- method: request.method
690
- });
691
- }
692
- }
693
-
694
- const effectiveRequest = await _getEffectiveRequest({
695
- plugins,
696
- request,
697
- mode: 'write'
698
- });
699
-
700
- if (!response) {
701
- {
702
- logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
703
- }
704
-
705
- throw new WorkboxError('cache-put-with-no-response', {
706
- url: getFriendlyURL(effectiveRequest.url)
707
- });
708
- }
709
-
710
- let responseToCache = await _isResponseSafeToCache({
711
- event,
712
- plugins,
713
- response,
714
- request: effectiveRequest
715
- });
716
-
717
- if (!responseToCache) {
718
- {
719
- logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will ` + `not be cached.`, responseToCache);
720
- }
721
-
722
- return;
723
- }
724
-
725
- const cache = await self.caches.open(cacheName);
726
- const updatePlugins = pluginUtils.filter(plugins, "cacheDidUpdate"
727
- /* CACHE_DID_UPDATE */
728
- );
729
- let oldResponse = updatePlugins.length > 0 ? await matchWrapper({
730
- cacheName,
731
- matchOptions,
732
- request: effectiveRequest
733
- }) : null;
734
-
735
- {
736
- logger.debug(`Updating the '${cacheName}' cache with a new Response for ` + `${getFriendlyURL(effectiveRequest.url)}.`);
737
- }
738
-
739
- try {
740
- await cache.put(effectiveRequest, responseToCache);
741
- } catch (error) {
742
- // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
743
- if (error.name === 'QuotaExceededError') {
744
- await executeQuotaErrorCallbacks();
745
- }
746
-
747
- throw error;
748
- }
749
-
750
- for (let plugin of updatePlugins) {
751
- await plugin["cacheDidUpdate"
752
- /* CACHE_DID_UPDATE */
753
- ].call(plugin, {
754
- cacheName,
755
- event,
756
- oldResponse,
757
- newResponse: responseToCache,
758
- request: effectiveRequest
759
- });
760
- }
761
- };
762
- /**
763
- * This is a wrapper around cache.match().
764
- *
765
- * @param {Object} options
766
- * @param {string} options.cacheName Name of the cache to match against.
767
- * @param {Request} options.request The Request that will be used to look up
768
- * cache entries.
769
- * @param {Event} [options.event] The event that prompted the action.
770
- * @param {Object} [options.matchOptions] Options passed to cache.match().
771
- * @param {Array<Object>} [options.plugins=[]] Array of plugins.
772
- * @return {Response} A cached response if available.
773
- *
774
- * @private
775
- * @memberof module:workbox-core
776
- */
777
-
778
-
779
- const matchWrapper = async ({
780
- cacheName,
781
- request,
782
- event,
783
- matchOptions,
784
- plugins = []
785
- }) => {
786
- const cache = await self.caches.open(cacheName);
787
- const effectiveRequest = await _getEffectiveRequest({
788
- plugins,
789
- request,
790
- mode: 'read'
791
- });
792
- let cachedResponse = await cache.match(effectiveRequest, matchOptions);
793
-
794
- {
795
- if (cachedResponse) {
796
- logger.debug(`Found a cached response in '${cacheName}'.`);
797
- } else {
798
- logger.debug(`No cached response found in '${cacheName}'.`);
799
- }
800
- }
801
-
802
- for (const plugin of plugins) {
803
- if ("cachedResponseWillBeUsed"
804
- /* CACHED_RESPONSE_WILL_BE_USED */
805
- in plugin) {
806
- const pluginMethod = plugin["cachedResponseWillBeUsed"
807
- /* CACHED_RESPONSE_WILL_BE_USED */
808
- ];
809
- cachedResponse = await pluginMethod.call(plugin, {
810
- cacheName,
811
- event,
812
- matchOptions,
813
- cachedResponse,
814
- request: effectiveRequest
815
- });
816
-
817
- {
818
- if (cachedResponse) {
819
- finalAssertExports.isInstance(cachedResponse, Response, {
820
- moduleName: 'Plugin',
821
- funcName: "cachedResponseWillBeUsed"
822
- /* CACHED_RESPONSE_WILL_BE_USED */
823
- ,
824
- isReturnValueProblem: true
825
- });
826
- }
827
- }
828
- }
829
- }
830
-
831
- return cachedResponse;
832
- };
833
- /**
834
- * This method will call cacheWillUpdate on the available plugins (or use
835
- * status === 200) to determine if the Response is safe and valid to cache.
836
- *
837
- * @param {Object} options
838
- * @param {Request} options.request
839
- * @param {Response} options.response
840
- * @param {Event} [options.event]
841
- * @param {Array<Object>} [options.plugins=[]]
842
- * @return {Promise<Response>}
843
- *
844
- * @private
845
- * @memberof module:workbox-core
846
- */
847
-
848
-
849
- const _isResponseSafeToCache = async ({
850
- request,
851
- response,
852
- event,
853
- plugins = []
854
- }) => {
855
- let responseToCache = response;
856
- let pluginsUsed = false;
857
-
858
- for (let plugin of plugins) {
859
- if ("cacheWillUpdate"
860
- /* CACHE_WILL_UPDATE */
861
- in plugin) {
862
- pluginsUsed = true;
863
- const pluginMethod = plugin["cacheWillUpdate"
864
- /* CACHE_WILL_UPDATE */
865
- ];
866
- responseToCache = await pluginMethod.call(plugin, {
867
- request,
868
- response: responseToCache,
869
- event
870
- });
871
-
872
- {
873
- if (responseToCache) {
874
- finalAssertExports.isInstance(responseToCache, Response, {
875
- moduleName: 'Plugin',
876
- funcName: "cacheWillUpdate"
877
- /* CACHE_WILL_UPDATE */
878
- ,
879
- isReturnValueProblem: true
880
- });
881
- }
882
- }
883
-
884
- if (!responseToCache) {
885
- break;
886
- }
887
- }
888
- }
889
-
890
- if (!pluginsUsed) {
891
- {
892
- if (responseToCache) {
893
- if (responseToCache.status !== 200) {
894
- if (responseToCache.status === 0) {
895
- logger.warn(`The response for '${request.url}' is an opaque ` + `response. The caching strategy that you're using will not ` + `cache opaque responses by default.`);
896
- } else {
897
- logger.debug(`The response for '${request.url}' returned ` + `a status code of '${response.status}' and won't be cached as a ` + `result.`);
898
- }
899
- }
900
- }
901
- }
902
-
903
- responseToCache = responseToCache && responseToCache.status === 200 ? responseToCache : undefined;
904
- }
905
-
906
- return responseToCache ? responseToCache : null;
907
- };
908
- /**
909
- * Checks the list of plugins for the cacheKeyWillBeUsed callback, and
910
- * executes any of those callbacks found in sequence. The final `Request` object
911
- * returned by the last plugin is treated as the cache key for cache reads
912
- * and/or writes.
913
- *
914
- * @param {Object} options
915
- * @param {Request} options.request
916
- * @param {string} options.mode
917
- * @param {Array<Object>} [options.plugins=[]]
918
- * @return {Promise<Request>}
919
- *
920
- * @private
921
- * @memberof module:workbox-core
922
- */
923
-
924
-
925
- const _getEffectiveRequest = async ({
926
- request,
927
- mode,
928
- plugins = []
929
- }) => {
930
- const cacheKeyWillBeUsedPlugins = pluginUtils.filter(plugins, "cacheKeyWillBeUsed"
931
- /* CACHE_KEY_WILL_BE_USED */
932
- );
933
- let effectiveRequest = request;
934
-
935
- for (const plugin of cacheKeyWillBeUsedPlugins) {
936
- effectiveRequest = await plugin["cacheKeyWillBeUsed"
937
- /* CACHE_KEY_WILL_BE_USED */
938
- ].call(plugin, {
939
- mode,
940
- request: effectiveRequest
941
- });
942
-
943
- if (typeof effectiveRequest === 'string') {
944
- effectiveRequest = new Request(effectiveRequest);
945
- }
946
-
947
- {
948
- finalAssertExports.isInstance(effectiveRequest, Request, {
949
- moduleName: 'Plugin',
950
- funcName: "cacheKeyWillBeUsed"
951
- /* CACHE_KEY_WILL_BE_USED */
952
- ,
953
- isReturnValueProblem: true
954
- });
955
- }
956
- }
957
-
958
- return effectiveRequest;
959
- };
960
-
961
- const cacheWrapper = {
962
- put: putWrapper,
963
- match: matchWrapper
964
- };
965
-
966
- /*
967
- Copyright 2019 Google LLC
968
-
969
- Use of this source code is governed by an MIT-style
970
- license that can be found in the LICENSE file or at
971
- https://opensource.org/licenses/MIT.
972
- */
973
- let supportStatus;
974
- /**
975
- * A utility function that determines whether the current browser supports
976
- * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
977
- * object.
978
- *
979
- * @return {boolean} `true`, if the current browser can successfully
980
- * construct a `ReadableStream`, `false` otherwise.
981
- *
982
- * @private
983
- */
984
-
985
- function canConstructReadableStream() {
986
- if (supportStatus === undefined) {
987
- // See https://github.com/GoogleChrome/workbox/issues/1473
988
- try {
989
- new ReadableStream({
990
- start() {}
991
-
992
- });
993
- supportStatus = true;
994
- } catch (error) {
995
- supportStatus = false;
996
- }
997
- }
998
-
999
- return supportStatus;
1000
- }
1001
-
1002
- /*
1003
- Copyright 2019 Google LLC
1004
-
1005
- Use of this source code is governed by an MIT-style
1006
- license that can be found in the LICENSE file or at
1007
- https://opensource.org/licenses/MIT.
1008
- */
1009
- let supportStatus$1;
1010
- /**
1011
- * A utility function that determines whether the current browser supports
1012
- * constructing a new `Response` from a `response.body` stream.
1013
- *
1014
- * @return {boolean} `true`, if the current browser can successfully
1015
- * construct a `Response` from a `response.body` stream, `false` otherwise.
1016
- *
1017
- * @private
1018
- */
1019
-
1020
- function canConstructResponseFromBodyStream() {
1021
- if (supportStatus$1 === undefined) {
1022
- const testResponse = new Response('');
1023
-
1024
- if ('body' in testResponse) {
1025
- try {
1026
- new Response(testResponse.body);
1027
- supportStatus$1 = true;
1028
- } catch (error) {
1029
- supportStatus$1 = false;
1030
- }
1031
- }
1032
-
1033
- supportStatus$1 = false;
1034
- }
1035
-
1036
- return supportStatus$1;
1037
- }
1038
-
1039
- /*
1040
- Copyright 2019 Google LLC
1041
- Use of this source code is governed by an MIT-style
1042
- license that can be found in the LICENSE file or at
1043
- https://opensource.org/licenses/MIT.
1044
- */
1045
- /**
1046
- * A helper function that prevents a promise from being flagged as unused.
1047
- *
1048
- * @private
1049
- **/
1050
-
1051
- function dontWaitFor(promise) {
1052
- // Effective no-op.
1053
- promise.then(() => {});
1054
- }
1055
-
1056
- /*
1057
- Copyright 2018 Google LLC
1058
-
1059
- Use of this source code is governed by an MIT-style
1060
- license that can be found in the LICENSE file or at
1061
- https://opensource.org/licenses/MIT.
1062
- */
1063
- /**
1064
- * A class that wraps common IndexedDB functionality in a promise-based API.
1065
- * It exposes all the underlying power and functionality of IndexedDB, but
1066
- * wraps the most commonly used features in a way that's much simpler to use.
1067
- *
1068
- * @private
1069
- */
1070
-
1071
- class DBWrapper {
1072
- /**
1073
- * @param {string} name
1074
- * @param {number} version
1075
- * @param {Object=} [callback]
1076
- * @param {!Function} [callbacks.onupgradeneeded]
1077
- * @param {!Function} [callbacks.onversionchange] Defaults to
1078
- * DBWrapper.prototype._onversionchange when not specified.
1079
- * @private
1080
- */
1081
- constructor(name, version, {
1082
- onupgradeneeded,
1083
- onversionchange
1084
- } = {}) {
1085
- this._db = null;
1086
- this._name = name;
1087
- this._version = version;
1088
- this._onupgradeneeded = onupgradeneeded;
1089
-
1090
- this._onversionchange = onversionchange || (() => this.close());
1091
- }
1092
- /**
1093
- * Returns the IDBDatabase instance (not normally needed).
1094
- * @return {IDBDatabase|undefined}
1095
- *
1096
- * @private
1097
- */
1098
-
1099
-
1100
- get db() {
1101
- return this._db;
1102
- }
1103
- /**
1104
- * Opens a connected to an IDBDatabase, invokes any onupgradedneeded
1105
- * callback, and added an onversionchange callback to the database.
1106
- *
1107
- * @return {IDBDatabase}
1108
- * @private
1109
- */
1110
-
1111
-
1112
- async open() {
1113
- if (this._db) return;
1114
- this._db = await new Promise((resolve, reject) => {
1115
- // This flag is flipped to true if the timeout callback runs prior
1116
- // to the request failing or succeeding. Note: we use a timeout instead
1117
- // of an onblocked handler since there are cases where onblocked will
1118
- // never never run. A timeout better handles all possible scenarios:
1119
- // https://github.com/w3c/IndexedDB/issues/223
1120
- let openRequestTimedOut = false;
1121
- setTimeout(() => {
1122
- openRequestTimedOut = true;
1123
- reject(new Error('The open request was blocked and timed out'));
1124
- }, this.OPEN_TIMEOUT);
1125
- const openRequest = indexedDB.open(this._name, this._version);
1126
-
1127
- openRequest.onerror = () => reject(openRequest.error);
1128
-
1129
- openRequest.onupgradeneeded = evt => {
1130
- if (openRequestTimedOut) {
1131
- openRequest.transaction.abort();
1132
- openRequest.result.close();
1133
- } else if (typeof this._onupgradeneeded === 'function') {
1134
- this._onupgradeneeded(evt);
1135
- }
1136
- };
1137
-
1138
- openRequest.onsuccess = () => {
1139
- const db = openRequest.result;
1140
-
1141
- if (openRequestTimedOut) {
1142
- db.close();
1143
- } else {
1144
- db.onversionchange = this._onversionchange.bind(this);
1145
- resolve(db);
1146
- }
1147
- };
1148
- });
1149
- return this;
1150
- }
1151
- /**
1152
- * Polyfills the native `getKey()` method. Note, this is overridden at
1153
- * runtime if the browser supports the native method.
1154
- *
1155
- * @param {string} storeName
1156
- * @param {*} query
1157
- * @return {Array}
1158
- * @private
1159
- */
1160
-
1161
-
1162
- async getKey(storeName, query) {
1163
- return (await this.getAllKeys(storeName, query, 1))[0];
1164
- }
1165
- /**
1166
- * Polyfills the native `getAll()` method. Note, this is overridden at
1167
- * runtime if the browser supports the native method.
1168
- *
1169
- * @param {string} storeName
1170
- * @param {*} query
1171
- * @param {number} count
1172
- * @return {Array}
1173
- * @private
1174
- */
1175
-
1176
-
1177
- async getAll(storeName, query, count) {
1178
- return await this.getAllMatching(storeName, {
1179
- query,
1180
- count
1181
- });
1182
- }
1183
- /**
1184
- * Polyfills the native `getAllKeys()` method. Note, this is overridden at
1185
- * runtime if the browser supports the native method.
1186
- *
1187
- * @param {string} storeName
1188
- * @param {*} query
1189
- * @param {number} count
1190
- * @return {Array}
1191
- * @private
1192
- */
1193
-
1194
-
1195
- async getAllKeys(storeName, query, count) {
1196
- const entries = await this.getAllMatching(storeName, {
1197
- query,
1198
- count,
1199
- includeKeys: true
1200
- });
1201
- return entries.map(entry => entry.key);
1202
- }
1203
- /**
1204
- * Supports flexible lookup in an object store by specifying an index,
1205
- * query, direction, and count. This method returns an array of objects
1206
- * with the signature .
1207
- *
1208
- * @param {string} storeName
1209
- * @param {Object} [opts]
1210
- * @param {string} [opts.index] The index to use (if specified).
1211
- * @param {*} [opts.query]
1212
- * @param {IDBCursorDirection} [opts.direction]
1213
- * @param {number} [opts.count] The max number of results to return.
1214
- * @param {boolean} [opts.includeKeys] When true, the structure of the
1215
- * returned objects is changed from an array of values to an array of
1216
- * objects in the form {key, primaryKey, value}.
1217
- * @return {Array}
1218
- * @private
1219
- */
1220
-
1221
-
1222
- async getAllMatching(storeName, {
1223
- index,
1224
- query = null,
1225
- // IE/Edge errors if query === `undefined`.
1226
- direction = 'next',
1227
- count,
1228
- includeKeys = false
1229
- } = {}) {
1230
- return await this.transaction([storeName], 'readonly', (txn, done) => {
1231
- const store = txn.objectStore(storeName);
1232
- const target = index ? store.index(index) : store;
1233
- const results = [];
1234
- const request = target.openCursor(query, direction);
1235
-
1236
- request.onsuccess = () => {
1237
- const cursor = request.result;
1238
-
1239
- if (cursor) {
1240
- results.push(includeKeys ? cursor : cursor.value);
1241
-
1242
- if (count && results.length >= count) {
1243
- done(results);
1244
- } else {
1245
- cursor.continue();
1246
- }
1247
- } else {
1248
- done(results);
1249
- }
1250
- };
1251
- });
1252
- }
1253
- /**
1254
- * Accepts a list of stores, a transaction type, and a callback and
1255
- * performs a transaction. A promise is returned that resolves to whatever
1256
- * value the callback chooses. The callback holds all the transaction logic
1257
- * and is invoked with two arguments:
1258
- * 1. The IDBTransaction object
1259
- * 2. A `done` function, that's used to resolve the promise when
1260
- * when the transaction is done, if passed a value, the promise is
1261
- * resolved to that value.
1262
- *
1263
- * @param {Array<string>} storeNames An array of object store names
1264
- * involved in the transaction.
1265
- * @param {string} type Can be `readonly` or `readwrite`.
1266
- * @param {!Function} callback
1267
- * @return {*} The result of the transaction ran by the callback.
1268
- * @private
1269
- */
1270
-
1271
-
1272
- async transaction(storeNames, type, callback) {
1273
- await this.open();
1274
- return await new Promise((resolve, reject) => {
1275
- const txn = this._db.transaction(storeNames, type);
1276
-
1277
- txn.onabort = () => reject(txn.error);
1278
-
1279
- txn.oncomplete = () => resolve();
1280
-
1281
- callback(txn, value => resolve(value));
1282
- });
1283
- }
1284
- /**
1285
- * Delegates async to a native IDBObjectStore method.
1286
- *
1287
- * @param {string} method The method name.
1288
- * @param {string} storeName The object store name.
1289
- * @param {string} type Can be `readonly` or `readwrite`.
1290
- * @param {...*} args The list of args to pass to the native method.
1291
- * @return {*} The result of the transaction.
1292
- * @private
1293
- */
1294
-
1295
-
1296
- async _call(method, storeName, type, ...args) {
1297
- const callback = (txn, done) => {
1298
- const objStore = txn.objectStore(storeName); // TODO(philipwalton): Fix this underlying TS2684 error.
1299
- // @ts-ignore
1300
-
1301
- const request = objStore[method].apply(objStore, args);
1302
-
1303
- request.onsuccess = () => done(request.result);
1304
- };
1305
-
1306
- return await this.transaction([storeName], type, callback);
1307
- }
1308
- /**
1309
- * Closes the connection opened by `DBWrapper.open()`. Generally this method
1310
- * doesn't need to be called since:
1311
- * 1. It's usually better to keep a connection open since opening
1312
- * a new connection is somewhat slow.
1313
- * 2. Connections are automatically closed when the reference is
1314
- * garbage collected.
1315
- * The primary use case for needing to close a connection is when another
1316
- * reference (typically in another tab) needs to upgrade it and would be
1317
- * blocked by the current, open connection.
1318
- *
1319
- * @private
1320
- */
1321
-
1322
-
1323
- close() {
1324
- if (this._db) {
1325
- this._db.close();
1326
-
1327
- this._db = null;
1328
- }
1329
- }
1330
-
1331
- } // Exposed on the prototype to let users modify the default timeout on a
1332
- // per-instance or global basis.
1333
-
1334
- DBWrapper.prototype.OPEN_TIMEOUT = 2000; // Wrap native IDBObjectStore methods according to their mode.
1335
-
1336
- const methodsToWrap = {
1337
- readonly: ['get', 'count', 'getKey', 'getAll', 'getAllKeys'],
1338
- readwrite: ['add', 'put', 'clear', 'delete']
1339
- };
1340
-
1341
- for (const [mode, methods] of Object.entries(methodsToWrap)) {
1342
- for (const method of methods) {
1343
- if (method in IDBObjectStore.prototype) {
1344
- // Don't use arrow functions here since we're outside of the class.
1345
- DBWrapper.prototype[method] = async function (storeName, ...args) {
1346
- return await this._call(method, storeName, mode, ...args);
1347
- };
1348
- }
1349
- }
1350
- }
1351
-
1352
- /*
1353
- Copyright 2018 Google LLC
1354
-
1355
- Use of this source code is governed by an MIT-style
1356
- license that can be found in the LICENSE file or at
1357
- https://opensource.org/licenses/MIT.
1358
- */
1359
- /**
1360
- * The Deferred class composes Promises in a way that allows for them to be
1361
- * resolved or rejected from outside the constructor. In most cases promises
1362
- * should be used directly, but Deferreds can be necessary when the logic to
1363
- * resolve a promise must be separate.
1364
- *
1365
- * @private
1366
- */
1367
-
1368
- class Deferred {
1369
- /**
1370
- * Creates a promise and exposes its resolve and reject functions as methods.
1371
- */
1372
- constructor() {
1373
- this.promise = new Promise((resolve, reject) => {
1374
- this.resolve = resolve;
1375
- this.reject = reject;
1376
- });
1377
- }
1378
-
1379
- }
1380
-
1381
- /*
1382
- Copyright 2018 Google LLC
1383
-
1384
- Use of this source code is governed by an MIT-style
1385
- license that can be found in the LICENSE file or at
1386
- https://opensource.org/licenses/MIT.
1387
- */
1388
- /**
1389
- * Deletes the database.
1390
- * Note: this is exported separately from the DBWrapper module because most
1391
- * usages of IndexedDB in workbox dont need deleting, and this way it can be
1392
- * reused in tests to delete databases without creating DBWrapper instances.
1393
- *
1394
- * @param {string} name The database name.
1395
- * @private
1396
- */
1397
-
1398
- const deleteDatabase = async name => {
1399
- await new Promise((resolve, reject) => {
1400
- const request = indexedDB.deleteDatabase(name);
1401
-
1402
- request.onerror = () => {
1403
- reject(request.error);
1404
- };
1405
-
1406
- request.onblocked = () => {
1407
- reject(new Error('Delete blocked'));
1408
- };
1409
-
1410
- request.onsuccess = () => {
1411
- resolve();
1412
- };
1413
- });
1414
- };
1415
-
1416
- /*
1417
- Copyright 2018 Google LLC
1418
-
1419
- Use of this source code is governed by an MIT-style
1420
- license that can be found in the LICENSE file or at
1421
- https://opensource.org/licenses/MIT.
1422
- */
1423
- /**
1424
- * Wrapper around the fetch API.
1425
- *
1426
- * Will call requestWillFetch on available plugins.
1427
- *
1428
- * @param {Object} options
1429
- * @param {Request|string} options.request
1430
- * @param {Object} [options.fetchOptions]
1431
- * @param {ExtendableEvent} [options.event]
1432
- * @param {Array<Object>} [options.plugins=[]]
1433
- * @return {Promise<Response>}
1434
- *
1435
- * @private
1436
- * @memberof module:workbox-core
1437
- */
1438
-
1439
- const wrappedFetch = async ({
1440
- request,
1441
- fetchOptions,
1442
- event,
1443
- plugins = []
1444
- }) => {
1445
- if (typeof request === 'string') {
1446
- request = new Request(request);
1447
- } // We *should* be able to call `await event.preloadResponse` even if it's
1448
- // undefined, but for some reason, doing so leads to errors in our Node unit
1449
- // tests. To work around that, explicitly check preloadResponse's value first.
1450
-
1451
-
1452
- if (event instanceof FetchEvent && event.preloadResponse) {
1453
- const possiblePreloadResponse = await event.preloadResponse;
1454
-
1455
- if (possiblePreloadResponse) {
1456
- {
1457
- logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
1458
- }
1459
-
1460
- return possiblePreloadResponse;
1461
- }
1462
- }
1463
-
1464
- {
1465
- finalAssertExports.isInstance(request, Request, {
1466
- paramName: 'request',
1467
- expectedClass: Request,
1468
- moduleName: 'workbox-core',
1469
- className: 'fetchWrapper',
1470
- funcName: 'wrappedFetch'
1471
- });
1472
- }
1473
-
1474
- const failedFetchPlugins = pluginUtils.filter(plugins, "fetchDidFail"
1475
- /* FETCH_DID_FAIL */
1476
- ); // If there is a fetchDidFail plugin, we need to save a clone of the
1477
- // original request before it's either modified by a requestWillFetch
1478
- // plugin or before the original request's body is consumed via fetch().
1479
-
1480
- const originalRequest = failedFetchPlugins.length > 0 ? request.clone() : null;
1481
-
1482
- try {
1483
- for (let plugin of plugins) {
1484
- if ("requestWillFetch"
1485
- /* REQUEST_WILL_FETCH */
1486
- in plugin) {
1487
- const pluginMethod = plugin["requestWillFetch"
1488
- /* REQUEST_WILL_FETCH */
1489
- ];
1490
- const requestClone = request.clone();
1491
- request = await pluginMethod.call(plugin, {
1492
- request: requestClone,
1493
- event
1494
- });
1495
-
1496
- if ("dev" !== 'production') {
1497
- if (request) {
1498
- finalAssertExports.isInstance(request, Request, {
1499
- moduleName: 'Plugin',
1500
- funcName: "cachedResponseWillBeUsed"
1501
- /* CACHED_RESPONSE_WILL_BE_USED */
1502
- ,
1503
- isReturnValueProblem: true
1504
- });
1505
- }
1506
- }
1507
- }
1508
- }
1509
- } catch (err) {
1510
- throw new WorkboxError('plugin-error-request-will-fetch', {
1511
- thrownError: err
1512
- });
1513
- } // The request can be altered by plugins with `requestWillFetch` making
1514
- // the original request (Most likely from a `fetch` event) to be different
1515
- // to the Request we make. Pass both to `fetchDidFail` to aid debugging.
1516
-
1517
-
1518
- let pluginFilteredRequest = request.clone();
1519
-
1520
- try {
1521
- let fetchResponse; // See https://github.com/GoogleChrome/workbox/issues/1796
1522
-
1523
- if (request.mode === 'navigate') {
1524
- fetchResponse = await fetch(request);
1525
- } else {
1526
- fetchResponse = await fetch(request, fetchOptions);
1527
- }
1528
-
1529
- if ("dev" !== 'production') {
1530
- logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
1531
- }
1532
-
1533
- for (const plugin of plugins) {
1534
- if ("fetchDidSucceed"
1535
- /* FETCH_DID_SUCCEED */
1536
- in plugin) {
1537
- fetchResponse = await plugin["fetchDidSucceed"
1538
- /* FETCH_DID_SUCCEED */
1539
- ].call(plugin, {
1540
- event,
1541
- request: pluginFilteredRequest,
1542
- response: fetchResponse
1543
- });
1544
-
1545
- if ("dev" !== 'production') {
1546
- if (fetchResponse) {
1547
- finalAssertExports.isInstance(fetchResponse, Response, {
1548
- moduleName: 'Plugin',
1549
- funcName: "fetchDidSucceed"
1550
- /* FETCH_DID_SUCCEED */
1551
- ,
1552
- isReturnValueProblem: true
1553
- });
1554
- }
1555
- }
1556
- }
1557
- }
1558
-
1559
- return fetchResponse;
1560
- } catch (error) {
1561
- {
1562
- logger.error(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
1563
- }
1564
-
1565
- for (const plugin of failedFetchPlugins) {
1566
- await plugin["fetchDidFail"
1567
- /* FETCH_DID_FAIL */
1568
- ].call(plugin, {
1569
- error,
1570
- event,
1571
- originalRequest: originalRequest.clone(),
1572
- request: pluginFilteredRequest.clone()
1573
- });
1574
- }
1575
-
1576
- throw error;
1577
- }
1578
- };
1579
-
1580
- const fetchWrapper = {
1581
- fetch: wrappedFetch
1582
- };
1583
-
1584
- /*
1585
- Copyright 2019 Google LLC
1586
- Use of this source code is governed by an MIT-style
1587
- license that can be found in the LICENSE file or at
1588
- https://opensource.org/licenses/MIT.
1589
- */
1590
- /**
1591
- * Returns a promise that resolves and the passed number of milliseconds.
1592
- * This utility is an async/await-friendly version of `setTimeout`.
1593
- *
1594
- * @param {number} ms
1595
- * @return {Promise}
1596
- * @private
1597
- */
1598
-
1599
- function timeout(ms) {
1600
- return new Promise(resolve => setTimeout(resolve, ms));
1601
- }
1602
-
1603
- /*
1604
- Copyright 2019 Google LLC
1605
- Use of this source code is governed by an MIT-style
1606
- license that can be found in the LICENSE file or at
1607
- https://opensource.org/licenses/MIT.
1608
- */
1609
- const MAX_RETRY_TIME = 2000;
1610
- /**
1611
- * Returns a promise that resolves to a window client matching the passed
1612
- * `resultingClientId`. For browsers that don't support `resultingClientId`
1613
- * or if waiting for the resulting client to apper takes too long, resolve to
1614
- * `undefined`.
1615
- *
1616
- * @param {string} [resultingClientId]
1617
- * @return {Promise<Client|undefined>}
1618
- * @private
1619
- */
1620
-
1621
- async function resultingClientExists(resultingClientId) {
1622
- if (!resultingClientId) {
1623
- return;
1624
- }
1625
-
1626
- let existingWindows = await self.clients.matchAll({
1627
- type: 'window'
1628
- });
1629
- const existingWindowIds = new Set(existingWindows.map(w => w.id));
1630
- let resultingWindow;
1631
- const startTime = performance.now(); // Only wait up to `MAX_RETRY_TIME` to find a matching client.
1632
-
1633
- while (performance.now() - startTime < MAX_RETRY_TIME) {
1634
- existingWindows = await self.clients.matchAll({
1635
- type: 'window'
1636
- });
1637
- resultingWindow = existingWindows.find(w => {
1638
- if (resultingClientId) {
1639
- // If we have a `resultingClientId`, we can match on that.
1640
- return w.id === resultingClientId;
1641
- } else {
1642
- // Otherwise match on finding a window not in `existingWindowIds`.
1643
- return !existingWindowIds.has(w.id);
1644
- }
1645
- });
1646
-
1647
- if (resultingWindow) {
1648
- break;
1649
- } // Sleep for 100ms and retry.
1650
-
1651
-
1652
- await timeout(100);
1653
- }
1654
-
1655
- return resultingWindow;
1656
- }
1657
-
1658
- /*
1659
- Copyright 2018 Google LLC
1660
-
1661
- Use of this source code is governed by an MIT-style
1662
- license that can be found in the LICENSE file or at
1663
- https://opensource.org/licenses/MIT.
1664
- */
1665
-
1666
- var _private = /*#__PURE__*/Object.freeze({
1667
- assert: finalAssertExports,
1668
- cacheNames: cacheNames,
1669
- cacheWrapper: cacheWrapper,
1670
- canConstructReadableStream: canConstructReadableStream,
1671
- canConstructResponseFromBodyStream: canConstructResponseFromBodyStream,
1672
- dontWaitFor: dontWaitFor,
1673
- DBWrapper: DBWrapper,
1674
- Deferred: Deferred,
1675
- deleteDatabase: deleteDatabase,
1676
- executeQuotaErrorCallbacks: executeQuotaErrorCallbacks,
1677
- fetchWrapper: fetchWrapper,
1678
- getFriendlyURL: getFriendlyURL,
1679
- logger: logger,
1680
- resultingClientExists: resultingClientExists,
1681
- timeout: timeout,
1682
- WorkboxError: WorkboxError
1683
- });
1684
-
1685
- /*
1686
- Copyright 2019 Google LLC
1687
-
1688
- Use of this source code is governed by an MIT-style
1689
- license that can be found in the LICENSE file or at
1690
- https://opensource.org/licenses/MIT.
1691
- */
1692
- /**
1693
- * Get the current cache names and prefix/suffix used by Workbox.
1694
- *
1695
- * `cacheNames.precache` is used for precached assets,
1696
- * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to
1697
- * store `analytics.js`, and `cacheNames.runtime` is used for everything else.
1698
- *
1699
- * `cacheNames.prefix` can be used to retrieve just the current prefix value.
1700
- * `cacheNames.suffix` can be used to retrieve just the current suffix value.
1701
- *
1702
- * @return {Object} An object with `precache`, `runtime`, `prefix`, and
1703
- * `googleAnalytics` properties.
1704
- *
1705
- * @memberof module:workbox-core
1706
- */
1707
-
1708
- const cacheNames$1 = {
1709
- get googleAnalytics() {
1710
- return cacheNames.getGoogleAnalyticsName();
1711
- },
1712
-
1713
- get precache() {
1714
- return cacheNames.getPrecacheName();
1715
- },
1716
-
1717
- get prefix() {
1718
- return cacheNames.getPrefix();
1719
- },
1720
-
1721
- get runtime() {
1722
- return cacheNames.getRuntimeName();
1723
- },
1724
-
1725
- get suffix() {
1726
- return cacheNames.getSuffix();
1727
- }
1728
-
1729
- };
1730
-
1731
- /*
1732
- Copyright 2019 Google LLC
1733
-
1734
- Use of this source code is governed by an MIT-style
1735
- license that can be found in the LICENSE file or at
1736
- https://opensource.org/licenses/MIT.
1737
- */
1738
- /**
1739
- * Allows developers to copy a response and modify its `headers`, `status`,
1740
- * or `statusText` values (the values settable via a
1741
- * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
1742
- * object in the constructor).
1743
- * To modify these values, pass a function as the second argument. That
1744
- * function will be invoked with a single object with the response properties
1745
- * `{headers, status, statusText}`. The return value of this function will
1746
- * be used as the `ResponseInit` for the new `Response`. To change the values
1747
- * either modify the passed parameter(s) and return it, or return a totally
1748
- * new object.
1749
- *
1750
- * @param {Response} response
1751
- * @param {Function} modifier
1752
- * @memberof module:workbox-core
1753
- */
1754
-
1755
- async function copyResponse(response, modifier) {
1756
- const clonedResponse = response.clone(); // Create a fresh `ResponseInit` object by cloning the headers.
1757
-
1758
- const responseInit = {
1759
- headers: new Headers(clonedResponse.headers),
1760
- status: clonedResponse.status,
1761
- statusText: clonedResponse.statusText
1762
- }; // Apply any user modifications.
1763
-
1764
- const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; // Create the new response from the body stream and `ResponseInit`
1765
- // modifications. Note: not all browsers support the Response.body stream,
1766
- // so fall back to reading the entire body into memory as a blob.
1767
-
1768
- const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
1769
- return new Response(body, modifiedResponseInit);
1770
- }
1771
-
1772
- /*
1773
- Copyright 2019 Google LLC
1774
-
1775
- Use of this source code is governed by an MIT-style
1776
- license that can be found in the LICENSE file or at
1777
- https://opensource.org/licenses/MIT.
1778
- */
1779
- /**
1780
- * Claim any currently available clients once the service worker
1781
- * becomes active. This is normally used in conjunction with `skipWaiting()`.
1782
- *
1783
- * @memberof module:workbox-core
1784
- */
1785
-
1786
- function clientsClaim() {
1787
- self.addEventListener('activate', () => self.clients.claim());
1788
- }
1789
-
1790
- /*
1791
- Copyright 2019 Google LLC
1792
-
1793
- Use of this source code is governed by an MIT-style
1794
- license that can be found in the LICENSE file or at
1795
- https://opensource.org/licenses/MIT.
1796
- */
1797
- /**
1798
- * Modifies the default cache names used by the Workbox packages.
1799
- * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
1800
- *
1801
- * @param {Object} details
1802
- * @param {Object} [details.prefix] The string to add to the beginning of
1803
- * the precache and runtime cache names.
1804
- * @param {Object} [details.suffix] The string to add to the end of
1805
- * the precache and runtime cache names.
1806
- * @param {Object} [details.precache] The cache name to use for precache
1807
- * caching.
1808
- * @param {Object} [details.runtime] The cache name to use for runtime caching.
1809
- * @param {Object} [details.googleAnalytics] The cache name to use for
1810
- * `workbox-google-analytics` caching.
1811
- *
1812
- * @memberof module:workbox-core
1813
- */
1814
-
1815
- function setCacheNameDetails(details) {
1816
- {
1817
- Object.keys(details).forEach(key => {
1818
- finalAssertExports.isType(details[key], 'string', {
1819
- moduleName: 'workbox-core',
1820
- funcName: 'setCacheNameDetails',
1821
- paramName: `details.${key}`
1822
- });
1823
- });
1824
-
1825
- if ('precache' in details && details['precache'].length === 0) {
1826
- throw new WorkboxError('invalid-cache-name', {
1827
- cacheNameId: 'precache',
1828
- value: details['precache']
1829
- });
1830
- }
1831
-
1832
- if ('runtime' in details && details['runtime'].length === 0) {
1833
- throw new WorkboxError('invalid-cache-name', {
1834
- cacheNameId: 'runtime',
1835
- value: details['runtime']
1836
- });
1837
- }
1838
-
1839
- if ('googleAnalytics' in details && details['googleAnalytics'].length === 0) {
1840
- throw new WorkboxError('invalid-cache-name', {
1841
- cacheNameId: 'googleAnalytics',
1842
- value: details['googleAnalytics']
1843
- });
1844
- }
1845
- }
1846
-
1847
- cacheNames.updateDetails(details);
1848
- }
1849
-
1850
- /*
1851
- Copyright 2019 Google LLC
1852
-
1853
- Use of this source code is governed by an MIT-style
1854
- license that can be found in the LICENSE file or at
1855
- https://opensource.org/licenses/MIT.
1856
- */
1857
- /**
1858
- * Force a service worker to activate immediately, instead of
1859
- * [waiting](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting)
1860
- * for existing clients to close.
1861
- *
1862
- * @memberof module:workbox-core
1863
- */
1864
-
1865
- function skipWaiting() {
1866
- // We need to explicitly call `self.skipWaiting()` here because we're
1867
- // shadowing `skipWaiting` with this local function.
1868
- self.addEventListener('install', () => self.skipWaiting());
1869
- }
1870
-
1871
- exports._private = _private;
1872
- exports.cacheNames = cacheNames$1;
1873
- exports.clientsClaim = clientsClaim;
1874
- exports.copyResponse = copyResponse;
1875
- exports.registerQuotaErrorCallback = registerQuotaErrorCallback;
1876
- exports.setCacheNameDetails = setCacheNameDetails;
1877
- exports.skipWaiting = skipWaiting;
1878
-
1879
- return exports;
1880
-
1881
- }({}));
1882
- //# sourceMappingURL=workbox-core.dev.js.map
1
+ this.workbox = this.workbox || {};
2
+ this.workbox.core = (function (exports) {
3
+ 'use strict';
4
+
5
+ try {
6
+ self['workbox:core:5.1.1'] && _();
7
+ } catch (e) {}
8
+
9
+ /*
10
+ Copyright 2019 Google LLC
11
+ Use of this source code is governed by an MIT-style
12
+ license that can be found in the LICENSE file or at
13
+ https://opensource.org/licenses/MIT.
14
+ */
15
+ const logger = (() => {
16
+ // Don't overwrite this value if it's already set.
17
+ // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
18
+ if (!('__WB_DISABLE_DEV_LOGS' in self)) {
19
+ self.__WB_DISABLE_DEV_LOGS = false;
20
+ }
21
+
22
+ let inGroup = false;
23
+ const methodToColorMap = {
24
+ debug: `#7f8c8d`,
25
+ log: `#2ecc71`,
26
+ warn: `#f39c12`,
27
+ error: `#c0392b`,
28
+ groupCollapsed: `#3498db`,
29
+ groupEnd: null
30
+ };
31
+
32
+ const print = function (method, args) {
33
+ if (self.__WB_DISABLE_DEV_LOGS) {
34
+ return;
35
+ }
36
+
37
+ if (method === 'groupCollapsed') {
38
+ // Safari doesn't print all console.groupCollapsed() arguments:
39
+ // https://bugs.webkit.org/show_bug.cgi?id=182754
40
+ if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
41
+ console[method](...args);
42
+ return;
43
+ }
44
+ }
45
+
46
+ const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed.
47
+
48
+ const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
49
+ console[method](...logPrefix, ...args);
50
+
51
+ if (method === 'groupCollapsed') {
52
+ inGroup = true;
53
+ }
54
+
55
+ if (method === 'groupEnd') {
56
+ inGroup = false;
57
+ }
58
+ };
59
+
60
+ const api = {};
61
+ const loggerMethods = Object.keys(methodToColorMap);
62
+
63
+ for (const key of loggerMethods) {
64
+ const method = key;
65
+
66
+ api[method] = (...args) => {
67
+ print(method, args);
68
+ };
69
+ }
70
+
71
+ return api;
72
+ })();
73
+
74
+ /*
75
+ Copyright 2018 Google LLC
76
+
77
+ Use of this source code is governed by an MIT-style
78
+ license that can be found in the LICENSE file or at
79
+ https://opensource.org/licenses/MIT.
80
+ */
81
+ const messages = {
82
+ 'invalid-value': ({
83
+ paramName,
84
+ validValueDescription,
85
+ value
86
+ }) => {
87
+ if (!paramName || !validValueDescription) {
88
+ throw new Error(`Unexpected input to 'invalid-value' error.`);
89
+ }
90
+
91
+ return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
92
+ },
93
+ 'not-in-sw': ({
94
+ moduleName
95
+ }) => {
96
+ if (!moduleName) {
97
+ throw new Error(`Unexpected input to 'not-in-sw' error.`);
98
+ }
99
+
100
+ return `The '${moduleName}' must be used in a service worker.`;
101
+ },
102
+ 'not-an-array': ({
103
+ moduleName,
104
+ className,
105
+ funcName,
106
+ paramName
107
+ }) => {
108
+ if (!moduleName || !className || !funcName || !paramName) {
109
+ throw new Error(`Unexpected input to 'not-an-array' error.`);
110
+ }
111
+
112
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
113
+ },
114
+ 'incorrect-type': ({
115
+ expectedType,
116
+ paramName,
117
+ moduleName,
118
+ className,
119
+ funcName
120
+ }) => {
121
+ if (!expectedType || !paramName || !moduleName || !funcName) {
122
+ throw new Error(`Unexpected input to 'incorrect-type' error.`);
123
+ }
124
+
125
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}` + `${funcName}()' must be of type ${expectedType}.`;
126
+ },
127
+ 'incorrect-class': ({
128
+ expectedClass,
129
+ paramName,
130
+ moduleName,
131
+ className,
132
+ funcName,
133
+ isReturnValueProblem
134
+ }) => {
135
+ if (!expectedClass || !moduleName || !funcName) {
136
+ throw new Error(`Unexpected input to 'incorrect-class' error.`);
137
+ }
138
+
139
+ if (isReturnValueProblem) {
140
+ return `The return value from ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`;
141
+ }
142
+
143
+ return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`;
144
+ },
145
+ 'missing-a-method': ({
146
+ expectedMethod,
147
+ paramName,
148
+ moduleName,
149
+ className,
150
+ funcName
151
+ }) => {
152
+ if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
153
+ throw new Error(`Unexpected input to 'missing-a-method' error.`);
154
+ }
155
+
156
+ return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
157
+ },
158
+ 'add-to-cache-list-unexpected-type': ({
159
+ entry
160
+ }) => {
161
+ return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
162
+ },
163
+ 'add-to-cache-list-conflicting-entries': ({
164
+ firstEntry,
165
+ secondEntry
166
+ }) => {
167
+ if (!firstEntry || !secondEntry) {
168
+ throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
169
+ }
170
+
171
+ return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry._entryId} but different revision details. Workbox is ` + `is unable to cache and version the asset correctly. Please remove one ` + `of the entries.`;
172
+ },
173
+ 'plugin-error-request-will-fetch': ({
174
+ thrownError
175
+ }) => {
176
+ if (!thrownError) {
177
+ throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
178
+ }
179
+
180
+ return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownError.message}'.`;
181
+ },
182
+ 'invalid-cache-name': ({
183
+ cacheNameId,
184
+ value
185
+ }) => {
186
+ if (!cacheNameId) {
187
+ throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
188
+ }
189
+
190
+ return `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
191
+ },
192
+ 'unregister-route-but-not-found-with-method': ({
193
+ method
194
+ }) => {
195
+ if (!method) {
196
+ throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
197
+ }
198
+
199
+ return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
200
+ },
201
+ 'unregister-route-route-not-registered': () => {
202
+ return `The route you're trying to unregister was not previously ` + `registered.`;
203
+ },
204
+ 'queue-replay-failed': ({
205
+ name
206
+ }) => {
207
+ return `Replaying the background sync queue '${name}' failed.`;
208
+ },
209
+ 'duplicate-queue-name': ({
210
+ name
211
+ }) => {
212
+ return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
213
+ },
214
+ 'expired-test-without-max-age': ({
215
+ methodName,
216
+ paramName
217
+ }) => {
218
+ return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
219
+ },
220
+ 'unsupported-route-type': ({
221
+ moduleName,
222
+ className,
223
+ funcName,
224
+ paramName
225
+ }) => {
226
+ return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
227
+ },
228
+ 'not-array-of-class': ({
229
+ value,
230
+ expectedClass,
231
+ moduleName,
232
+ className,
233
+ funcName,
234
+ paramName
235
+ }) => {
236
+ return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
237
+ },
238
+ 'max-entries-or-age-required': ({
239
+ moduleName,
240
+ className,
241
+ funcName
242
+ }) => {
243
+ return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
244
+ },
245
+ 'statuses-or-headers-required': ({
246
+ moduleName,
247
+ className,
248
+ funcName
249
+ }) => {
250
+ return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
251
+ },
252
+ 'invalid-string': ({
253
+ moduleName,
254
+ funcName,
255
+ paramName
256
+ }) => {
257
+ if (!paramName || !moduleName || !funcName) {
258
+ throw new Error(`Unexpected input to 'invalid-string' error.`);
259
+ }
260
+
261
+ return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`;
262
+ },
263
+ 'channel-name-required': () => {
264
+ return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
265
+ },
266
+ 'invalid-responses-are-same-args': () => {
267
+ return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
268
+ },
269
+ 'expire-custom-caches-only': () => {
270
+ return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
271
+ },
272
+ 'unit-must-be-bytes': ({
273
+ normalizedRangeHeader
274
+ }) => {
275
+ if (!normalizedRangeHeader) {
276
+ throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
277
+ }
278
+
279
+ return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
280
+ },
281
+ 'single-range-only': ({
282
+ normalizedRangeHeader
283
+ }) => {
284
+ if (!normalizedRangeHeader) {
285
+ throw new Error(`Unexpected input to 'single-range-only' error.`);
286
+ }
287
+
288
+ return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
289
+ },
290
+ 'invalid-range-values': ({
291
+ normalizedRangeHeader
292
+ }) => {
293
+ if (!normalizedRangeHeader) {
294
+ throw new Error(`Unexpected input to 'invalid-range-values' error.`);
295
+ }
296
+
297
+ return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
298
+ },
299
+ 'no-range-header': () => {
300
+ return `No Range header was found in the Request provided.`;
301
+ },
302
+ 'range-not-satisfiable': ({
303
+ size,
304
+ start,
305
+ end
306
+ }) => {
307
+ return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
308
+ },
309
+ 'attempt-to-cache-non-get-request': ({
310
+ url,
311
+ method
312
+ }) => {
313
+ return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
314
+ },
315
+ 'cache-put-with-no-response': ({
316
+ url
317
+ }) => {
318
+ return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
319
+ },
320
+ 'no-response': ({
321
+ url,
322
+ error
323
+ }) => {
324
+ let message = `The strategy could not generate a response for '${url}'.`;
325
+
326
+ if (error) {
327
+ message += ` The underlying error is ${error}.`;
328
+ }
329
+
330
+ return message;
331
+ },
332
+ 'bad-precaching-response': ({
333
+ url,
334
+ status
335
+ }) => {
336
+ return `The precaching request for '${url}' failed with an HTTP ` + `status of ${status}.`;
337
+ },
338
+ 'non-precached-url': ({
339
+ url
340
+ }) => {
341
+ return `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.`;
342
+ },
343
+ 'add-to-cache-list-conflicting-integrities': ({
344
+ url
345
+ }) => {
346
+ return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.`;
347
+ },
348
+ 'missing-precache-entry': ({
349
+ cacheName,
350
+ url
351
+ }) => {
352
+ return `Unable to find a precached response in ${cacheName} for ${url}.`;
353
+ }
354
+ };
355
+
356
+ /*
357
+ Copyright 2018 Google LLC
358
+
359
+ Use of this source code is governed by an MIT-style
360
+ license that can be found in the LICENSE file or at
361
+ https://opensource.org/licenses/MIT.
362
+ */
363
+
364
+ const generatorFunction = (code, details = {}) => {
365
+ const message = messages[code];
366
+
367
+ if (!message) {
368
+ throw new Error(`Unable to find message for code '${code}'.`);
369
+ }
370
+
371
+ return message(details);
372
+ };
373
+
374
+ const messageGenerator = generatorFunction;
375
+
376
+ /*
377
+ Copyright 2018 Google LLC
378
+
379
+ Use of this source code is governed by an MIT-style
380
+ license that can be found in the LICENSE file or at
381
+ https://opensource.org/licenses/MIT.
382
+ */
383
+ /**
384
+ * Workbox errors should be thrown with this class.
385
+ * This allows use to ensure the type easily in tests,
386
+ * helps developers identify errors from workbox
387
+ * easily and allows use to optimise error
388
+ * messages correctly.
389
+ *
390
+ * @private
391
+ */
392
+
393
+ class WorkboxError extends Error {
394
+ /**
395
+ *
396
+ * @param {string} errorCode The error code that
397
+ * identifies this particular error.
398
+ * @param {Object=} details Any relevant arguments
399
+ * that will help developers identify issues should
400
+ * be added as a key on the context object.
401
+ */
402
+ constructor(errorCode, details) {
403
+ const message = messageGenerator(errorCode, details);
404
+ super(message);
405
+ this.name = errorCode;
406
+ this.details = details;
407
+ }
408
+
409
+ }
410
+
411
+ /*
412
+ Copyright 2018 Google LLC
413
+
414
+ Use of this source code is governed by an MIT-style
415
+ license that can be found in the LICENSE file or at
416
+ https://opensource.org/licenses/MIT.
417
+ */
418
+ /*
419
+ * This method returns true if the current context is a service worker.
420
+ */
421
+
422
+ const isSWEnv = moduleName => {
423
+ if (!('ServiceWorkerGlobalScope' in self)) {
424
+ throw new WorkboxError('not-in-sw', {
425
+ moduleName
426
+ });
427
+ }
428
+ };
429
+ /*
430
+ * This method throws if the supplied value is not an array.
431
+ * The destructed values are required to produce a meaningful error for users.
432
+ * The destructed and restructured object is so it's clear what is
433
+ * needed.
434
+ */
435
+
436
+
437
+ const isArray = (value, details) => {
438
+ if (!Array.isArray(value)) {
439
+ throw new WorkboxError('not-an-array', details);
440
+ }
441
+ };
442
+
443
+ const hasMethod = (object, expectedMethod, details) => {
444
+ const type = typeof object[expectedMethod];
445
+
446
+ if (type !== 'function') {
447
+ details['expectedMethod'] = expectedMethod;
448
+ throw new WorkboxError('missing-a-method', details);
449
+ }
450
+ };
451
+
452
+ const isType = (object, expectedType, details) => {
453
+ if (typeof object !== expectedType) {
454
+ details['expectedType'] = expectedType;
455
+ throw new WorkboxError('incorrect-type', details);
456
+ }
457
+ };
458
+
459
+ const isInstance = (object, expectedClass, details) => {
460
+ if (!(object instanceof expectedClass)) {
461
+ details['expectedClass'] = expectedClass;
462
+ throw new WorkboxError('incorrect-class', details);
463
+ }
464
+ };
465
+
466
+ const isOneOf = (value, validValues, details) => {
467
+ if (!validValues.includes(value)) {
468
+ details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
469
+ throw new WorkboxError('invalid-value', details);
470
+ }
471
+ };
472
+
473
+ const isArrayOfClass = (value, expectedClass, details) => {
474
+ const error = new WorkboxError('not-array-of-class', details);
475
+
476
+ if (!Array.isArray(value)) {
477
+ throw error;
478
+ }
479
+
480
+ for (const item of value) {
481
+ if (!(item instanceof expectedClass)) {
482
+ throw error;
483
+ }
484
+ }
485
+ };
486
+
487
+ const finalAssertExports = {
488
+ hasMethod,
489
+ isArray,
490
+ isInstance,
491
+ isOneOf,
492
+ isSWEnv,
493
+ isType,
494
+ isArrayOfClass
495
+ };
496
+
497
+ /*
498
+ Copyright 2018 Google LLC
499
+
500
+ Use of this source code is governed by an MIT-style
501
+ license that can be found in the LICENSE file or at
502
+ https://opensource.org/licenses/MIT.
503
+ */
504
+
505
+ const quotaErrorCallbacks = new Set();
506
+
507
+ /*
508
+ Copyright 2019 Google LLC
509
+
510
+ Use of this source code is governed by an MIT-style
511
+ license that can be found in the LICENSE file or at
512
+ https://opensource.org/licenses/MIT.
513
+ */
514
+ /**
515
+ * Adds a function to the set of quotaErrorCallbacks that will be executed if
516
+ * there's a quota error.
517
+ *
518
+ * @param {Function} callback
519
+ * @memberof module:workbox-core
520
+ */
521
+
522
+ function registerQuotaErrorCallback(callback) {
523
+ {
524
+ finalAssertExports.isType(callback, 'function', {
525
+ moduleName: 'workbox-core',
526
+ funcName: 'register',
527
+ paramName: 'callback'
528
+ });
529
+ }
530
+
531
+ quotaErrorCallbacks.add(callback);
532
+
533
+ {
534
+ logger.log('Registered a callback to respond to quota errors.', callback);
535
+ }
536
+ }
537
+
538
+ /*
539
+ Copyright 2018 Google LLC
540
+
541
+ Use of this source code is governed by an MIT-style
542
+ license that can be found in the LICENSE file or at
543
+ https://opensource.org/licenses/MIT.
544
+ */
545
+ const _cacheNameDetails = {
546
+ googleAnalytics: 'googleAnalytics',
547
+ precache: 'precache-v2',
548
+ prefix: 'workbox',
549
+ runtime: 'runtime',
550
+ suffix: typeof registration !== 'undefined' ? registration.scope : ''
551
+ };
552
+
553
+ const _createCacheName = cacheName => {
554
+ return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value && value.length > 0).join('-');
555
+ };
556
+
557
+ const eachCacheNameDetail = fn => {
558
+ for (const key of Object.keys(_cacheNameDetails)) {
559
+ fn(key);
560
+ }
561
+ };
562
+
563
+ const cacheNames = {
564
+ updateDetails: details => {
565
+ eachCacheNameDetail(key => {
566
+ if (typeof details[key] === 'string') {
567
+ _cacheNameDetails[key] = details[key];
568
+ }
569
+ });
570
+ },
571
+ getGoogleAnalyticsName: userCacheName => {
572
+ return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
573
+ },
574
+ getPrecacheName: userCacheName => {
575
+ return userCacheName || _createCacheName(_cacheNameDetails.precache);
576
+ },
577
+ getPrefix: () => {
578
+ return _cacheNameDetails.prefix;
579
+ },
580
+ getRuntimeName: userCacheName => {
581
+ return userCacheName || _createCacheName(_cacheNameDetails.runtime);
582
+ },
583
+ getSuffix: () => {
584
+ return _cacheNameDetails.suffix;
585
+ }
586
+ };
587
+
588
+ /*
589
+ Copyright 2018 Google LLC
590
+
591
+ Use of this source code is governed by an MIT-style
592
+ license that can be found in the LICENSE file or at
593
+ https://opensource.org/licenses/MIT.
594
+ */
595
+ /**
596
+ * Runs all of the callback functions, one at a time sequentially, in the order
597
+ * in which they were registered.
598
+ *
599
+ * @memberof module:workbox-core
600
+ * @private
601
+ */
602
+
603
+ async function executeQuotaErrorCallbacks() {
604
+ {
605
+ logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`);
606
+ }
607
+
608
+ for (const callback of quotaErrorCallbacks) {
609
+ await callback();
610
+
611
+ {
612
+ logger.log(callback, 'is complete.');
613
+ }
614
+ }
615
+
616
+ {
617
+ logger.log('Finished running callbacks.');
618
+ }
619
+ }
620
+
621
+ /*
622
+ Copyright 2018 Google LLC
623
+
624
+ Use of this source code is governed by an MIT-style
625
+ license that can be found in the LICENSE file or at
626
+ https://opensource.org/licenses/MIT.
627
+ */
628
+
629
+ const getFriendlyURL = url => {
630
+ const urlObj = new URL(String(url), location.href); // See https://github.com/GoogleChrome/workbox/issues/2323
631
+ // We want to include everything, except for the origin if it's same-origin.
632
+
633
+ return urlObj.href.replace(new RegExp(`^${location.origin}`), '');
634
+ };
635
+
636
+ /*
637
+ Copyright 2018 Google LLC
638
+
639
+ Use of this source code is governed by an MIT-style
640
+ license that can be found in the LICENSE file or at
641
+ https://opensource.org/licenses/MIT.
642
+ */
643
+ const pluginUtils = {
644
+ filter: (plugins, callbackName) => {
645
+ return plugins.filter(plugin => callbackName in plugin);
646
+ }
647
+ };
648
+
649
+ /*
650
+ Copyright 2018 Google LLC
651
+
652
+ Use of this source code is governed by an MIT-style
653
+ license that can be found in the LICENSE file or at
654
+ https://opensource.org/licenses/MIT.
655
+ */
656
+ /**
657
+ * Checks the list of plugins for the cacheKeyWillBeUsed callback, and
658
+ * executes any of those callbacks found in sequence. The final `Request` object
659
+ * returned by the last plugin is treated as the cache key for cache reads
660
+ * and/or writes.
661
+ *
662
+ * @param {Object} options
663
+ * @param {Request} options.request
664
+ * @param {string} options.mode
665
+ * @param {Array<Object>} [options.plugins=[]]
666
+ * @return {Promise<Request>}
667
+ *
668
+ * @private
669
+ * @memberof module:workbox-core
670
+ */
671
+
672
+ const _getEffectiveRequest = async ({
673
+ request,
674
+ mode,
675
+ plugins = []
676
+ }) => {
677
+ const cacheKeyWillBeUsedPlugins = pluginUtils.filter(plugins, "cacheKeyWillBeUsed"
678
+ /* CACHE_KEY_WILL_BE_USED */
679
+ );
680
+ let effectiveRequest = request;
681
+
682
+ for (const plugin of cacheKeyWillBeUsedPlugins) {
683
+ effectiveRequest = await plugin["cacheKeyWillBeUsed"
684
+ /* CACHE_KEY_WILL_BE_USED */
685
+ ].call(plugin, {
686
+ mode,
687
+ request: effectiveRequest
688
+ });
689
+
690
+ if (typeof effectiveRequest === 'string') {
691
+ effectiveRequest = new Request(effectiveRequest);
692
+ }
693
+
694
+ {
695
+ finalAssertExports.isInstance(effectiveRequest, Request, {
696
+ moduleName: 'Plugin',
697
+ funcName: "cacheKeyWillBeUsed"
698
+ /* CACHE_KEY_WILL_BE_USED */
699
+ ,
700
+ isReturnValueProblem: true
701
+ });
702
+ }
703
+ }
704
+
705
+ return effectiveRequest;
706
+ };
707
+ /**
708
+ * This method will call cacheWillUpdate on the available plugins (or use
709
+ * status === 200) to determine if the Response is safe and valid to cache.
710
+ *
711
+ * @param {Object} options
712
+ * @param {Request} options.request
713
+ * @param {Response} options.response
714
+ * @param {Event} [options.event]
715
+ * @param {Array<Object>} [options.plugins=[]]
716
+ * @return {Promise<Response>}
717
+ *
718
+ * @private
719
+ * @memberof module:workbox-core
720
+ */
721
+
722
+
723
+ const _isResponseSafeToCache = async ({
724
+ request,
725
+ response,
726
+ event,
727
+ plugins = []
728
+ }) => {
729
+ let responseToCache = response;
730
+ let pluginsUsed = false;
731
+
732
+ for (const plugin of plugins) {
733
+ if ("cacheWillUpdate"
734
+ /* CACHE_WILL_UPDATE */
735
+ in plugin) {
736
+ pluginsUsed = true;
737
+ const pluginMethod = plugin["cacheWillUpdate"
738
+ /* CACHE_WILL_UPDATE */
739
+ ];
740
+ responseToCache = await pluginMethod.call(plugin, {
741
+ request,
742
+ response: responseToCache,
743
+ event
744
+ });
745
+
746
+ {
747
+ if (responseToCache) {
748
+ finalAssertExports.isInstance(responseToCache, Response, {
749
+ moduleName: 'Plugin',
750
+ funcName: "cacheWillUpdate"
751
+ /* CACHE_WILL_UPDATE */
752
+ ,
753
+ isReturnValueProblem: true
754
+ });
755
+ }
756
+ }
757
+
758
+ if (!responseToCache) {
759
+ break;
760
+ }
761
+ }
762
+ }
763
+
764
+ if (!pluginsUsed) {
765
+ {
766
+ if (responseToCache) {
767
+ if (responseToCache.status !== 200) {
768
+ if (responseToCache.status === 0) {
769
+ logger.warn(`The response for '${request.url}' is an opaque ` + `response. The caching strategy that you're using will not ` + `cache opaque responses by default.`);
770
+ } else {
771
+ logger.debug(`The response for '${request.url}' returned ` + `a status code of '${response.status}' and won't be cached as a ` + `result.`);
772
+ }
773
+ }
774
+ }
775
+ }
776
+
777
+ responseToCache = responseToCache && responseToCache.status === 200 ? responseToCache : undefined;
778
+ }
779
+
780
+ return responseToCache ? responseToCache : null;
781
+ };
782
+ /**
783
+ * This is a wrapper around cache.match().
784
+ *
785
+ * @param {Object} options
786
+ * @param {string} options.cacheName Name of the cache to match against.
787
+ * @param {Request} options.request The Request that will be used to look up
788
+ * cache entries.
789
+ * @param {Event} [options.event] The event that prompted the action.
790
+ * @param {Object} [options.matchOptions] Options passed to cache.match().
791
+ * @param {Array<Object>} [options.plugins=[]] Array of plugins.
792
+ * @return {Response} A cached response if available.
793
+ *
794
+ * @private
795
+ * @memberof module:workbox-core
796
+ */
797
+
798
+
799
+ const matchWrapper = async ({
800
+ cacheName,
801
+ request,
802
+ event,
803
+ matchOptions,
804
+ plugins = []
805
+ }) => {
806
+ const cache = await self.caches.open(cacheName);
807
+ const effectiveRequest = await _getEffectiveRequest({
808
+ plugins,
809
+ request,
810
+ mode: 'read'
811
+ });
812
+ let cachedResponse = await cache.match(effectiveRequest, matchOptions);
813
+
814
+ {
815
+ if (cachedResponse) {
816
+ logger.debug(`Found a cached response in '${cacheName}'.`);
817
+ } else {
818
+ logger.debug(`No cached response found in '${cacheName}'.`);
819
+ }
820
+ }
821
+
822
+ for (const plugin of plugins) {
823
+ if ("cachedResponseWillBeUsed"
824
+ /* CACHED_RESPONSE_WILL_BE_USED */
825
+ in plugin) {
826
+ const pluginMethod = plugin["cachedResponseWillBeUsed"
827
+ /* CACHED_RESPONSE_WILL_BE_USED */
828
+ ];
829
+ cachedResponse = await pluginMethod.call(plugin, {
830
+ cacheName,
831
+ event,
832
+ matchOptions,
833
+ cachedResponse,
834
+ request: effectiveRequest
835
+ });
836
+
837
+ {
838
+ if (cachedResponse) {
839
+ finalAssertExports.isInstance(cachedResponse, Response, {
840
+ moduleName: 'Plugin',
841
+ funcName: "cachedResponseWillBeUsed"
842
+ /* CACHED_RESPONSE_WILL_BE_USED */
843
+ ,
844
+ isReturnValueProblem: true
845
+ });
846
+ }
847
+ }
848
+ }
849
+ }
850
+
851
+ return cachedResponse;
852
+ };
853
+ /**
854
+ * Wrapper around cache.put().
855
+ *
856
+ * Will call `cacheDidUpdate` on plugins if the cache was updated, using
857
+ * `matchOptions` when determining what the old entry is.
858
+ *
859
+ * @param {Object} options
860
+ * @param {string} options.cacheName
861
+ * @param {Request} options.request
862
+ * @param {Response} options.response
863
+ * @param {Event} [options.event]
864
+ * @param {Array<Object>} [options.plugins=[]]
865
+ * @param {Object} [options.matchOptions]
866
+ *
867
+ * @private
868
+ * @memberof module:workbox-core
869
+ */
870
+
871
+
872
+ const putWrapper = async ({
873
+ cacheName,
874
+ request,
875
+ response,
876
+ event,
877
+ plugins = [],
878
+ matchOptions
879
+ }) => {
880
+ {
881
+ if (request.method && request.method !== 'GET') {
882
+ throw new WorkboxError('attempt-to-cache-non-get-request', {
883
+ url: getFriendlyURL(request.url),
884
+ method: request.method
885
+ });
886
+ }
887
+ }
888
+
889
+ const effectiveRequest = await _getEffectiveRequest({
890
+ plugins,
891
+ request,
892
+ mode: 'write'
893
+ });
894
+
895
+ if (!response) {
896
+ {
897
+ logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`);
898
+ }
899
+
900
+ throw new WorkboxError('cache-put-with-no-response', {
901
+ url: getFriendlyURL(effectiveRequest.url)
902
+ });
903
+ }
904
+
905
+ const responseToCache = await _isResponseSafeToCache({
906
+ event,
907
+ plugins,
908
+ response,
909
+ request: effectiveRequest
910
+ });
911
+
912
+ if (!responseToCache) {
913
+ {
914
+ logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will ` + `not be cached.`, responseToCache);
915
+ }
916
+
917
+ return;
918
+ }
919
+
920
+ const cache = await self.caches.open(cacheName);
921
+ const updatePlugins = pluginUtils.filter(plugins, "cacheDidUpdate"
922
+ /* CACHE_DID_UPDATE */
923
+ );
924
+ const oldResponse = updatePlugins.length > 0 ? await matchWrapper({
925
+ cacheName,
926
+ matchOptions,
927
+ request: effectiveRequest
928
+ }) : null;
929
+
930
+ {
931
+ logger.debug(`Updating the '${cacheName}' cache with a new Response for ` + `${getFriendlyURL(effectiveRequest.url)}.`);
932
+ }
933
+
934
+ try {
935
+ await cache.put(effectiveRequest, responseToCache);
936
+ } catch (error) {
937
+ // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
938
+ if (error.name === 'QuotaExceededError') {
939
+ await executeQuotaErrorCallbacks();
940
+ }
941
+
942
+ throw error;
943
+ }
944
+
945
+ for (const plugin of updatePlugins) {
946
+ await plugin["cacheDidUpdate"
947
+ /* CACHE_DID_UPDATE */
948
+ ].call(plugin, {
949
+ cacheName,
950
+ event,
951
+ oldResponse,
952
+ newResponse: responseToCache,
953
+ request: effectiveRequest
954
+ });
955
+ }
956
+ };
957
+
958
+ const cacheWrapper = {
959
+ put: putWrapper,
960
+ match: matchWrapper
961
+ };
962
+
963
+ /*
964
+ Copyright 2019 Google LLC
965
+
966
+ Use of this source code is governed by an MIT-style
967
+ license that can be found in the LICENSE file or at
968
+ https://opensource.org/licenses/MIT.
969
+ */
970
+ let supportStatus;
971
+ /**
972
+ * A utility function that determines whether the current browser supports
973
+ * constructing a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)
974
+ * object.
975
+ *
976
+ * @return {boolean} `true`, if the current browser can successfully
977
+ * construct a `ReadableStream`, `false` otherwise.
978
+ *
979
+ * @private
980
+ */
981
+
982
+ function canConstructReadableStream() {
983
+ if (supportStatus === undefined) {
984
+ // See https://github.com/GoogleChrome/workbox/issues/1473
985
+ try {
986
+ new ReadableStream({
987
+ start() {}
988
+
989
+ });
990
+ supportStatus = true;
991
+ } catch (error) {
992
+ supportStatus = false;
993
+ }
994
+ }
995
+
996
+ return supportStatus;
997
+ }
998
+
999
+ /*
1000
+ Copyright 2019 Google LLC
1001
+
1002
+ Use of this source code is governed by an MIT-style
1003
+ license that can be found in the LICENSE file or at
1004
+ https://opensource.org/licenses/MIT.
1005
+ */
1006
+ let supportStatus$1;
1007
+ /**
1008
+ * A utility function that determines whether the current browser supports
1009
+ * constructing a new `Response` from a `response.body` stream.
1010
+ *
1011
+ * @return {boolean} `true`, if the current browser can successfully
1012
+ * construct a `Response` from a `response.body` stream, `false` otherwise.
1013
+ *
1014
+ * @private
1015
+ */
1016
+
1017
+ function canConstructResponseFromBodyStream() {
1018
+ if (supportStatus$1 === undefined) {
1019
+ const testResponse = new Response('');
1020
+
1021
+ if ('body' in testResponse) {
1022
+ try {
1023
+ new Response(testResponse.body);
1024
+ supportStatus$1 = true;
1025
+ } catch (error) {
1026
+ supportStatus$1 = false;
1027
+ }
1028
+ }
1029
+
1030
+ supportStatus$1 = false;
1031
+ }
1032
+
1033
+ return supportStatus$1;
1034
+ }
1035
+
1036
+ /*
1037
+ Copyright 2019 Google LLC
1038
+ Use of this source code is governed by an MIT-style
1039
+ license that can be found in the LICENSE file or at
1040
+ https://opensource.org/licenses/MIT.
1041
+ */
1042
+ /**
1043
+ * A helper function that prevents a promise from being flagged as unused.
1044
+ *
1045
+ * @private
1046
+ **/
1047
+
1048
+ function dontWaitFor(promise) {
1049
+ // Effective no-op.
1050
+ promise.then(() => {});
1051
+ }
1052
+
1053
+ /*
1054
+ Copyright 2018 Google LLC
1055
+
1056
+ Use of this source code is governed by an MIT-style
1057
+ license that can be found in the LICENSE file or at
1058
+ https://opensource.org/licenses/MIT.
1059
+ */
1060
+ /**
1061
+ * A class that wraps common IndexedDB functionality in a promise-based API.
1062
+ * It exposes all the underlying power and functionality of IndexedDB, but
1063
+ * wraps the most commonly used features in a way that's much simpler to use.
1064
+ *
1065
+ * @private
1066
+ */
1067
+
1068
+ class DBWrapper {
1069
+ /**
1070
+ * @param {string} name
1071
+ * @param {number} version
1072
+ * @param {Object=} [callback]
1073
+ * @param {!Function} [callbacks.onupgradeneeded]
1074
+ * @param {!Function} [callbacks.onversionchange] Defaults to
1075
+ * DBWrapper.prototype._onversionchange when not specified.
1076
+ * @private
1077
+ */
1078
+ constructor(name, version, {
1079
+ onupgradeneeded,
1080
+ onversionchange
1081
+ } = {}) {
1082
+ this._db = null;
1083
+ this._name = name;
1084
+ this._version = version;
1085
+ this._onupgradeneeded = onupgradeneeded;
1086
+
1087
+ this._onversionchange = onversionchange || (() => this.close());
1088
+ }
1089
+ /**
1090
+ * Returns the IDBDatabase instance (not normally needed).
1091
+ * @return {IDBDatabase|undefined}
1092
+ *
1093
+ * @private
1094
+ */
1095
+
1096
+
1097
+ get db() {
1098
+ return this._db;
1099
+ }
1100
+ /**
1101
+ * Opens a connected to an IDBDatabase, invokes any onupgradedneeded
1102
+ * callback, and added an onversionchange callback to the database.
1103
+ *
1104
+ * @return {IDBDatabase}
1105
+ * @private
1106
+ */
1107
+
1108
+
1109
+ async open() {
1110
+ if (this._db) return;
1111
+ this._db = await new Promise((resolve, reject) => {
1112
+ // This flag is flipped to true if the timeout callback runs prior
1113
+ // to the request failing or succeeding. Note: we use a timeout instead
1114
+ // of an onblocked handler since there are cases where onblocked will
1115
+ // never never run. A timeout better handles all possible scenarios:
1116
+ // https://github.com/w3c/IndexedDB/issues/223
1117
+ let openRequestTimedOut = false;
1118
+ setTimeout(() => {
1119
+ openRequestTimedOut = true;
1120
+ reject(new Error('The open request was blocked and timed out'));
1121
+ }, this.OPEN_TIMEOUT);
1122
+ const openRequest = indexedDB.open(this._name, this._version);
1123
+
1124
+ openRequest.onerror = () => reject(openRequest.error);
1125
+
1126
+ openRequest.onupgradeneeded = evt => {
1127
+ if (openRequestTimedOut) {
1128
+ openRequest.transaction.abort();
1129
+ openRequest.result.close();
1130
+ } else if (typeof this._onupgradeneeded === 'function') {
1131
+ this._onupgradeneeded(evt);
1132
+ }
1133
+ };
1134
+
1135
+ openRequest.onsuccess = () => {
1136
+ const db = openRequest.result;
1137
+
1138
+ if (openRequestTimedOut) {
1139
+ db.close();
1140
+ } else {
1141
+ db.onversionchange = this._onversionchange.bind(this);
1142
+ resolve(db);
1143
+ }
1144
+ };
1145
+ });
1146
+ return this;
1147
+ }
1148
+ /**
1149
+ * Polyfills the native `getKey()` method. Note, this is overridden at
1150
+ * runtime if the browser supports the native method.
1151
+ *
1152
+ * @param {string} storeName
1153
+ * @param {*} query
1154
+ * @return {Array}
1155
+ * @private
1156
+ */
1157
+
1158
+
1159
+ async getKey(storeName, query) {
1160
+ return (await this.getAllKeys(storeName, query, 1))[0];
1161
+ }
1162
+ /**
1163
+ * Polyfills the native `getAll()` method. Note, this is overridden at
1164
+ * runtime if the browser supports the native method.
1165
+ *
1166
+ * @param {string} storeName
1167
+ * @param {*} query
1168
+ * @param {number} count
1169
+ * @return {Array}
1170
+ * @private
1171
+ */
1172
+
1173
+
1174
+ async getAll(storeName, query, count) {
1175
+ return await this.getAllMatching(storeName, {
1176
+ query,
1177
+ count
1178
+ });
1179
+ }
1180
+ /**
1181
+ * Polyfills the native `getAllKeys()` method. Note, this is overridden at
1182
+ * runtime if the browser supports the native method.
1183
+ *
1184
+ * @param {string} storeName
1185
+ * @param {*} query
1186
+ * @param {number} count
1187
+ * @return {Array}
1188
+ * @private
1189
+ */
1190
+
1191
+
1192
+ async getAllKeys(storeName, query, count) {
1193
+ const entries = await this.getAllMatching(storeName, {
1194
+ query,
1195
+ count,
1196
+ includeKeys: true
1197
+ });
1198
+ return entries.map(entry => entry.key);
1199
+ }
1200
+ /**
1201
+ * Supports flexible lookup in an object store by specifying an index,
1202
+ * query, direction, and count. This method returns an array of objects
1203
+ * with the signature .
1204
+ *
1205
+ * @param {string} storeName
1206
+ * @param {Object} [opts]
1207
+ * @param {string} [opts.index] The index to use (if specified).
1208
+ * @param {*} [opts.query]
1209
+ * @param {IDBCursorDirection} [opts.direction]
1210
+ * @param {number} [opts.count] The max number of results to return.
1211
+ * @param {boolean} [opts.includeKeys] When true, the structure of the
1212
+ * returned objects is changed from an array of values to an array of
1213
+ * objects in the form {key, primaryKey, value}.
1214
+ * @return {Array}
1215
+ * @private
1216
+ */
1217
+
1218
+
1219
+ async getAllMatching(storeName, {
1220
+ index,
1221
+ query = null,
1222
+ // IE/Edge errors if query === `undefined`.
1223
+ direction = 'next',
1224
+ count,
1225
+ includeKeys = false
1226
+ } = {}) {
1227
+ return await this.transaction([storeName], 'readonly', (txn, done) => {
1228
+ const store = txn.objectStore(storeName);
1229
+ const target = index ? store.index(index) : store;
1230
+ const results = [];
1231
+ const request = target.openCursor(query, direction);
1232
+
1233
+ request.onsuccess = () => {
1234
+ const cursor = request.result;
1235
+
1236
+ if (cursor) {
1237
+ results.push(includeKeys ? cursor : cursor.value);
1238
+
1239
+ if (count && results.length >= count) {
1240
+ done(results);
1241
+ } else {
1242
+ cursor.continue();
1243
+ }
1244
+ } else {
1245
+ done(results);
1246
+ }
1247
+ };
1248
+ });
1249
+ }
1250
+ /**
1251
+ * Accepts a list of stores, a transaction type, and a callback and
1252
+ * performs a transaction. A promise is returned that resolves to whatever
1253
+ * value the callback chooses. The callback holds all the transaction logic
1254
+ * and is invoked with two arguments:
1255
+ * 1. The IDBTransaction object
1256
+ * 2. A `done` function, that's used to resolve the promise when
1257
+ * when the transaction is done, if passed a value, the promise is
1258
+ * resolved to that value.
1259
+ *
1260
+ * @param {Array<string>} storeNames An array of object store names
1261
+ * involved in the transaction.
1262
+ * @param {string} type Can be `readonly` or `readwrite`.
1263
+ * @param {!Function} callback
1264
+ * @return {*} The result of the transaction ran by the callback.
1265
+ * @private
1266
+ */
1267
+
1268
+
1269
+ async transaction(storeNames, type, callback) {
1270
+ await this.open();
1271
+ return await new Promise((resolve, reject) => {
1272
+ const txn = this._db.transaction(storeNames, type);
1273
+
1274
+ txn.onabort = () => reject(txn.error);
1275
+
1276
+ txn.oncomplete = () => resolve();
1277
+
1278
+ callback(txn, value => resolve(value));
1279
+ });
1280
+ }
1281
+ /**
1282
+ * Delegates async to a native IDBObjectStore method.
1283
+ *
1284
+ * @param {string} method The method name.
1285
+ * @param {string} storeName The object store name.
1286
+ * @param {string} type Can be `readonly` or `readwrite`.
1287
+ * @param {...*} args The list of args to pass to the native method.
1288
+ * @return {*} The result of the transaction.
1289
+ * @private
1290
+ */
1291
+
1292
+
1293
+ async _call(method, storeName, type, ...args) {
1294
+ const callback = (txn, done) => {
1295
+ const objStore = txn.objectStore(storeName); // TODO(philipwalton): Fix this underlying TS2684 error.
1296
+ // @ts-ignore
1297
+
1298
+ const request = objStore[method].apply(objStore, args);
1299
+
1300
+ request.onsuccess = () => done(request.result);
1301
+ };
1302
+
1303
+ return await this.transaction([storeName], type, callback);
1304
+ }
1305
+ /**
1306
+ * Closes the connection opened by `DBWrapper.open()`. Generally this method
1307
+ * doesn't need to be called since:
1308
+ * 1. It's usually better to keep a connection open since opening
1309
+ * a new connection is somewhat slow.
1310
+ * 2. Connections are automatically closed when the reference is
1311
+ * garbage collected.
1312
+ * The primary use case for needing to close a connection is when another
1313
+ * reference (typically in another tab) needs to upgrade it and would be
1314
+ * blocked by the current, open connection.
1315
+ *
1316
+ * @private
1317
+ */
1318
+
1319
+
1320
+ close() {
1321
+ if (this._db) {
1322
+ this._db.close();
1323
+
1324
+ this._db = null;
1325
+ }
1326
+ }
1327
+
1328
+ } // Exposed on the prototype to let users modify the default timeout on a
1329
+ // per-instance or global basis.
1330
+
1331
+ DBWrapper.prototype.OPEN_TIMEOUT = 2000; // Wrap native IDBObjectStore methods according to their mode.
1332
+
1333
+ const methodsToWrap = {
1334
+ readonly: ['get', 'count', 'getKey', 'getAll', 'getAllKeys'],
1335
+ readwrite: ['add', 'put', 'clear', 'delete']
1336
+ };
1337
+
1338
+ for (const [mode, methods] of Object.entries(methodsToWrap)) {
1339
+ for (const method of methods) {
1340
+ if (method in IDBObjectStore.prototype) {
1341
+ // Don't use arrow functions here since we're outside of the class.
1342
+ DBWrapper.prototype[method] = async function (storeName, ...args) {
1343
+ return await this._call(method, storeName, mode, ...args);
1344
+ };
1345
+ }
1346
+ }
1347
+ }
1348
+
1349
+ /*
1350
+ Copyright 2018 Google LLC
1351
+
1352
+ Use of this source code is governed by an MIT-style
1353
+ license that can be found in the LICENSE file or at
1354
+ https://opensource.org/licenses/MIT.
1355
+ */
1356
+ /**
1357
+ * The Deferred class composes Promises in a way that allows for them to be
1358
+ * resolved or rejected from outside the constructor. In most cases promises
1359
+ * should be used directly, but Deferreds can be necessary when the logic to
1360
+ * resolve a promise must be separate.
1361
+ *
1362
+ * @private
1363
+ */
1364
+
1365
+ class Deferred {
1366
+ /**
1367
+ * Creates a promise and exposes its resolve and reject functions as methods.
1368
+ */
1369
+ constructor() {
1370
+ this.promise = new Promise((resolve, reject) => {
1371
+ this.resolve = resolve;
1372
+ this.reject = reject;
1373
+ });
1374
+ }
1375
+
1376
+ }
1377
+
1378
+ /*
1379
+ Copyright 2018 Google LLC
1380
+
1381
+ Use of this source code is governed by an MIT-style
1382
+ license that can be found in the LICENSE file or at
1383
+ https://opensource.org/licenses/MIT.
1384
+ */
1385
+ /**
1386
+ * Deletes the database.
1387
+ * Note: this is exported separately from the DBWrapper module because most
1388
+ * usages of IndexedDB in workbox dont need deleting, and this way it can be
1389
+ * reused in tests to delete databases without creating DBWrapper instances.
1390
+ *
1391
+ * @param {string} name The database name.
1392
+ * @private
1393
+ */
1394
+
1395
+ const deleteDatabase = async name => {
1396
+ await new Promise((resolve, reject) => {
1397
+ const request = indexedDB.deleteDatabase(name);
1398
+
1399
+ request.onerror = () => {
1400
+ reject(request.error);
1401
+ };
1402
+
1403
+ request.onblocked = () => {
1404
+ reject(new Error('Delete blocked'));
1405
+ };
1406
+
1407
+ request.onsuccess = () => {
1408
+ resolve();
1409
+ };
1410
+ });
1411
+ };
1412
+
1413
+ /*
1414
+ Copyright 2018 Google LLC
1415
+
1416
+ Use of this source code is governed by an MIT-style
1417
+ license that can be found in the LICENSE file or at
1418
+ https://opensource.org/licenses/MIT.
1419
+ */
1420
+ /**
1421
+ * Wrapper around the fetch API.
1422
+ *
1423
+ * Will call requestWillFetch on available plugins.
1424
+ *
1425
+ * @param {Object} options
1426
+ * @param {Request|string} options.request
1427
+ * @param {Object} [options.fetchOptions]
1428
+ * @param {ExtendableEvent} [options.event]
1429
+ * @param {Array<Object>} [options.plugins=[]]
1430
+ * @return {Promise<Response>}
1431
+ *
1432
+ * @private
1433
+ * @memberof module:workbox-core
1434
+ */
1435
+
1436
+ const wrappedFetch = async ({
1437
+ request,
1438
+ fetchOptions,
1439
+ event,
1440
+ plugins = []
1441
+ }) => {
1442
+ if (typeof request === 'string') {
1443
+ request = new Request(request);
1444
+ } // We *should* be able to call `await event.preloadResponse` even if it's
1445
+ // undefined, but for some reason, doing so leads to errors in our Node unit
1446
+ // tests. To work around that, explicitly check preloadResponse's value first.
1447
+
1448
+
1449
+ if (event instanceof FetchEvent && event.preloadResponse) {
1450
+ const possiblePreloadResponse = await event.preloadResponse;
1451
+
1452
+ if (possiblePreloadResponse) {
1453
+ {
1454
+ logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
1455
+ }
1456
+
1457
+ return possiblePreloadResponse;
1458
+ }
1459
+ }
1460
+
1461
+ {
1462
+ finalAssertExports.isInstance(request, Request, {
1463
+ paramName: 'request',
1464
+ expectedClass: Request,
1465
+ moduleName: 'workbox-core',
1466
+ className: 'fetchWrapper',
1467
+ funcName: 'wrappedFetch'
1468
+ });
1469
+ }
1470
+
1471
+ const failedFetchPlugins = pluginUtils.filter(plugins, "fetchDidFail"
1472
+ /* FETCH_DID_FAIL */
1473
+ ); // If there is a fetchDidFail plugin, we need to save a clone of the
1474
+ // original request before it's either modified by a requestWillFetch
1475
+ // plugin or before the original request's body is consumed via fetch().
1476
+
1477
+ const originalRequest = failedFetchPlugins.length > 0 ? request.clone() : null;
1478
+
1479
+ try {
1480
+ for (const plugin of plugins) {
1481
+ if ("requestWillFetch"
1482
+ /* REQUEST_WILL_FETCH */
1483
+ in plugin) {
1484
+ const pluginMethod = plugin["requestWillFetch"
1485
+ /* REQUEST_WILL_FETCH */
1486
+ ];
1487
+ const requestClone = request.clone();
1488
+ request = await pluginMethod.call(plugin, {
1489
+ request: requestClone,
1490
+ event
1491
+ });
1492
+
1493
+ if ("dev" !== 'production') {
1494
+ if (request) {
1495
+ finalAssertExports.isInstance(request, Request, {
1496
+ moduleName: 'Plugin',
1497
+ funcName: "cachedResponseWillBeUsed"
1498
+ /* CACHED_RESPONSE_WILL_BE_USED */
1499
+ ,
1500
+ isReturnValueProblem: true
1501
+ });
1502
+ }
1503
+ }
1504
+ }
1505
+ }
1506
+ } catch (err) {
1507
+ throw new WorkboxError('plugin-error-request-will-fetch', {
1508
+ thrownError: err
1509
+ });
1510
+ } // The request can be altered by plugins with `requestWillFetch` making
1511
+ // the original request (Most likely from a `fetch` event) to be different
1512
+ // to the Request we make. Pass both to `fetchDidFail` to aid debugging.
1513
+
1514
+
1515
+ const pluginFilteredRequest = request.clone();
1516
+
1517
+ try {
1518
+ let fetchResponse; // See https://github.com/GoogleChrome/workbox/issues/1796
1519
+
1520
+ if (request.mode === 'navigate') {
1521
+ fetchResponse = await fetch(request);
1522
+ } else {
1523
+ fetchResponse = await fetch(request, fetchOptions);
1524
+ }
1525
+
1526
+ if ("dev" !== 'production') {
1527
+ logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
1528
+ }
1529
+
1530
+ for (const plugin of plugins) {
1531
+ if ("fetchDidSucceed"
1532
+ /* FETCH_DID_SUCCEED */
1533
+ in plugin) {
1534
+ fetchResponse = await plugin["fetchDidSucceed"
1535
+ /* FETCH_DID_SUCCEED */
1536
+ ].call(plugin, {
1537
+ event,
1538
+ request: pluginFilteredRequest,
1539
+ response: fetchResponse
1540
+ });
1541
+
1542
+ if ("dev" !== 'production') {
1543
+ if (fetchResponse) {
1544
+ finalAssertExports.isInstance(fetchResponse, Response, {
1545
+ moduleName: 'Plugin',
1546
+ funcName: "fetchDidSucceed"
1547
+ /* FETCH_DID_SUCCEED */
1548
+ ,
1549
+ isReturnValueProblem: true
1550
+ });
1551
+ }
1552
+ }
1553
+ }
1554
+ }
1555
+
1556
+ return fetchResponse;
1557
+ } catch (error) {
1558
+ {
1559
+ logger.error(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
1560
+ }
1561
+
1562
+ for (const plugin of failedFetchPlugins) {
1563
+ await plugin["fetchDidFail"
1564
+ /* FETCH_DID_FAIL */
1565
+ ].call(plugin, {
1566
+ error,
1567
+ event,
1568
+ originalRequest: originalRequest.clone(),
1569
+ request: pluginFilteredRequest.clone()
1570
+ });
1571
+ }
1572
+
1573
+ throw error;
1574
+ }
1575
+ };
1576
+
1577
+ const fetchWrapper = {
1578
+ fetch: wrappedFetch
1579
+ };
1580
+
1581
+ /*
1582
+ Copyright 2019 Google LLC
1583
+ Use of this source code is governed by an MIT-style
1584
+ license that can be found in the LICENSE file or at
1585
+ https://opensource.org/licenses/MIT.
1586
+ */
1587
+ /**
1588
+ * Returns a promise that resolves and the passed number of milliseconds.
1589
+ * This utility is an async/await-friendly version of `setTimeout`.
1590
+ *
1591
+ * @param {number} ms
1592
+ * @return {Promise}
1593
+ * @private
1594
+ */
1595
+
1596
+ function timeout(ms) {
1597
+ return new Promise(resolve => setTimeout(resolve, ms));
1598
+ }
1599
+
1600
+ /*
1601
+ Copyright 2019 Google LLC
1602
+ Use of this source code is governed by an MIT-style
1603
+ license that can be found in the LICENSE file or at
1604
+ https://opensource.org/licenses/MIT.
1605
+ */
1606
+ const MAX_RETRY_TIME = 2000;
1607
+ /**
1608
+ * Returns a promise that resolves to a window client matching the passed
1609
+ * `resultingClientId`. For browsers that don't support `resultingClientId`
1610
+ * or if waiting for the resulting client to apper takes too long, resolve to
1611
+ * `undefined`.
1612
+ *
1613
+ * @param {string} [resultingClientId]
1614
+ * @return {Promise<Client|undefined>}
1615
+ * @private
1616
+ */
1617
+
1618
+ async function resultingClientExists(resultingClientId) {
1619
+ if (!resultingClientId) {
1620
+ return;
1621
+ }
1622
+
1623
+ let existingWindows = await self.clients.matchAll({
1624
+ type: 'window'
1625
+ });
1626
+ const existingWindowIds = new Set(existingWindows.map(w => w.id));
1627
+ let resultingWindow;
1628
+ const startTime = performance.now(); // Only wait up to `MAX_RETRY_TIME` to find a matching client.
1629
+
1630
+ while (performance.now() - startTime < MAX_RETRY_TIME) {
1631
+ existingWindows = await self.clients.matchAll({
1632
+ type: 'window'
1633
+ });
1634
+ resultingWindow = existingWindows.find(w => {
1635
+ if (resultingClientId) {
1636
+ // If we have a `resultingClientId`, we can match on that.
1637
+ return w.id === resultingClientId;
1638
+ } else {
1639
+ // Otherwise match on finding a window not in `existingWindowIds`.
1640
+ return !existingWindowIds.has(w.id);
1641
+ }
1642
+ });
1643
+
1644
+ if (resultingWindow) {
1645
+ break;
1646
+ } // Sleep for 100ms and retry.
1647
+
1648
+
1649
+ await timeout(100);
1650
+ }
1651
+
1652
+ return resultingWindow;
1653
+ }
1654
+
1655
+ /*
1656
+ Copyright 2018 Google LLC
1657
+
1658
+ Use of this source code is governed by an MIT-style
1659
+ license that can be found in the LICENSE file or at
1660
+ https://opensource.org/licenses/MIT.
1661
+ */
1662
+
1663
+ var _private = /*#__PURE__*/Object.freeze({
1664
+ __proto__: null,
1665
+ assert: finalAssertExports,
1666
+ cacheNames: cacheNames,
1667
+ cacheWrapper: cacheWrapper,
1668
+ canConstructReadableStream: canConstructReadableStream,
1669
+ canConstructResponseFromBodyStream: canConstructResponseFromBodyStream,
1670
+ dontWaitFor: dontWaitFor,
1671
+ DBWrapper: DBWrapper,
1672
+ Deferred: Deferred,
1673
+ deleteDatabase: deleteDatabase,
1674
+ executeQuotaErrorCallbacks: executeQuotaErrorCallbacks,
1675
+ fetchWrapper: fetchWrapper,
1676
+ getFriendlyURL: getFriendlyURL,
1677
+ logger: logger,
1678
+ resultingClientExists: resultingClientExists,
1679
+ timeout: timeout,
1680
+ WorkboxError: WorkboxError
1681
+ });
1682
+
1683
+ /*
1684
+ Copyright 2019 Google LLC
1685
+
1686
+ Use of this source code is governed by an MIT-style
1687
+ license that can be found in the LICENSE file or at
1688
+ https://opensource.org/licenses/MIT.
1689
+ */
1690
+ /**
1691
+ * Get the current cache names and prefix/suffix used by Workbox.
1692
+ *
1693
+ * `cacheNames.precache` is used for precached assets,
1694
+ * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to
1695
+ * store `analytics.js`, and `cacheNames.runtime` is used for everything else.
1696
+ *
1697
+ * `cacheNames.prefix` can be used to retrieve just the current prefix value.
1698
+ * `cacheNames.suffix` can be used to retrieve just the current suffix value.
1699
+ *
1700
+ * @return {Object} An object with `precache`, `runtime`, `prefix`, and
1701
+ * `googleAnalytics` properties.
1702
+ *
1703
+ * @memberof module:workbox-core
1704
+ */
1705
+
1706
+ const cacheNames$1 = {
1707
+ get googleAnalytics() {
1708
+ return cacheNames.getGoogleAnalyticsName();
1709
+ },
1710
+
1711
+ get precache() {
1712
+ return cacheNames.getPrecacheName();
1713
+ },
1714
+
1715
+ get prefix() {
1716
+ return cacheNames.getPrefix();
1717
+ },
1718
+
1719
+ get runtime() {
1720
+ return cacheNames.getRuntimeName();
1721
+ },
1722
+
1723
+ get suffix() {
1724
+ return cacheNames.getSuffix();
1725
+ }
1726
+
1727
+ };
1728
+
1729
+ /*
1730
+ Copyright 2019 Google LLC
1731
+
1732
+ Use of this source code is governed by an MIT-style
1733
+ license that can be found in the LICENSE file or at
1734
+ https://opensource.org/licenses/MIT.
1735
+ */
1736
+ /**
1737
+ * Allows developers to copy a response and modify its `headers`, `status`,
1738
+ * or `statusText` values (the values settable via a
1739
+ * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
1740
+ * object in the constructor).
1741
+ * To modify these values, pass a function as the second argument. That
1742
+ * function will be invoked with a single object with the response properties
1743
+ * `{headers, status, statusText}`. The return value of this function will
1744
+ * be used as the `ResponseInit` for the new `Response`. To change the values
1745
+ * either modify the passed parameter(s) and return it, or return a totally
1746
+ * new object.
1747
+ *
1748
+ * @param {Response} response
1749
+ * @param {Function} modifier
1750
+ * @memberof module:workbox-core
1751
+ */
1752
+
1753
+ async function copyResponse(response, modifier) {
1754
+ const clonedResponse = response.clone(); // Create a fresh `ResponseInit` object by cloning the headers.
1755
+
1756
+ const responseInit = {
1757
+ headers: new Headers(clonedResponse.headers),
1758
+ status: clonedResponse.status,
1759
+ statusText: clonedResponse.statusText
1760
+ }; // Apply any user modifications.
1761
+
1762
+ const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit; // Create the new response from the body stream and `ResponseInit`
1763
+ // modifications. Note: not all browsers support the Response.body stream,
1764
+ // so fall back to reading the entire body into memory as a blob.
1765
+
1766
+ const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob();
1767
+ return new Response(body, modifiedResponseInit);
1768
+ }
1769
+
1770
+ /*
1771
+ Copyright 2019 Google LLC
1772
+
1773
+ Use of this source code is governed by an MIT-style
1774
+ license that can be found in the LICENSE file or at
1775
+ https://opensource.org/licenses/MIT.
1776
+ */
1777
+ /**
1778
+ * Claim any currently available clients once the service worker
1779
+ * becomes active. This is normally used in conjunction with `skipWaiting()`.
1780
+ *
1781
+ * @memberof module:workbox-core
1782
+ */
1783
+
1784
+ function clientsClaim() {
1785
+ self.addEventListener('activate', () => self.clients.claim());
1786
+ }
1787
+
1788
+ /*
1789
+ Copyright 2019 Google LLC
1790
+
1791
+ Use of this source code is governed by an MIT-style
1792
+ license that can be found in the LICENSE file or at
1793
+ https://opensource.org/licenses/MIT.
1794
+ */
1795
+ /**
1796
+ * Modifies the default cache names used by the Workbox packages.
1797
+ * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
1798
+ *
1799
+ * @param {Object} details
1800
+ * @param {Object} [details.prefix] The string to add to the beginning of
1801
+ * the precache and runtime cache names.
1802
+ * @param {Object} [details.suffix] The string to add to the end of
1803
+ * the precache and runtime cache names.
1804
+ * @param {Object} [details.precache] The cache name to use for precache
1805
+ * caching.
1806
+ * @param {Object} [details.runtime] The cache name to use for runtime caching.
1807
+ * @param {Object} [details.googleAnalytics] The cache name to use for
1808
+ * `workbox-google-analytics` caching.
1809
+ *
1810
+ * @memberof module:workbox-core
1811
+ */
1812
+
1813
+ function setCacheNameDetails(details) {
1814
+ {
1815
+ Object.keys(details).forEach(key => {
1816
+ finalAssertExports.isType(details[key], 'string', {
1817
+ moduleName: 'workbox-core',
1818
+ funcName: 'setCacheNameDetails',
1819
+ paramName: `details.${key}`
1820
+ });
1821
+ });
1822
+
1823
+ if ('precache' in details && details['precache'].length === 0) {
1824
+ throw new WorkboxError('invalid-cache-name', {
1825
+ cacheNameId: 'precache',
1826
+ value: details['precache']
1827
+ });
1828
+ }
1829
+
1830
+ if ('runtime' in details && details['runtime'].length === 0) {
1831
+ throw new WorkboxError('invalid-cache-name', {
1832
+ cacheNameId: 'runtime',
1833
+ value: details['runtime']
1834
+ });
1835
+ }
1836
+
1837
+ if ('googleAnalytics' in details && details['googleAnalytics'].length === 0) {
1838
+ throw new WorkboxError('invalid-cache-name', {
1839
+ cacheNameId: 'googleAnalytics',
1840
+ value: details['googleAnalytics']
1841
+ });
1842
+ }
1843
+ }
1844
+
1845
+ cacheNames.updateDetails(details);
1846
+ }
1847
+
1848
+ /*
1849
+ Copyright 2019 Google LLC
1850
+
1851
+ Use of this source code is governed by an MIT-style
1852
+ license that can be found in the LICENSE file or at
1853
+ https://opensource.org/licenses/MIT.
1854
+ */
1855
+ /**
1856
+ * Force a service worker to activate immediately, instead of
1857
+ * [waiting](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting)
1858
+ * for existing clients to close.
1859
+ *
1860
+ * @memberof module:workbox-core
1861
+ */
1862
+
1863
+ function skipWaiting() {
1864
+ // We need to explicitly call `self.skipWaiting()` here because we're
1865
+ // shadowing `skipWaiting` with this local function.
1866
+ self.addEventListener('install', () => self.skipWaiting());
1867
+ }
1868
+
1869
+ exports._private = _private;
1870
+ exports.cacheNames = cacheNames$1;
1871
+ exports.clientsClaim = clientsClaim;
1872
+ exports.copyResponse = copyResponse;
1873
+ exports.registerQuotaErrorCallback = registerQuotaErrorCallback;
1874
+ exports.setCacheNameDetails = setCacheNameDetails;
1875
+ exports.skipWaiting = skipWaiting;
1876
+
1877
+ return exports;
1878
+
1879
+ }({}));
1880
+ //# sourceMappingURL=workbox-core.dev.js.map