workbox-broadcast-update.prod.js.map 13.3 KB
{"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.4'] && _();\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"}